Compare commits
21 Commits
4d6067650a
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 0c8782ea75 | |||
| c042adc51b | |||
| 776ad6466f | |||
| 9c98638ec0 | |||
| aa8ac6cad9 | |||
| 3237ce4774 | |||
| 7c5f30df7d | |||
| 5e0a9b526b | |||
| 538aec3ed9 | |||
| 692f532972 | |||
| f460fff406 | |||
| 2c712b06d1 | |||
| 1b09371042 | |||
| 14595651fe | |||
| 8739294a72 | |||
| e07993c536 | |||
| 5cb70d702b | |||
| 9a4ed54cf7 | |||
| 57c423cdb1 | |||
| ecbbb4dd8f | |||
| a58e95a957 |
+13
-1
@@ -72,9 +72,21 @@
|
||||
# DASHBOARD_SESSION_SYNC_MS=30000
|
||||
|
||||
# Hourly database upkeep: a non-blocking WAL checkpoint (the WAL then shrinks
|
||||
# to 64 MB) and PRAGMA optimize. 0 turns it off. Never VACUUMs.
|
||||
# to 64 MB), PRAGMA optimize, the opt-in retention below and a bounded
|
||||
# incremental_vacuum. 0 turns it off. Never a full VACUUM (that is Settings →
|
||||
# Data → Compact, on a click).
|
||||
# DASHBOARD_DB_MAINTAIN_MS=3600000
|
||||
|
||||
# Automatic retention (OFF unless set): finished sessions that started more
|
||||
# than N days ago (1–3650) are purged by the hourly upkeep. Usually set from
|
||||
# Settings → Data → Session cleanup, which writes it to the settings file.
|
||||
# AGENTHUB_RETENTION_DAYS=90
|
||||
|
||||
# Update check interval (ms, default 3600000 = 1 h, minimum 60000). A tick
|
||||
# with no browser connected is skipped; the next browser to connect gets one.
|
||||
# DASHBOARD_UPDATE_CHECK=0 turns the scheduled check off.
|
||||
# DASHBOARD_UPDATE_CHECK_INTERVAL_MS=3600000
|
||||
|
||||
# Poll interval (ms) for Antigravity CLI sessions and tokens, read from agy's
|
||||
# own ~/.gemini/antigravity-cli/conversations/*.db (0 disables; default: 15000).
|
||||
# DASHBOARD_ANTIGRAVITY_POLL_MS=15000
|
||||
|
||||
@@ -11,3 +11,4 @@ client/package-lock.json
|
||||
*.md
|
||||
*.yml
|
||||
*.yaml
|
||||
server/vendor/
|
||||
|
||||
+27
-15
@@ -310,7 +310,7 @@ graph TD
|
||||
|---------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `server/index.js` | Express app setup, middleware, route mounting, static file serving in production, HTTP server creation. Static middleware sets explicit `Cache-Control` headers — `immutable` for `/assets/*`, `no-cache, must-revalidate` for `index.html` / `sw.js` / `manifest.json`, a short revalidation window otherwise — so a rebuild always replaces the in-browser bundle without a hard refresh. Runs a periodic maintenance sweep — cadence derived from `DASHBOARD_STALE_MINUTES` (¼ of the threshold, clamped to 60 s – 5 min, default ~45 min) — that abandons stale sessions with transcript cache eviction and scans active sessions for new compaction entries by reading `sessions.transcript_path` directly (an O(active sessions) lookup; the previous `SELECT DISTINCT json_extract(events.data,'$.transcript_path')` scan grew with the events table and is gone). **Error detection watchdog** runs every 15 seconds: finds active sessions with no recent hook events (>10 s stale), re-reads their transcript files looking for API errors (401 auth, rate limits, quota exhaustion), derives transcript paths from session `cwd` for imported sessions, and marks sessions/agents as `error` when API errors are found — catches cases where the CLI doesn't fire a hook after API errors. The same watchdog also performs **user-interrupt (Esc) recovery**: `Esc` fires no hook, so a cancelled turn would otherwise leave the main agent stuck `working`. It detects this two ways — (a) the transcript's `[Request interrupted by user]` marker, surfaced as `result.pendingInterrupt` from `TranscriptCache` (computed from transcript ordering alone, immune to server/transcript clock skew), and (b) an idle-working fallback for an Esc pressed *before any output* (which writes no marker): when the main agent has been `working` with `current_tool` null and neither a hook event nor the transcript mtime has advanced for `DASHBOARD_WORKING_IDLE_SECONDS` (default 120) — and moves the session to **Waiting** (agent → `waiting`, `awaiting_input_since` stamped) with an `Interrupted` event. Triggers legacy session import (with active-session detection for recently-modified JSONL files) and compaction backfill on startup, plus a boot **liveness reap** — immediately for rows from a previous run and again ~5 s later for rows the startup sync just imported (see the `routes/hooks.js` row) — so sessions that died while the dashboard was down never render as Waiting. Also starts the **Remote Data Sources** sync poller (`startRemoteSourceSync`) that pulls each enabled remote source on an interval — `DASHBOARD_REMOTE_SYNC_MS` (default 60000; 0 disables) — reusing `server/lib/remote-sync.js`. **Graceful shutdown** (SIGTERM/SIGINT) tears down in order: drop realtime clients first (`closeWebSocket` terminates WS clients so their sockets release), then `httpServer.close()` to stop new connections, then `httpServer.closeAllConnections()` to drop lingering keep-alive sockets so `close()` fires promptly, and only **then** close SQLite — inside the `close()` callback, after the HTTP server has drained. Closing the DB before drain made in-flight requests throw `The database connection is not open`; leaving WS/keep-alive sockets open stalled the shutdown until the 5 s force-exit backstop (the "waiting for graceful termination" hang under `node --watch`). A second signal forces an immediate exit |
|
||||
| `server/openapi.js` | OpenAPI 3.0.3 document generator for the backend API (metadata, schemas, endpoint paths), merging supplementary fragments from `server/openapi-extra/` in `createOpenApiSpec()`. Feeds the raw spec endpoint (`/api/openapi.json`), Swagger UI (`/api/docs`), **ReDoc** (`/api/redoc`, served via `server/lib/redoc.js` with a self-hosted bundle — never a CDN), and the committed `openapi.yaml` regenerated by `npm run openapi:yaml` |
|
||||
| `server/lib/redoc.js` | Serves the **ReDoc** API reference (`/api/redoc`) as a self-hosted three-panel rendering of the OpenAPI spec, with the ReDoc bundle served locally from `/api/redoc/redoc.standalone.js` (bundled via the `redoc` dependency, never a CDN) so the reference works fully offline / air-gapped |
|
||||
| `server/lib/redoc.js` | Serves the **ReDoc** API reference (`/api/redoc`) as a self-hosted three-panel rendering of the OpenAPI spec, with the ReDoc bundle served locally from `/api/redoc/redoc.standalone.js` (vendored under `server/vendor/redoc/` — the `redoc` npm package is not a dependency — never a CDN) so the reference works fully offline / air-gapped |
|
||||
| `server/openapi-extra/` | Supplementary OpenAPI path/schema fragments merged into the spec by `createOpenApiSpec()` — covers `cc-config.js`, `push.js`, `run.js`, and `misc.js` route groups |
|
||||
| `server/db.js` | SQLite connection with WAL mode, schema migration (CREATE TABLE IF NOT EXISTS + ALTER TABLE for column additions), all prepared statements as a reusable `stmts` object. Tries `better-sqlite3` first, falls back to `node:sqlite` via `compat-sqlite.js`. Migrations use literal defaults for ALTER TABLE since SQLite does not support expressions like `strftime()` in column defaults added via ALTER TABLE |
|
||||
| `server/compat-sqlite.js` | Compatibility wrapper that gives Node.js built-in `node:sqlite` (`DatabaseSync`) the same API as `better-sqlite3` — pragma, transaction, prepare. Used as automatic fallback when the native module is unavailable (Node 22+) Maps every better-sqlite3 API the server uses — `function` (the `trim_event_data` SQL function `db.js` registers at boot), `stmt.pluck()`, the `readonly`/`fileMustExist` open options — and `db.js` exports the chosen class as `Database` so other SQLite files (agy's conversations) open with the same driver. A plugin install has NO better-sqlite3 build, so this is production there; `server/__tests__/compat-sqlite.test.js` boots `db.js` with better-sqlite3 blocked because the rest of the suite never runs on it. |
|
||||
@@ -1066,7 +1066,7 @@ flowchart TD
|
||||
- Uses Node.js `http` module directly — no dependencies.
|
||||
- Resolution order is **env override → discovery file → default**:
|
||||
- `CLAUDE_DASHBOARD_PORT` forces a single target (no fan-out, no discovery).
|
||||
- Otherwise `server/lib/server-info.js` reads `~/.claude/.agenthub.json`, prunes dead-PID entries, and returns one live `port` per unique `dataDir` (lowest port wins when two instances share `~/.claude/agenthub`). The handler POSTs to each returned port in parallel. The other instance learns of a lane the hooks moved through `broadcastForeignLaneChanges` (`server/routes/lanes.js`): every `DASHBOARD_LANE_SYNC_MS` (2 s) it reads `PRAGMA data_version`, which moves only on another connection's commit, and re-broadcasts each lane whose `updated_at` changed (and `removed` for a vanished one) to its own browsers. Sessions and events are not re-broadcast this way — a page on that instance shows them on its next fetch.
|
||||
- Otherwise `server/lib/server-info.js` reads `~/.claude/.agenthub.json`, prunes dead-PID entries, and returns one live `port` per unique `dataDir` (lowest port wins when two instances share `~/.claude/agenthub`). The handler POSTs to each returned port in parallel. The other instance learns of a lane the hooks moved through `broadcastForeignLaneChanges` (`server/routes/lanes.js`): every `DASHBOARD_LANE_SYNC_MS` (2 s) — while `peersSharingDataDir()` finds another live dashboard on its data dir, which it checks every 30 s — it reads `PRAGMA data_version`, which moves only on another connection's commit, and re-broadcasts each lane whose `updated_at` changed (and `removed` for a vanished one) to its own browsers. Sessions and events are not re-broadcast this way — a page on that instance shows them on its next fetch.
|
||||
- If neither yields anything, the handler falls back to `4820`.
|
||||
- Per-target promises never reject — a dead listener can't starve the others, and the handler can wait on `Promise.all` for clean exit timing.
|
||||
|
||||
@@ -1223,7 +1223,12 @@ common "nothing changed" tick is just a handful of `stat` calls), funnels them
|
||||
through the same `parseSessionFile` + `importSession` pipeline as every other
|
||||
path, and broadcasts `session_created` for newly imported sessions /
|
||||
`session_updated` for grown ones — the same events hooks emit, so the UI
|
||||
refreshes live. All timers and watchers are `unref`'d and best-effort; nothing
|
||||
refreshes live. Two kinds of transcript are not re-parsed: one whose session
|
||||
hooks are feeding **live** (status `active`, newest event a hook's, a hook
|
||||
within `DASHBOARD_SYNC_LIVE_HOOK_MS`, default 5 min) is left until it goes
|
||||
quiet or ends — then caught up once — and one whose session a hook created
|
||||
(no `imported` flag, which `importSession` skips anyway) only has its durable
|
||||
snapshot refreshed, never a parse. All timers and watchers are `unref`'d and best-effort; nothing
|
||||
here blocks shutdown or can take down the server.
|
||||
|
||||
### Upload request sequence
|
||||
@@ -1579,7 +1584,11 @@ re-point if that changes.
|
||||
`DASHBOARD_CODEX_POLL_MS` beat, a first pass over every journal in the
|
||||
background at startup). Each file's read offset and parse state live in the
|
||||
`codex_rollouts` table, so an unchanged file is never re-read and a grown one is
|
||||
read from where it stopped. `token_count` events are summed per `turn_context`
|
||||
read from where it stopped (a pass loads every row's size/mtime in one query).
|
||||
The first pass and one every five minutes walk every journal; the poll's other
|
||||
passes stat only the two newest day folders plus the journals the table saw
|
||||
written in the last hour (or not yet read to the end), so a thread resumed
|
||||
after an hour's quiet in an older folder is picked up by the next full pass. `token_count` events are summed per `turn_context`
|
||||
model — `input_tokens` includes `cached_input_tokens` (stored as input − cached
|
||||
plus cache_read) and `output_tokens` includes reasoning. A **fork** copies its
|
||||
parent's whole history into its own file, token events included, so every total
|
||||
@@ -1654,7 +1663,9 @@ the binary's own proto descriptors.
|
||||
|
||||
**Sessions and tokens** (`server/lib/antigravity-usage.js`,
|
||||
`startAntigravityUsagePoll`, every `DASHBOARD_ANTIGRAVITY_POLL_MS`, default
|
||||
15000, `0` disables). agy writes one SQLite file per conversation,
|
||||
15000, `0` disables; after a pass that read nothing, wrote nothing and left no
|
||||
fresh session to settle it slows to once a minute until one finds work —
|
||||
`server/lib/backoff-poll.js`). agy writes one SQLite file per conversation,
|
||||
`~/.gemini/antigravity-cli/conversations/<conversation id>.db`. Each is opened
|
||||
read-only whenever its mtime (or its non-empty `-wal`'s) changes;
|
||||
`antigravity_conversations` holds the mtime read, so a session the user deleted
|
||||
@@ -1743,7 +1754,8 @@ is ever inferred.
|
||||
## Cursor Sessions
|
||||
|
||||
`server/lib/cursor-usage.js` (`startCursorUsagePoll`, every
|
||||
`DASHBOARD_CURSOR_POLL_MS`, default 15000, `0` disables) reads the agent
|
||||
`DASHBOARD_CURSOR_POLL_MS`, default 15000, `0` disables; idle passes slow it to
|
||||
once a minute like the Antigravity poll) reads the agent
|
||||
transcripts Cursor writes — the CLI (`cursor-agent`) and the editor's agent both —
|
||||
at `~/.cursor/projects/<project slug>/agent-transcripts/<id>/<id>.jsonl`
|
||||
(`AGENTHUB_CURSOR_DIR` overrides `~/.cursor`). Each becomes a `sessions` row with
|
||||
@@ -2225,7 +2237,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 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/update-scheduler.js`** | Ticks the lib every `DASHBOARD_UPDATE_CHECK_INTERVAL_MS` (default 3 600 000 = 1 h, floor 60 000). A tick with no `/ws` browser connected (`getConnectionCount`) is skipped, and the first browser to connect afterwards (`onConnection` in `server/websocket.js`) gets one check 3 s later if the last one is older than the interval; the manual `POST /api/updates/check` is unaffected. 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 (both through the bootstrap's `npmCommand` with `NODE_ENV` dropped — `npmInvocation` in `server/lib/update-check.js` — since the server's `NODE_ENV=production` makes npm omit the client's devDependency build toolchain, and a bare `npm.cmd` is EINVAL under `execFile` on Windows), 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. |
|
||||
| **`UpdateNotifier.tsx`** | Modal. Hydrates from `api.updates.status()` on mount and mirrors the payload back into the local `eventBus` so the Sidebar can listen without a second git fetch. Subscribes to `update_status` WS frames for ongoing sync. Keeps the dismissal key in `localStorage` (`agent-monitor-update-dismissed-sha`) and in React state — the **release tag** when one was read, else the upstream SHA, so a newer release re-opens the prompt while a dismissed one stays dismissed; a window event `dashboard:reset-update-dismissal` from the Sidebar clears both. ESC / backdrop click dismisses. |
|
||||
@@ -2325,7 +2337,7 @@ The same shape is used by `GET /status`, `POST /check`, and the `update_status`
|
||||
- **Branch coverage.** A feature branch or detached HEAD would need branch-aware integration (rebase vs merge vs switch) and merge-conflict handling. That belongs in the user's shell, not in a background daemon — which is why those situations get a printed `git fetch` and no button.
|
||||
- **Ownership.** A plugin-cache install is not ours to rewrite by hand — its directory names are content hashes Claude Code manages. So that case does not fast-forward anything; it calls `claude plugin update` and then re-runs `plugin-bootstrap.js` from the directory that tool produced. The residual limit is only `/reload-plugins`, which is REPL-scoped: an interactive session keeps its old skills/commands until the user reloads, even though the dashboard server has already moved.
|
||||
|
||||
What `--ff-only` buys is the absence of the first three problems inside the supported cases: the move is either a clean fast-forward or it aborts, `npm run setup`/`build` failures reject the request before any restart is scheduled, and the restart itself goes through `self-restart.js`: a server our own service unit runs (its cgroup ends in `/agenthub.service`, or it is our launchd job) is restarted BY that manager (`systemctl restart --no-block`, via `sudo -n` for the server-mode system unit; launchd's KeepAlive after an exit), anything else by the detached `scripts/restart-helper.js`. A detached replacement under a `Restart=always` unit held the port while the unit restarted every 3 s, each start exiting "already running" (v2.7.2).
|
||||
What `--ff-only` buys is the absence of the first three problems inside the supported cases: the move is either a clean fast-forward or it aborts, `npm run setup`/`build` failures reject the request before any restart is scheduled, and the restart itself goes through `self-restart.js`: a server our own service unit runs (its cgroup ends in `/agenthub.service`, or it is our launchd job) is restarted BY that manager (`systemctl restart --no-block`, via `sudo -n` for the server-mode system unit; launchd's KeepAlive after an exit), anything else by the detached `scripts/restart-helper.js`, which appends the new server's stdout/stderr to `data/agenthub-server.log` like `agenthub start` (it used to discard them, so a crash after an update left no stack trace). A detached replacement under a `Restart=always` unit held the port while the unit restarted every 3 s, each start exiting "already running" (v2.7.2).
|
||||
|
||||
---
|
||||
|
||||
@@ -2356,7 +2368,7 @@ graph TD
|
||||
SHELL["Sagi.tsx<br/>shell: open/closed state,<br/>⌘B / Esc, reduced-motion,<br/>navigation"]
|
||||
AVATAR["SagiAvatar.tsx<br/>SVG mascot; data-mood drives CSS;<br/>cursor-tracking pupils"]
|
||||
BUBBLE["SpeechBubble.tsx<br/>bubble"]
|
||||
PANEL["SagiPanel.tsx<br/>status + Needs you + Mute / Clear alerts + Ask box"]
|
||||
PANEL["PetChat.tsx + SagiInfo.tsx<br/>the chat window: status strip, Needs you,<br/>Mute / Clear alerts, local answers, AI chat"]
|
||||
CSS["sagi.css<br/>keyframes + per-mood expressions"]
|
||||
end
|
||||
|
||||
@@ -2386,8 +2398,8 @@ flowchart LR
|
||||
SUB --> DERIVED["derived state<br/>{ mood, status, bubble }"]
|
||||
DERIVED --> AVATAR["SagiAvatar"]
|
||||
DERIVED --> BUBBLE["SpeechBubble"]
|
||||
DERIVED --> PANEL["SagiPanel"]
|
||||
PANEL -->|"unmatched Ask"| ENSURE["POST /api/lanes/ensure<br/>(adopt 'Sagi' lane, cwd = home)"]
|
||||
DERIVED --> PANEL["PetChat (+ SagiInfo)"]
|
||||
PANEL -->|"unmatched question"| ENSURE["POST /api/lanes/ensure<br/>(adopt 'Sagi' lane, cwd = home)"]
|
||||
ENSURE --> START["POST /api/run<br/>(spawn tmux-backed claude<br/>in Sagi lane, initialPrompt=…)"]
|
||||
START --> RUN["/run?laneId=…<br/>(existing Run page picks up<br/>the live run)"]
|
||||
|
||||
@@ -2407,10 +2419,10 @@ The mood state machine in `deriveMood` resolves to a single expression using a f
|
||||
| **`useSagiBrain.ts`** | The **only** consumer of the global `eventBus`. Wires the pure brain to real timers (idle / sleep / stuck), the speech bubble (naming the session it is about; the same pulse again within 8 s joins it as a count), the one-shot `moment` animation, a once-per-browser-session greeting, an idle fidget every minute or so, pat, mute, and clear-alerts (the dismissed ids persist in `localStorage` `agenthub.pet.dismissedErrors`, newest 200). The reducer runs outside React's updater so StrictMode never doubles a pulse. Produces `{ mood, status, attention, bubble, moment }`. |
|
||||
| **`SagiAvatar.tsx`** | Pure presentational SVG mascot. The `data-mood` attribute drives CSS; pupils track the cursor. Rendered at 90×90 px (`size` default, kept in sync with `SAGI_SIZE` in `useSagiPosition.ts`, which is the draggable button's real footprint) through a `viewBox` cropped to the artwork's measured bounding box instead of the exporter's padded `0 0 1280 1280` canvas. Path data is never rescaled, so `MAX_PUPIL_SHIFT` stays in the original 1280-unit space. The `transform-origin` values in `sagi.css` do **not**: an origin on an inner SVG element resolves against `transform-box: view-box`, whose 0,0 sits at the `viewBox` min (`253.5 106`), so those are mascot coordinates **minus that offset**. The root `.sagi-avatar` origin is a percentage on purpose — on the outermost `<svg>` a length would be measured against the 68 px CSS box, and the resulting ~9× overshoot turns every mood animation into a whole-avatar lurch. |
|
||||
| **`SpeechBubble.tsx`** | Pure presentational speech bubble: the line, the session(s) it is about, and an **Open** button for a single one (`workspaceHref` — its live pane, else its replay, else `/sessions/<id>`; never a resume). |
|
||||
| **`SagiPanel.tsx`** | Pure presentational panel: the pet's name (click to rename — `agenthub.pet.names`, synced to the account), a pat button, status readout, a **Needs you** list of errored/waiting sessions by name, Mute and Clear alerts, and the Ask box. |
|
||||
| **`PetChat.tsx`** | The pet's chat window (Ask handoff, or **Chat with …** in the panel), styled as a soft accent gradient with chat bubbles. The first message starts a session of the user's default AI tool (`agenthub.defaultTool`; Claude or Codex — any other tool still opens its pane in the workspace) in the "Sagi" workspace's first free tab; replies are read from the session's transcript every 1.5 s, and follow-ups and menu answers (`PaneMenuCard`) go through a `TerminalView` attached off-screen (`submitToRun`), so no new route exists. The chat is kept in `localStorage` (`agenthub.pet.chat`) while its pane lives; an ended pane is never resumed — the next message starts a new session. |
|
||||
| **`Sagi.tsx`** | Shell component. A pat (the panel's heart, the Ask box, or stroking the pet — four left/right turns of the pointer over it within 1.2 s) shows hearts and a line ON the pet, so it reads while the panel or chat is open. Mounted once in `client/src/components/Layout.tsx` as a sibling of `UpdateNotifier`. Owns open/closed state, the `⌘B` / `Esc` shortcuts, reduced-motion detection, and navigation. |
|
||||
| **`intents.ts`** | Local Q&A over the cached status snapshot, in English and Vietnamese keywords, answering in the UI language and naming the sessions it counts (also: who are you, hello, thanks, pat). Queries that don't match a local intent open `PetChat`; with a default tool it cannot read back, `Sagi.tsx` instead calls `POST /api/lanes/ensure` (adopting the "Sagi" lane whose cwd defaults to `$HOME`), then `POST /api/run` to spawn a fresh tmux-backed `claude` session in that lane with the prompt as its `initialPrompt`, then navigates to `/run?laneId=…&autostart=1` so the live run is observable. |
|
||||
| **`SagiInfo.tsx`** | Pure presentational pieces of the chat window: `PetNameButton` (click to rename — `agenthub.pet.names`, synced to the account) and `SagiInfo`, the status strip under the header — live / waiting / errored and the connection always shown; expanded (by default while something needs you) a **Needs you** list of errored/waiting sessions by name, Mute and Clear alerts. |
|
||||
| **`PetChat.tsx`** | The pet's whole UI — clicking the pet opens it (there is no separate panel): header (name, pat heart, Open in workspace, New chat, close), the `SagiInfo` strip, then the conversation. Before a chat runs, a question `intents.ts` can answer is answered in place (`onLocal`); anything else goes to the AI. Styled as a soft accent gradient with chat bubbles. The first message starts a session of the user's default AI tool (`agenthub.defaultTool`; Claude or Codex — any other tool still opens its pane in the workspace) in the "Sagi" workspace's first free tab; replies are read from the session's transcript every 1.5 s, and follow-ups and menu answers (`PaneMenuCard` — numbered menus and Claude's unnumbered folder-trust prompt alike) go through a `TerminalView` attached off-screen (`submitToRun`), so no new route exists. The chat is kept in `localStorage` (`agenthub.pet.chat`) while its pane lives, so closing and reopening the window continues it; **New chat** stops that session (`DELETE /api/run/:id?archive=1`, asking first only mid-reply); an ended pane is never resumed — the next message starts a new session. |
|
||||
| **`Sagi.tsx`** | Shell component. A pat (the chat's heart, a typed pat, or stroking the pet — four left/right turns of the pointer over it within 1.2 s) shows hearts and a line ON the pet, so it reads while the chat is open. Mounted once in `client/src/components/Layout.tsx` as a sibling of `UpdateNotifier`. Owns the chat's open/closed state, the `⌘B` / `Esc` shortcuts, reduced-motion detection, and navigation. |
|
||||
| **`intents.ts`** | Local Q&A over the cached status snapshot, in English and Vietnamese keywords, answering in the UI language and naming the sessions it counts (also: who are you, hello, thanks, pat). Queries that don't match a local intent go to `PetChat`'s AI session; with a default tool it cannot read back, `Sagi.tsx` instead calls `POST /api/lanes/ensure` (adopting the "Sagi" lane whose cwd defaults to `$HOME`), then `POST /api/run` to spawn a fresh tmux-backed `claude` session in that lane with the prompt as its `initialPrompt`, then navigates to `/run?laneId=…&autostart=1` so the live run is observable. |
|
||||
| **`quips.ts`** | Mood/pulse → phrase pools, plus greetings and pat lines, read from `settings:sagi.{quips,greet,pat}` so they follow the UI language. |
|
||||
| **`prefs.ts`** | `localStorage`-backed enabled / muted / pet / size / nickname preferences with cross-tab sync; `petName` = nickname, else the worn pet's own name, else Sagi. |
|
||||
| **`sagi.css`** | Keyframes and per-mood expressions (`data-mood`), plus the one-shot moments (`data-moment`: jump, wave, fail, wait, review) on Sagi's art and an uploaded image. |
|
||||
|
||||
+407
-82
@@ -1,6 +1,6 @@
|
||||
# Installation
|
||||
|
||||
A step-by-step guide to get AgentHub — the local control surface for Claude Code agents — up and running on your machine, with optional sections for importing history and running in a container.
|
||||
The one install-and-setup guide for AgentHub — the local control surface for Claude Code agents: the plugin install, a checkout install, configuration, the database, importing history, and troubleshooting. (`SETUP.md` is only a pointer here now.)
|
||||
|
||||
## Fastest path — install it as a Claude Code plugin
|
||||
|
||||
@@ -17,17 +17,20 @@ on PATH — no clone, no `npm run setup`, no
|
||||
result and `/agenthub-open` to build the UI and get the URL.
|
||||
|
||||
Requires Node **>= 22.5** (a plugin install has no native `better-sqlite3`, so
|
||||
the server stores data through `node:sqlite`). Full behavior, including the
|
||||
uninstall cleanup (`agenthub uninstall`), is in [`docs/PLUGINS.md`](docs/PLUGINS.md).
|
||||
the server stores data through `node:sqlite`), plus `git` and `tmux` from
|
||||
[Step 0](#step-0--system-packages). Full behavior, including the uninstall
|
||||
cleanup (`agenthub uninstall`), is in [`docs/PLUGINS.md`](docs/PLUGINS.md). If
|
||||
the dashboard never comes up, see
|
||||
[Plugin bootstrap never comes up](#plugin-bootstrap-never-comes-up).
|
||||
|
||||
Follow the steps below instead when you want a checkout — to develop the
|
||||
dashboard, run it from source, or stay on Node 20.
|
||||
dashboard or run it from source.
|
||||
|
||||
## Requirements
|
||||
|
||||
| Requirement | Version | Notes |
|
||||
|---|---|---|
|
||||
| Node.js | 20+ (22+ recommended) | Required for server and client |
|
||||
| Node.js | **22.5+** | Required for server and client (`node:sqlite`). Node 20 is end-of-life and unsupported |
|
||||
| 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) |
|
||||
@@ -76,7 +79,7 @@ Check it:
|
||||
```bash
|
||||
tmux -V # e.g. tmux 3.4
|
||||
git --version
|
||||
node -v # v20.x / v22.x / v24.x
|
||||
node -v # v22.5+ / v24.x
|
||||
```
|
||||
|
||||
Once the server is up you can ask it directly — this is the same probe the
|
||||
@@ -113,8 +116,8 @@ brew install node git tmux # Node >= 22.5 for the plugin install (nvm work
|
||||
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc # where the plugin puts `agenthub`
|
||||
```
|
||||
|
||||
- **Node:** a plugin install needs **>= 22.5** (it stores data through
|
||||
`node:sqlite`); a checkout still runs on Node 20. The `agenthub` launcher
|
||||
- **Node:** **>= 22.5** (the plugin stores data through `node:sqlite`; a
|
||||
checkout needs the same). The `agenthub` launcher
|
||||
pins the node that installed it and falls back to `node` on `PATH` when a
|
||||
`brew upgrade` or `nvm` switch deletes that binary.
|
||||
- **Starts at login once you turn it on (LaunchAgent).** Off by default; with
|
||||
@@ -172,24 +175,20 @@ cd AgentHub
|
||||
## Step 2 — Install dependencies
|
||||
|
||||
```bash
|
||||
npm run setup
|
||||
npm run setup # or: make setup
|
||||
```
|
||||
|
||||
This installs all server and client dependencies, plus the VS Code extension, and links the `agenthub` CLI.
|
||||
This runs `npm install` (whose `postinstall` hook installs the client's
|
||||
dependencies in `client/`), installs `client/` once more explicitly, and links
|
||||
the `agenthub` CLI (`npm link`; if that has no permission it prints how to link
|
||||
it by hand). A plain `npm install` is enough to build and run the dashboard —
|
||||
only the CLI link is missing.
|
||||
|
||||
A plain root install already covers server **and** client — a `postinstall` hook installs the client dependencies automatically, so this alone is enough to build and run the dashboard:
|
||||
With `--ignore-scripts` the `postinstall` hook is skipped; install the client
|
||||
yourself with `npm --prefix client install`.
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
`npm run setup` additionally installs the VS Code extension and links the `agenthub` CLI. (If you install with `--ignore-scripts`, the `postinstall` hook is skipped — run `cd client && npm install` manually in that case.)
|
||||
|
||||
Or via Makefile:
|
||||
|
||||
```bash
|
||||
make setup
|
||||
```
|
||||
`better-sqlite3` gyp/compile warnings here are harmless — see
|
||||
[Troubleshooting](#better-sqlite3-errors-during-npm-install--npm-run-setup).
|
||||
|
||||
---
|
||||
|
||||
@@ -234,7 +233,7 @@ After starting a Claude Code session, you should see:
|
||||
- **Dashboard** — stats updating in real-time
|
||||
- **Settings page** — data export and cleanup tools on the Dashboard tab; Claude Code's model pricing rules, hook configuration status and CLAUDE_HOME on **Settings → Claude Code → Overview**
|
||||
|
||||
If nothing appears after 30 seconds, see [SETUP.md](./SETUP.md#troubleshooting).
|
||||
If nothing appears after 30 seconds, see [Troubleshooting](#no-sessions-appearing-after-starting-claude-code).
|
||||
|
||||
### PWA install (optional)
|
||||
|
||||
@@ -246,57 +245,110 @@ The dashboard is a Progressive Web App. After opening it in a supported browser
|
||||
|
||||
---
|
||||
|
||||
## Step 5 — (Optional) Import existing Claude Code history
|
||||
## Step 5 — (Optional) Importing existing Claude Code history
|
||||
|
||||
The server **automatically imports** every session under
|
||||
`~/.claude/projects/` on startup, so if you've used Claude Code on this
|
||||
machine before, your historical sessions, agents, events, token counts,
|
||||
and cost totals should already be visible in the Sessions list.
|
||||
The dashboard automatically imports sessions from `~/.claude/projects/` on
|
||||
**every startup**, so if Claude Code has been used on this machine, you'll
|
||||
see history immediately after the first launch. If you need to bring in
|
||||
history from another machine, from a backup, or just force a rescan, use
|
||||
**Settings → Import History** in the UI — it's a guided, drag-and-drop
|
||||
experience with live progress.
|
||||
|
||||
To bring in history from another machine, a backup, or a `.tar.gz`
|
||||
archive a teammate sent you, use **Settings → Import History** in the
|
||||
UI. It supports three modes:
|
||||
### Pick the right mode
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
UI["Settings →<br/>Import History"] --> M1["Rescan default folder<br/>~/.claude/projects"]
|
||||
UI --> M2["Scan a folder<br/>any absolute path"]
|
||||
UI --> M3["Upload files<br/>.jsonl / .zip / .tar.gz / .gz"]
|
||||
M1 --> P["Same parser as live<br/>hook ingestion"]
|
||||
M2 --> P
|
||||
M3 --> P
|
||||
P --> DB[("SQLite<br/>sessions + tokens + cost")]
|
||||
flowchart TD
|
||||
Q["Where is the history?"] --> Q1{Is it on this machine<br/>under ~/.claude/projects?}
|
||||
Q1 -->|yes, and I just want<br/>to re-scan| M1["Mode: Rescan default folder<br/>one click"]
|
||||
Q1 -->|yes, but in another folder<br/>on this machine| M2["Mode: Scan a folder<br/>paste the absolute path"]
|
||||
Q1 -->|no — it's on another machine<br/>or in an archive file| M3["Mode: Upload files<br/>drag-drop JSONL or archive"]
|
||||
|
||||
style UI fill:#a855f7,stroke:#c084fc,color:#fff
|
||||
style P fill:#f59e0b,stroke:#fbbf24,color:#000
|
||||
style DB fill:#10b981,stroke:#34d399,color:#fff
|
||||
M3 --> PREP["Archive source:<br/>tar -czf claude-history.tar.gz<br/>-C ~/.claude projects"]
|
||||
|
||||
style M1 fill:#10b981,stroke:#34d399,color:#fff
|
||||
style M2 fill:#f59e0b,stroke:#fbbf24,color:#000
|
||||
style M3 fill:#a855f7,stroke:#c084fc,color:#fff
|
||||
```
|
||||
|
||||
Re-imports are idempotent: sessions are deduplicated by UUID and
|
||||
compaction baselines preserve pre-compaction token totals, so running
|
||||
the importer twice never double-counts tokens or cost.
|
||||
### Step-by-step: moving history from one machine to another
|
||||
|
||||
Verify it worked by opening the **Analytics** page and checking that
|
||||
per-model token totals and estimated cost look correct. Full walkthrough
|
||||
with per-OS archive commands in
|
||||
[SETUP.md → Importing existing Claude Code history](./SETUP.md#importing-existing-claude-code-history).
|
||||
### Optional: tune import limits
|
||||
**On the source machine**, bundle the projects folder:
|
||||
|
||||
If you regularly import very large archives, these environment variables
|
||||
can be raised (the defaults are generous for typical use):
|
||||
```bash
|
||||
# macOS / Linux
|
||||
tar -czf claude-history.tar.gz -C ~/.claude projects
|
||||
|
||||
| Variable | Default | Purpose |
|
||||
| --------------------------------- | ------- | ----------------------------------------------------------- |
|
||||
| `AGENTHUB_IMPORT_MAX_BYTES` | 1 GB | Maximum size per uploaded file |
|
||||
| `AGENTHUB_IMPORT_MAX_FILES` | 2000 | Maximum files per upload request |
|
||||
| `AGENTHUB_IMPORT_MAX_EXTRACT_BYTES` | 4 GB | Ceiling on uncompressed bytes per archive (zip-bomb guard) |
|
||||
# Windows (PowerShell, via built-in tar)
|
||||
tar -czf claude-history.tar.gz -C "$env:USERPROFILE\.claude" projects
|
||||
```
|
||||
|
||||
Set them before `npm run dev` or `npm start`:
|
||||
Transfer the resulting `claude-history.tar.gz` to the destination machine
|
||||
however you like — AirDrop, `scp`, USB, cloud storage.
|
||||
|
||||
**On the destination machine**, in the dashboard:
|
||||
|
||||
1. Open **Settings → Import History**.
|
||||
2. Pick **Upload files** (the third tab).
|
||||
3. Drag the archive onto the drop zone.
|
||||
4. Click **Upload & Import** and watch the progress.
|
||||
5. When the green result card appears, open **Analytics → Cost** to confirm
|
||||
per-model token totals and estimated cost.
|
||||
|
||||
### Supported inputs
|
||||
|
||||
Any of the following can be dropped onto the upload zone or found inside a
|
||||
folder given to **Scan a folder**:
|
||||
|
||||
- `.jsonl` — session transcripts
|
||||
- `.meta.json` — subagent metadata sidecars
|
||||
- `.zip` — extracted with path-traversal protection
|
||||
- `.tar`, `.tar.gz`, `.tgz` — extracted via the `tar` package
|
||||
- `.gz` — single gzipped JSONL (streaming-decompressed)
|
||||
|
||||
### Accuracy guarantees
|
||||
|
||||
- **Idempotent** — re-importing never double-counts. Sessions are
|
||||
deduplicated by UUID.
|
||||
- **Cost-preserving** — the `token_usage` table uses `baseline_*` columns
|
||||
to preserve pre-compaction token totals, so re-ingesting a compacted
|
||||
transcript never erases historical cost.
|
||||
- **Same parser as live** — `parseSessionFile` + `importSession` is the
|
||||
single source of truth for both hook-driven ingestion and manual
|
||||
import, so imported numbers match captured numbers exactly.
|
||||
|
||||
### Safety
|
||||
|
||||
Archive extraction is hardened against path traversal and archive bombs.
|
||||
The defaults are generous for real-world transcripts but tight enough to
|
||||
stop obvious attacks. If you regularly import very large archives, raise them
|
||||
before `npm run dev` or `npm start` (also listed under
|
||||
[Environment variables](#environment-variables)):
|
||||
|
||||
| Variable | Default | Purpose |
|
||||
| ----------------------------------- | ------- | ---------------------------------------------------------- |
|
||||
| `AGENTHUB_IMPORT_MAX_BYTES` | 1 GB | Maximum size per uploaded file |
|
||||
| `AGENTHUB_IMPORT_MAX_FILES` | 2000 | Maximum files per upload request |
|
||||
| `AGENTHUB_IMPORT_MAX_EXTRACT_BYTES` | 4 GB | Ceiling on uncompressed bytes per archive (zip-bomb guard) |
|
||||
|
||||
```bash
|
||||
AGENTHUB_IMPORT_MAX_EXTRACT_BYTES=17179869184 npm start # allow 16 GB extraction
|
||||
```
|
||||
|
||||
### CLI alternative
|
||||
|
||||
For scripts and automation, the same logic runs from the terminal:
|
||||
|
||||
```bash
|
||||
# Import (or re-import) everything under ~/.claude/projects
|
||||
npm run import-history
|
||||
|
||||
# Dry run — show what would be imported without writing
|
||||
node scripts/import-history.js --dry-run
|
||||
|
||||
# Scope to a single project dir
|
||||
node scripts/import-history.js --project my-project
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Production mode
|
||||
@@ -328,44 +380,260 @@ and, for plugin installs, [`docs/PLUGINS.md` → Auto-start on boot](docs/PLUGIN
|
||||
|
||||
---
|
||||
|
||||
## Optional: Agent extension packs
|
||||
## How it works
|
||||
|
||||
This repository includes extension packs for both Claude Code and Codex.
|
||||
AgentHub integrates with Claude Code through its native hook system. When Claude Code performs any action (session start, tool use, turn completion, subagent finish, session exit), it fires a hook that calls a small Node.js script bundled with this project. That script forwards the event over HTTP to the dashboard server, which stores it in SQLite and broadcasts it to the browser over WebSocket.
|
||||
|
||||
- Claude Code loads project extensions from:
|
||||
```
|
||||
Claude Code → hook fires → hook-handler.js → POST /api/hooks/event
|
||||
↓
|
||||
Browser ← WebSocket broadcast ← Express server ← SQLite
|
||||
```
|
||||
|
||||
No extra Claude Code configuration is required in the normal host-run path — when you start the dashboard with `npm run dev` or `npm start`, the server configures the hooks automatically on startup (or, with the `agenthub` plugin enabled in `~/.claude/settings.json`, removes the checkout's copies — the plugin's own hooks already run, and both would post every event twice). Container deployments are the exception: after the container is up, run `npm run install-hooks` on the host so Claude Code points at `http://localhost:4820`.
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
### Hook auto-installation
|
||||
|
||||
When the dashboard is running directly on the host, the server writes the following to `~/.claude/settings.json` every time it starts:
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"SessionStart": [{ "hooks": [{ "type": "command", "command": "node \"/path/to/scripts/hook-handler.js\" SessionStart" }] }],
|
||||
"PreToolUse": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "node \"/path/to/scripts/hook-handler.js\" PreToolUse" }] }],
|
||||
"PostToolUse": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "node \"/path/to/scripts/hook-handler.js\" PostToolUse" }] }],
|
||||
"Stop": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "node \"/path/to/scripts/hook-handler.js\" Stop" }] }],
|
||||
"SubagentStop": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "node \"/path/to/scripts/hook-handler.js\" SubagentStop" }] }],
|
||||
"Notification": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "node \"/path/to/scripts/hook-handler.js\" Notification" }] }],
|
||||
"SessionEnd": [{ "hooks": [{ "type": "command", "command": "node \"/path/to/scripts/hook-handler.js\" SessionEnd" }] }]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> Note: `SessionStart` and `SessionEnd` hooks do not support the `matcher` field — they fire unconditionally on every session start and exit.
|
||||
|
||||
Existing hooks in that file are preserved. The dashboard only adds or updates entries that contain `hook-handler.js`.
|
||||
|
||||
To re-run hook installation manually:
|
||||
|
||||
```bash
|
||||
npm run install-hooks
|
||||
```
|
||||
|
||||
> [!TIP]
|
||||
> Container note: if you run the dashboard inside a container (a Dev Container, Codespaces, or your own image), do not install hooks from in there — the hook path a container writes points at the container filesystem, not the host. Run `npm run install-hooks` on the host instead. As a safeguard (issue #193) the installer **detects container execution and refuses to run** (exiting non-zero) so it can never poison a bind-mounted host `~/.claude`. If Claude Code itself genuinely runs inside that container, override with `AGENTHUB_ALLOW_CONTAINER_HOOKS=1 npm run install-hooks`.
|
||||
|
||||
> [!NOTE]
|
||||
> Prefer a ready-made dev environment? This repo ships an **optional** Dev Container (`.devcontainer/`) for VS Code / GitHub Codespaces — Node 22, native build tools for `better-sqlite3`, Python, and ports `4820`/`5173` preconfigured. It's purely opt-in and changes nothing for host-based development. See [`.devcontainer/README.md`](.devcontainer/README.md). (Hooks remain host-side there too.)
|
||||
|
||||
### Environment variables
|
||||
|
||||
| Variable | Default | Description |
|
||||
|---|---|---|
|
||||
| `DASHBOARD_PORT` | `4820` | Port the Express server listens on |
|
||||
| `CLAUDE_DASHBOARD_PORT` | `4820` | Port the hook handler uses when posting events to the dashboard |
|
||||
| `DASHBOARD_DB_PATH` | `data/dashboard.db` | Path to the SQLite database file |
|
||||
| `NODE_ENV` | `development` | Set to `production` to serve built client |
|
||||
| `DASHBOARD_CLIENT_DIST` | `client/dist` | Directory the built UI is served from in production. Set by the `agenthub` plugin bootstrap to its own runtime dir, because the plugin cache is replaced on every update |
|
||||
| `AGENTHUB_IMPORT_MAX_BYTES` | `1073741824` (1 GB) | Maximum size per uploaded file on `/api/import/upload` |
|
||||
| `AGENTHUB_IMPORT_MAX_FILES` | `2000` | Maximum number of files per upload request |
|
||||
| `AGENTHUB_IMPORT_MAX_EXTRACT_BYTES` | `4294967296` (4 GB) | Maximum uncompressed bytes any single archive is allowed to expand to (zip-bomb defense) |
|
||||
| `DASHBOARD_DATA_DIR` | `~/.claude/agenthub` | AgentHub's data dir; a plugin install keeps its runtime (deps, UI build, logs) in `runtime/` under it |
|
||||
|
||||
Example with a custom port:
|
||||
|
||||
```bash
|
||||
DASHBOARD_PORT=9000 npm run dev
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> You usually do **not** need to set `DASHBOARD_PORT` manually. `npm run dev` is wrapped by `scripts/dev.js`, which probes both `127.0.0.1` and `::1` (so an SSH `LocalForward` bound to one loopback can't slip past) and picks the first free port in `4820–4859` automatically. The chosen port is propagated to the Vite dev proxy via `DASHBOARD_PORT`, and the Express server writes it to `~/.claude/.agenthub.json` so the Claude Code hook handler discovers it without any env var.
|
||||
>
|
||||
> Multiple dashboards can run side by side — for example two `npm run dev` checkouts, or `npm run dev` alongside `npm start`. Each one appends its `{port, pid, startedAt}` entry to the discovery file, and `scripts/hook-handler.js` fan-outs every hook event to every live entry, so both UIs keep their real-time stream.
|
||||
>
|
||||
> Setting `CLAUDE_DASHBOARD_PORT=N` overrides discovery entirely and forces the hook handler to a single port — useful for tests and container setups where the in-process discovery file isn't reachable from the host.
|
||||
>
|
||||
> If you bypass the picker (e.g. `npm run dev:raw`, container builds, or anything else that calls `node server/index.js` directly), make sure your client is built / proxied against the port the server actually bound.
|
||||
|
||||
### Agent extension setup (Claude Code + Codex)
|
||||
|
||||
This repository ships extension files for both agent ecosystems:
|
||||
|
||||
- Claude Code:
|
||||
- `CLAUDE.md`
|
||||
- `.claude/rules/`
|
||||
- `skills/` (shipped as the `agenthub` plugin's skills)
|
||||
- Codex project packs live under `.codex/`:
|
||||
- `.claude/rules/*`
|
||||
- `skills/*` (the `agenthub` plugin's own skills)
|
||||
- Codex:
|
||||
- `AGENTS.md`
|
||||
- `.codex/rules/`
|
||||
- `.codex/agents/`
|
||||
- `.codex/skills/`
|
||||
- `.codex/config.toml`
|
||||
- `.codex/rules/default.rules`
|
||||
- `.codex/agents/*`
|
||||
- `.codex/skills/*`
|
||||
|
||||
See [`.codex/README.md`](./.codex/README.md) for Codex extension details.
|
||||
|
||||
### PWA configuration (optional)
|
||||
|
||||
The dashboard ships as a Progressive Web App. No configuration is required — its manifest and service worker are included out of the box.
|
||||
|
||||
**Customising the manifest:** Edit `client/public/manifest.json`. Common fields to change:
|
||||
|
||||
- `name` / `short_name` — displayed on the home screen / dock
|
||||
- `theme_color` — address bar / title bar tint (default: `#6366f1`)
|
||||
- `background_color` — splash screen background
|
||||
- `start_url` — entry point when launched from home screen
|
||||
|
||||
**Updating the service worker cache:** The SW has a `CACHE_NAME` constant (e.g. `dashboard-v2`). After deploying new assets, bump the version string to force browsers to re-fetch — though for the dashboard this is rarely needed: hashed `/assets/*` URLs are immutable per build, everything else is fetched network-first with cache fallback, and a `controllerchange` listener in the client reloads the page exactly once when a new SW takes over, so a rebuild propagates without a hard refresh.
|
||||
|
||||
**Browser support:** PWA install prompts appear in Chrome 107+, Edge 107+, and Firefox 110+ (desktop and Android). Safari supports `apple-mobile-web-app-capable` for iOS home-screen mode but does not show an install banner.
|
||||
|
||||
**Verifying PWA status:** Open DevTools → Application → Manifest to confirm the manifest loads. Check the Service Workers section to verify the SW is registered and active. The Lighthouse PWA audit should pass all core checks.
|
||||
|
||||
---
|
||||
|
||||
## Database
|
||||
|
||||
The SQLite database is created automatically on first run (`data/dashboard.db` in a checkout, unless `DASHBOARD_DB_PATH` says otherwise). The directory is created if it does not exist. The database uses WAL mode for concurrent reads and foreign keys for referential integrity.
|
||||
|
||||
### Clear all data
|
||||
|
||||
To remove all sessions, agents, events, and token usage (useful after running seed data or for a clean start):
|
||||
|
||||
```bash
|
||||
npm run clear-data
|
||||
```
|
||||
|
||||
### Data management via Settings page
|
||||
|
||||
The Settings page (`/settings`) provides a UI for the following. **Model Pricing**
|
||||
and **Hook Configuration** are not on its Dashboard tab: they sit under the
|
||||
Claude Code tab's **Overview** (Settings → Claude Code → Overview), beside
|
||||
CLAUDE_HOME; Codex (its Overview) and Antigravity have their own pricing and
|
||||
hooks in their own tabs.
|
||||
|
||||
- **Model Pricing** — view and edit per-model cost rates, reset to defaults, add custom models
|
||||
- **Hook Configuration** — check which hooks are installed and reinstall them
|
||||
- **Data Export** — download all sessions, agents, events, and pricing as a JSON file
|
||||
- **Session Cleanup** — abandon stale active sessions after N hours, purge old completed sessions after N days
|
||||
- **Clear All Data** — remove all sessions, agents, events, and token usage
|
||||
- **Data Management** and **About** sections render with loading placeholders while server info is being fetched, so the page is always fully navigable
|
||||
|
||||
### Seed demo data
|
||||
|
||||
To populate the dashboard with sample sessions, agents, and events for UI exploration:
|
||||
|
||||
```bash
|
||||
npm run seed
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Scripts reference
|
||||
|
||||
| Script | Command | Description |
|
||||
|---|---|---|
|
||||
| `setup` | `npm run setup` | Install all dependencies (server + client) |
|
||||
| `dev` | `npm run dev` | Start server + client in development mode |
|
||||
| `start` | `npm start` | Start server in production mode |
|
||||
| `build` | `npm run build` | Build the React client to `client/dist/` |
|
||||
| `install-hooks` | `npm run install-hooks` | Write Claude Code hooks to `~/.claude/settings.json` |
|
||||
| `clear-data` | `npm run clear-data` | Delete all data from the database |
|
||||
| `seed` | `npm run seed` | Insert demo sessions/agents/events |
|
||||
| `import-history` | `npm run import-history` | Import legacy sessions from `~/.claude/` (also runs on startup) |
|
||||
| `claude` | Claude CLI | Uses `CLAUDE.md`, `.claude/rules`, and `.claude/skills` automatically |
|
||||
| `test` | `npm test` | Run all server and client tests |
|
||||
| `test:server` | `npm run test:server` | Run server integration tests only |
|
||||
| `test:client` | `npm run test:client` | Run client unit tests only |
|
||||
| `format` | `npm run format` | Format all files with Prettier |
|
||||
| `format:check` | `npm run format:check` | Check formatting without writing |
|
||||
|
||||
---
|
||||
|
||||
## Makefile targets
|
||||
|
||||
All npm scripts are mirrored as `make` targets for convenience. Run `make help` to list them:
|
||||
|
||||
```bash
|
||||
make help
|
||||
```
|
||||
|
||||
Commonly used targets:
|
||||
|
||||
| Make target | Equivalent npm command | Description |
|
||||
|---|---|---|
|
||||
| `make setup` | `npm run setup` | Install all dependencies (root + client) |
|
||||
| `make dev` | `npm run dev` | Start server + client in watch mode |
|
||||
| `make build` | `npm run build` | Build the React client for production |
|
||||
| `make start` | `npm start` | Start the production server |
|
||||
| `make prod` | `npm run build && npm start` | Build then start in one step |
|
||||
| `make test` | `npm test` | Run all tests (server + client) |
|
||||
| `make test-server` | `npm run test:server` | Run server tests only |
|
||||
| `make test-client` | `npm run test:client` | Run client tests only |
|
||||
| `make format` | `npm run format` | Format all files with Prettier |
|
||||
| `make format-check` | `npm run format:check` | Check formatting without writing |
|
||||
| `make seed` | `npm run seed` | Load demo data |
|
||||
| `make clear-data` | `npm run clear-data` | Delete all data rows |
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### `npm run setup` shows `better-sqlite3` errors
|
||||
### Plugin bootstrap never comes up
|
||||
|
||||
This is expected and **non-fatal**. `better-sqlite3` is a native C++ module listed as an optional dependency. If prebuilt binaries are not available for your Node version or platform, npm will print gyp/compilation errors but still complete successfully.
|
||||
The plugin's `SessionStart` hook only checks a fast path and hands the real
|
||||
work (npm install, UI build, server start) to a detached background worker, so
|
||||
a failure there does not show in the session. When the worker's last run
|
||||
failed, the next session start prints a one-time **AgentHub:** message naming
|
||||
the log to read. Everything is logged under `~/.claude/agenthub/runtime/`:
|
||||
|
||||
At runtime the server uses this fallback chain:
|
||||
| File | What it holds |
|
||||
|---|---|
|
||||
| `bootstrap.log` | Each bootstrap step and why it stopped (Node too old, install failed, superseded build, …) |
|
||||
| `npm-install.log` | npm's output for the runtime dependency install |
|
||||
| `client-build.log` | The dashboard UI build (the API still works when only this fails) |
|
||||
| `server.log` | The server's own output, when it was started detached |
|
||||
| `last-failure.json` | The last failure the session-start message reports (removed once a bootstrap succeeds) |
|
||||
|
||||
1. **`better-sqlite3`** — used when prebuilt binaries are available (Node 20/22/24 on Windows x64, macOS arm64/x64, Linux x64/arm64)
|
||||
2. **`node:sqlite`** — Node.js built-in SQLite module, used automatically on Node 22+ when `better-sqlite3` is unavailable
|
||||
Then run `/agenthub-doctor` from Claude Code — it checks Node, the runtime
|
||||
dependencies, the server and the service unit, and names the fix for each
|
||||
failing row. `/agenthub-update` re-runs the bootstrap in the foreground with its
|
||||
output visible. The most common causes: Node older than 22.5 (`node -v` in the
|
||||
shell Claude Code was started from), no network or a proxy blocking the npm
|
||||
registry (`npm-install.log`), and a port held by another program (`server.log`,
|
||||
see [Port 4820 already in use](#port-4820-already-in-use)).
|
||||
|
||||
If you see an error box at startup saying *"SQLite backend not available"*, either:
|
||||
### `better-sqlite3` errors during `npm install` / `npm run setup`
|
||||
|
||||
- **Upgrade to Node.js 22+** (recommended — zero native dependencies needed), or
|
||||
- **Install build tools** so `better-sqlite3` can compile from source:
|
||||
- **Windows:** `npm install -g windows-build-tools` or install [Visual Studio Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) with the C++ workload
|
||||
- **macOS:** `xcode-select --install`
|
||||
- **Linux:** `sudo apt install python3 make g++` (Debian/Ubuntu) or equivalent
|
||||
Only a **checkout** install sees these — the plugin installs with
|
||||
`--ignore-scripts` and never builds `better-sqlite3`. They are **harmless**:
|
||||
`better-sqlite3` is an optional dependency, and when it cannot be built npm
|
||||
skips it and the server uses Node's built-in `node:sqlite` (Node 22.5+). You do
|
||||
**not** need Python, Visual Studio Build Tools or a C++ compiler.
|
||||
|
||||
Then run: `npm rebuild better-sqlite3`
|
||||
To build it anyway (it is used when present), install a toolchain and run
|
||||
`npm rebuild better-sqlite3`:
|
||||
|
||||
- **Windows:** [Visual Studio Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) with the C++ workload
|
||||
- **macOS:** `xcode-select --install`
|
||||
- **Linux:** `sudo apt install python3 make g++` (Debian/Ubuntu) or equivalent
|
||||
|
||||
### "SQLite backend not available" error on startup
|
||||
|
||||
Neither `better-sqlite3` nor `node:sqlite` could be loaded — almost always a
|
||||
Node older than 22.5. Upgrade Node.
|
||||
|
||||
### Database is locked / busy errors
|
||||
|
||||
The SQLite database uses WAL mode with a 5-second busy timeout. If you see lock errors:
|
||||
|
||||
- Ensure only one dashboard server instance is running
|
||||
- Check for zombie `node server/index.js` processes: `ps aux | grep server/index`
|
||||
- Delete `data/dashboard.db-wal` and `data/dashboard.db-shm` if the server was killed uncleanly, then restart
|
||||
|
||||
### `npm run dev` fails immediately
|
||||
|
||||
@@ -375,7 +643,7 @@ Ensure both server and client dependencies are installed:
|
||||
npm run setup
|
||||
```
|
||||
|
||||
If the error mentions a missing module like `express` or `react`, dependencies may be incomplete. Delete `node_modules` in both root and `client/`, then re-run setup:
|
||||
If the error mentions a missing module like `express` or `react`, dependencies may be incomplete. Delete `node_modules` in both the root and `client/`, then re-run setup:
|
||||
|
||||
```bash
|
||||
rm -rf node_modules client/node_modules
|
||||
@@ -409,9 +677,66 @@ that case.
|
||||
|
||||
### No sessions appearing after starting Claude Code
|
||||
|
||||
See [SETUP.md — Troubleshooting](./SETUP.md#troubleshooting) for detailed hook debugging steps.
|
||||
**Check 1 — Is the server running?**
|
||||
|
||||
---
|
||||
```bash
|
||||
curl http://localhost:4820/api/health
|
||||
# Expected: {"status":"ok","timestamp":"..."}
|
||||
```
|
||||
|
||||
**Check 2 — Are hooks installed?**
|
||||
|
||||
With the plugin, its hooks come with it — run `/agenthub-doctor` instead. For a
|
||||
checkout, open `~/.claude/settings.json` and confirm it contains a `hooks`
|
||||
section with entries referencing `hook-handler.js`. If not, run:
|
||||
|
||||
```bash
|
||||
npm run install-hooks
|
||||
```
|
||||
|
||||
**Check 3 — Did you start a new Claude Code session after the server started?**
|
||||
|
||||
Hooks only apply to sessions started after installation. Restart Claude Code.
|
||||
|
||||
**Check 4 — Is Node.js in PATH when Claude Code runs hooks?**
|
||||
|
||||
On some systems, the shell environment when Claude Code fires hooks may not include the full PATH. Test with:
|
||||
|
||||
```bash
|
||||
node --version
|
||||
```
|
||||
|
||||
If Node.js is not found, use the full path to `node` in the hook command. Edit `scripts/install-hooks.js`, replace `node` with the absolute path (e.g. `/usr/local/bin/node`), and re-run `npm run install-hooks`.
|
||||
|
||||
### Dashboard shows "Disconnected" in the sidebar
|
||||
|
||||
The WebSocket connection to the server failed. Ensure the server is running:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
The client will automatically reconnect every 2 seconds once the server is available.
|
||||
|
||||
### Port 4820 already in use
|
||||
|
||||
When another program holds the port, the server stops with
|
||||
`Port 4820 is already in use by another program…` (a running AgentHub there is
|
||||
detected and simply reused). Pick another port:
|
||||
|
||||
```bash
|
||||
DASHBOARD_PORT=4821 npm start # or: DASHBOARD_PORT=4821 npm run dev
|
||||
```
|
||||
|
||||
The Vite dev proxy and the Claude Code hooks follow the port on their own
|
||||
(`client/vite.config.ts` reads `DASHBOARD_PORT`; the server publishes the port it bound).
|
||||
|
||||
And make sure Claude Code posts hooks to the new port:
|
||||
|
||||
```bash
|
||||
CLAUDE_DASHBOARD_PORT=4821 claude
|
||||
# or edit scripts/hook-handler.js and change the default port
|
||||
```
|
||||
|
||||
## Ports
|
||||
|
||||
|
||||
@@ -1,422 +1,14 @@
|
||||
# Setup Guide
|
||||
|
||||
A comprehensive guide to setting up and configuring the Agent Dashboard, including how it integrates with Claude Code, environment variables, container deployment, and troubleshooting common issues.
|
||||
|
||||
## How it works
|
||||
|
||||
Agent Dashboard integrates with Claude Code through its native hook system. When Claude Code performs any action (session start, tool use, turn completion, subagent finish, session exit), it fires a hook that calls a small Node.js script bundled with this project. That script forwards the event over HTTP to the dashboard server, which stores it in SQLite and broadcasts it to the browser over WebSocket.
|
||||
|
||||
```
|
||||
Claude Code → hook fires → hook-handler.js → POST /api/hooks/event
|
||||
↓
|
||||
Browser ← WebSocket broadcast ← Express server ← SQLite
|
||||
```
|
||||
|
||||
No extra Claude Code configuration is required in the normal host-run path — when you start the dashboard with `npm run dev` or `npm start`, the server configures the hooks automatically on startup (or, with the `agenthub` plugin enabled in `~/.claude/settings.json`, removes the checkout's copies — the plugin's own hooks already run, and both would post every event twice). Container deployments are the exception: after the container is up, run `npm run install-hooks` on the host so Claude Code points at `http://localhost:4820`.
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
### Hook auto-installation
|
||||
|
||||
When the dashboard is running directly on the host, the server writes the following to `~/.claude/settings.json` every time it starts:
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"SessionStart": [{ "hooks": [{ "type": "command", "command": "node \"/path/to/scripts/hook-handler.js\" SessionStart" }] }],
|
||||
"PreToolUse": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "node \"/path/to/scripts/hook-handler.js\" PreToolUse" }] }],
|
||||
"PostToolUse": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "node \"/path/to/scripts/hook-handler.js\" PostToolUse" }] }],
|
||||
"Stop": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "node \"/path/to/scripts/hook-handler.js\" Stop" }] }],
|
||||
"SubagentStop": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "node \"/path/to/scripts/hook-handler.js\" SubagentStop" }] }],
|
||||
"Notification": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "node \"/path/to/scripts/hook-handler.js\" Notification" }] }],
|
||||
"SessionEnd": [{ "hooks": [{ "type": "command", "command": "node \"/path/to/scripts/hook-handler.js\" SessionEnd" }] }]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> Note: `SessionStart` and `SessionEnd` hooks do not support the `matcher` field — they fire unconditionally on every session start and exit.
|
||||
|
||||
Existing hooks in that file are preserved. The dashboard only adds or updates entries that contain `hook-handler.js`.
|
||||
|
||||
To re-run hook installation manually:
|
||||
|
||||
```bash
|
||||
npm run install-hooks
|
||||
```
|
||||
|
||||
> [!TIP]
|
||||
> Container note: if you run the dashboard inside a container (a Dev Container, Codespaces, or your own image), do not install hooks from in there — the hook path a container writes points at the container filesystem, not the host. Run `npm run install-hooks` on the host instead. As a safeguard (issue #193) the installer **detects container execution and refuses to run** (exiting non-zero) so it can never poison a bind-mounted host `~/.claude`. If Claude Code itself genuinely runs inside that container, override with `AGENTHUB_ALLOW_CONTAINER_HOOKS=1 npm run install-hooks`.
|
||||
|
||||
> [!NOTE]
|
||||
> Prefer a ready-made dev environment? This repo ships an **optional** Dev Container (`.devcontainer/`) for VS Code / GitHub Codespaces — Node 22, native build tools for `better-sqlite3`, Python, and ports `4820`/`5173` preconfigured. It's purely opt-in and changes nothing for host-based development. See [`.devcontainer/README.md`](.devcontainer/README.md). (Hooks remain host-side there too.)
|
||||
|
||||
### Environment variables
|
||||
|
||||
| Variable | Default | Description |
|
||||
|---|---|---|
|
||||
| `DASHBOARD_PORT` | `4820` | Port the Express server listens on |
|
||||
| `CLAUDE_DASHBOARD_PORT` | `4820` | Port the hook handler uses when posting events to the dashboard |
|
||||
| `DASHBOARD_DB_PATH` | `data/dashboard.db` | Path to the SQLite database file |
|
||||
| `NODE_ENV` | `development` | Set to `production` to serve built client |
|
||||
| `DASHBOARD_CLIENT_DIST` | `client/dist` | Directory the built UI is served from in production. Set by the `agenthub` plugin bootstrap to its own runtime dir, because the plugin cache is replaced on every update |
|
||||
| `AGENTHUB_IMPORT_MAX_BYTES` | `1073741824` (1 GB) | Maximum size per uploaded file on `/api/import/upload` |
|
||||
| `AGENTHUB_IMPORT_MAX_FILES` | `2000` | Maximum number of files per upload request |
|
||||
| `AGENTHUB_IMPORT_MAX_EXTRACT_BYTES` | `4294967296` (4 GB) | Maximum uncompressed bytes any single archive is allowed to expand to (zip-bomb defense) |
|
||||
|
||||
Example with a custom port:
|
||||
|
||||
```bash
|
||||
DASHBOARD_PORT=9000 npm run dev
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> You usually do **not** need to set `DASHBOARD_PORT` manually. `npm run dev` is wrapped by `scripts/dev.js`, which probes both `127.0.0.1` and `::1` (so an SSH `LocalForward` bound to one loopback can't slip past) and picks the first free port in `4820–4859` automatically. The chosen port is propagated to the Vite dev proxy via `DASHBOARD_PORT`, and the Express server writes it to `~/.claude/.agenthub.json` so the Claude Code hook handler discovers it without any env var.
|
||||
>
|
||||
> Multiple dashboards can run side by side — for example two `npm run dev` checkouts, or `npm run dev` alongside `npm start`. Each one appends its `{port, pid, startedAt}` entry to the discovery file, and `scripts/hook-handler.js` fan-outs every hook event to every live entry, so both UIs keep their real-time stream.
|
||||
>
|
||||
> Setting `CLAUDE_DASHBOARD_PORT=N` overrides discovery entirely and forces the hook handler to a single port — useful for tests and container setups where the in-process discovery file isn't reachable from the host.
|
||||
>
|
||||
> If you bypass the picker (e.g. `npm run dev:raw`, container builds, or anything else that calls `node server/index.js` directly), make sure your client is built / proxied against the port the server actually bound.
|
||||
|
||||
### Agent extension setup (Claude Code + Codex)
|
||||
|
||||
This repository ships extension files for both agent ecosystems:
|
||||
|
||||
- Claude Code:
|
||||
- `CLAUDE.md`
|
||||
- `.claude/rules/*`
|
||||
- `skills/*` (the `agenthub` plugin's own skills)
|
||||
- `agents/*` (the `agenthub` plugin's own agents)
|
||||
- Codex:
|
||||
- `AGENTS.md`
|
||||
- `.codex/config.toml`
|
||||
- `.codex/rules/default.rules`
|
||||
- `.codex/agents/*`
|
||||
- `.codex/skills/*`
|
||||
|
||||
See [`.codex/README.md`](./.codex/README.md) for Codex extension details.
|
||||
|
||||
### PWA configuration (optional)
|
||||
|
||||
The dashboard ships as a Progressive Web App. No configuration is required — its manifest and service worker are included out of the box.
|
||||
|
||||
**Customising the manifest:** Edit `client/public/manifest.json`. Common fields to change:
|
||||
|
||||
- `name` / `short_name` — displayed on the home screen / dock
|
||||
- `theme_color` — address bar / title bar tint (default: `#6366f1`)
|
||||
- `background_color` — splash screen background
|
||||
- `start_url` — entry point when launched from home screen
|
||||
|
||||
**Updating the service worker cache:** The SW has a `CACHE_NAME` constant (e.g. `dashboard-v2`). After deploying new assets, bump the version string to force browsers to re-fetch — though for the dashboard this is rarely needed: hashed `/assets/*` URLs are immutable per build, everything else is fetched network-first with cache fallback, and a `controllerchange` listener in the client reloads the page exactly once when a new SW takes over, so a rebuild propagates without a hard refresh.
|
||||
|
||||
**Browser support:** PWA install prompts appear in Chrome 107+, Edge 107+, and Firefox 110+ (desktop and Android). Safari supports `apple-mobile-web-app-capable` for iOS home-screen mode but does not show an install banner.
|
||||
|
||||
**Verifying PWA status:** Open DevTools → Application → Manifest to confirm the manifest loads. Check the Service Workers section to verify the SW is registered and active. The Lighthouse PWA audit should pass all core checks.
|
||||
|
||||
---
|
||||
|
||||
## Database
|
||||
|
||||
The SQLite database is created automatically at `data/dashboard.db` on first run. The directory is created if it does not exist. The database uses WAL mode for concurrent reads and foreign keys for referential integrity.
|
||||
|
||||
### Clear all data
|
||||
|
||||
To remove all sessions, agents, events, and token usage (useful after running seed data or for a clean start):
|
||||
|
||||
```bash
|
||||
npm run clear-data
|
||||
```
|
||||
|
||||
### Data management via Settings page
|
||||
|
||||
The Settings page (`/settings`) provides a UI for the following. **Model Pricing**
|
||||
and **Hook Configuration** are not on its Dashboard tab: they sit under the
|
||||
Claude Code tab's **Overview** (Settings → Claude Code → Overview), beside
|
||||
CLAUDE_HOME; Codex (its Overview) and Antigravity have their own pricing and
|
||||
hooks in their own tabs.
|
||||
|
||||
- **Model Pricing** — view and edit per-model cost rates, reset to defaults, add custom models
|
||||
- **Hook Configuration** — check which hooks are installed and reinstall them
|
||||
- **Data Export** — download all sessions, agents, events, and pricing as a JSON file
|
||||
- **Session Cleanup** — abandon stale active sessions after N hours, purge old completed sessions after N days
|
||||
- **Clear All Data** — remove all sessions, agents, events, and token usage
|
||||
- **Data Management** and **About** sections render with loading placeholders while server info is being fetched, so the page is always fully navigable
|
||||
|
||||
### Seed demo data
|
||||
|
||||
To populate the dashboard with sample sessions, agents, and events for UI exploration:
|
||||
|
||||
```bash
|
||||
npm run seed
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Importing existing Claude Code history
|
||||
|
||||
The dashboard automatically imports sessions from `~/.claude/projects/` on
|
||||
**every startup**, so if Claude Code has been used on this machine, you'll
|
||||
see history immediately after the first launch. If you need to bring in
|
||||
history from another machine, from a backup, or just force a rescan, use
|
||||
**Settings → Import History** in the UI — it's a guided, drag-and-drop
|
||||
experience with live progress.
|
||||
### Pick the right mode
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Q["Where is the history?"] --> Q1{Is it on this machine<br/>under ~/.claude/projects?}
|
||||
Q1 -->|yes, and I just want<br/>to re-scan| M1["Mode: Rescan default folder<br/>one click"]
|
||||
Q1 -->|yes, but in another folder<br/>on this machine| M2["Mode: Scan a folder<br/>paste the absolute path"]
|
||||
Q1 -->|no — it's on another machine<br/>or in an archive file| M3["Mode: Upload files<br/>drag-drop JSONL or archive"]
|
||||
|
||||
M3 --> PREP["Archive source:<br/>tar -czf claude-history.tar.gz<br/>-C ~/.claude projects"]
|
||||
|
||||
style M1 fill:#10b981,stroke:#34d399,color:#fff
|
||||
style M2 fill:#f59e0b,stroke:#fbbf24,color:#000
|
||||
style M3 fill:#a855f7,stroke:#c084fc,color:#fff
|
||||
```
|
||||
|
||||
### Step-by-step: moving history from one machine to another
|
||||
|
||||
**On the source machine**, bundle the projects folder:
|
||||
|
||||
```bash
|
||||
# macOS / Linux
|
||||
tar -czf claude-history.tar.gz -C ~/.claude projects
|
||||
|
||||
# Windows (PowerShell, via built-in tar)
|
||||
tar -czf claude-history.tar.gz -C "$env:USERPROFILE\.claude" projects
|
||||
```
|
||||
|
||||
Transfer the resulting `claude-history.tar.gz` to the destination machine
|
||||
however you like — AirDrop, `scp`, USB, cloud storage.
|
||||
|
||||
**On the destination machine**, in the dashboard:
|
||||
|
||||
1. Open **Settings → Import History**.
|
||||
2. Pick **Upload files** (the third tab).
|
||||
3. Drag the archive onto the drop zone.
|
||||
4. Click **Upload & Import** and watch the progress.
|
||||
5. When the green result card appears, open **Analytics → Cost** to confirm
|
||||
per-model token totals and estimated cost.
|
||||
|
||||
### Supported inputs
|
||||
|
||||
Any of the following can be dropped onto the upload zone or found inside a
|
||||
folder given to **Scan a folder**:
|
||||
|
||||
- `.jsonl` — session transcripts
|
||||
- `.meta.json` — subagent metadata sidecars
|
||||
- `.zip` — extracted with path-traversal protection
|
||||
- `.tar`, `.tar.gz`, `.tgz` — extracted via the `tar` package
|
||||
- `.gz` — single gzipped JSONL (streaming-decompressed)
|
||||
|
||||
### Accuracy guarantees
|
||||
|
||||
- **Idempotent** — re-importing never double-counts. Sessions are
|
||||
deduplicated by UUID.
|
||||
- **Cost-preserving** — the `token_usage` table uses `baseline_*` columns
|
||||
to preserve pre-compaction token totals, so re-ingesting a compacted
|
||||
transcript never erases historical cost.
|
||||
- **Same parser as live** — `parseSessionFile` + `importSession` is the
|
||||
single source of truth for both hook-driven ingestion and manual
|
||||
import, so imported numbers match captured numbers exactly.
|
||||
|
||||
### Safety
|
||||
|
||||
Archive extraction is hardened against path traversal and archive bombs.
|
||||
The defaults are generous for real-world transcripts but tight enough to
|
||||
stop obvious attacks; see the env vars table above for
|
||||
`AGENTHUB_IMPORT_MAX_BYTES`, `AGENTHUB_IMPORT_MAX_FILES`, and
|
||||
`AGENTHUB_IMPORT_MAX_EXTRACT_BYTES`.
|
||||
|
||||
### CLI alternative
|
||||
|
||||
For scripts and automation, the same logic runs from the terminal:
|
||||
|
||||
```bash
|
||||
# Import (or re-import) everything under ~/.claude/projects
|
||||
npm run import-history
|
||||
|
||||
# Dry run — show what would be imported without writing
|
||||
node scripts/import-history.js --dry-run
|
||||
|
||||
# Scope to a single project dir
|
||||
node scripts/import-history.js --project my-project
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Scripts reference
|
||||
|
||||
| Script | Command | Description |
|
||||
|---|---|---|
|
||||
| `setup` | `npm run setup` | Install all dependencies (server + client) |
|
||||
| `dev` | `npm run dev` | Start server + client in development mode |
|
||||
| `start` | `npm start` | Start server in production mode |
|
||||
| `build` | `npm run build` | Build the React client to `client/dist/` |
|
||||
| `install-hooks` | `npm run install-hooks` | Write Claude Code hooks to `~/.claude/settings.json` |
|
||||
| `clear-data` | `npm run clear-data` | Delete all data from the database |
|
||||
| `seed` | `npm run seed` | Insert demo sessions/agents/events |
|
||||
| `import-history` | `npm run import-history` | Import legacy sessions from `~/.claude/` (also runs on startup) |
|
||||
| `claude` | Claude CLI | Uses `CLAUDE.md`, `.claude/rules`, and `.claude/skills` automatically |
|
||||
| `test` | `npm test` | Run all server and client tests |
|
||||
| `test:server` | `npm run test:server` | Run server integration tests only |
|
||||
| `test:client` | `npm run test:client` | Run client unit tests only |
|
||||
| `format` | `npm run format` | Format all files with Prettier |
|
||||
| `format:check` | `npm run format:check` | Check formatting without writing |
|
||||
|
||||
---
|
||||
|
||||
## Makefile targets
|
||||
|
||||
All npm scripts are mirrored as `make` targets for convenience. Run `make help` to list them:
|
||||
|
||||
```bash
|
||||
make help
|
||||
```
|
||||
|
||||
Commonly used targets:
|
||||
|
||||
| Make target | Equivalent npm command | Description |
|
||||
|---|---|---|
|
||||
| `make setup` | `npm run setup` | Install all dependencies (root + client) |
|
||||
| `make dev` | `npm run dev` | Start server + client in watch mode |
|
||||
| `make build` | `npm run build` | Build the React client for production |
|
||||
| `make start` | `npm start` | Start the production server |
|
||||
| `make prod` | `npm run build && npm start` | Build then start in one step |
|
||||
| `make test` | `npm test` | Run all tests (server + client) |
|
||||
| `make test-server` | `npm run test:server` | Run server tests only |
|
||||
| `make test-client` | `npm run test:client` | Run client tests only |
|
||||
| `make format` | `npm run format` | Format all files with Prettier |
|
||||
| `make format-check` | `npm run format:check` | Check formatting without writing |
|
||||
| `make seed` | `npm run seed` | Load demo data |
|
||||
| `make clear-data` | `npm run clear-data` | Delete all data rows |
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### `better-sqlite3` errors during `npm install` / `npm run setup`
|
||||
|
||||
These warnings are **harmless**. `better-sqlite3` is an optional dependency — if it cannot compile, npm skips it and the server falls back to Node.js built-in `node:sqlite` (available on Node 22+).
|
||||
|
||||
You do **not** need Python, Visual Studio Build Tools, or any C++ compiler to run this project on Node 22+.
|
||||
|
||||
If you are on Node 20 or 21 and `better-sqlite3` prebuilds are not available for your platform (there is no `node:sqlite` fallback below Node 22), you have two options:
|
||||
|
||||
1. **Upgrade to Node.js 22+** — the built-in `node:sqlite` fallback requires no native compilation at all
|
||||
2. **Install build tools** and run `npm rebuild better-sqlite3`:
|
||||
- **Windows:** install [Visual Studio Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) with the C++ workload
|
||||
- **macOS:** `xcode-select --install`
|
||||
- **Linux:** `sudo apt install python3 make g++` (Debian/Ubuntu)
|
||||
|
||||
### "SQLite backend not available" error on startup
|
||||
|
||||
This means neither `better-sqlite3` nor `node:sqlite` could be loaded. The most common cause is running Node.js < 22 without `better-sqlite3` prebuilds. Upgrade to Node.js 22+ to resolve this.
|
||||
|
||||
### Database is locked / busy errors
|
||||
|
||||
The SQLite database uses WAL mode with a 5-second busy timeout. If you see lock errors:
|
||||
|
||||
- Ensure only one dashboard server instance is running
|
||||
- Check for zombie `node server/index.js` processes: `ps aux | grep server/index`
|
||||
- Delete `data/dashboard.db-wal` and `data/dashboard.db-shm` if the server was killed uncleanly, then restart
|
||||
|
||||
---
|
||||
|
||||
### 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?**
|
||||
|
||||
```bash
|
||||
curl http://localhost:4820/api/health
|
||||
# Expected: {"status":"ok","timestamp":"..."}
|
||||
```
|
||||
|
||||
**Check 2 — Are hooks installed?**
|
||||
|
||||
Open `~/.claude/settings.json` and confirm it contains a `hooks` section with entries referencing `hook-handler.js`. If not, run:
|
||||
|
||||
```bash
|
||||
npm run install-hooks
|
||||
```
|
||||
|
||||
**Check 3 — Did you start a new Claude Code session after the server started?**
|
||||
|
||||
Hooks only apply to sessions started after installation. Restart Claude Code.
|
||||
|
||||
**Check 4 — Is Node.js in PATH when Claude Code runs hooks?**
|
||||
|
||||
On some systems, the shell environment when Claude Code fires hooks may not include the full PATH. Test with:
|
||||
|
||||
```bash
|
||||
node --version
|
||||
```
|
||||
|
||||
If Node.js is not found, use the full path to `node` in the hook command. Edit `scripts/install-hooks.js`, replace `node` with the absolute path (e.g. `/usr/local/bin/node`), and re-run `npm run install-hooks`.
|
||||
|
||||
---
|
||||
|
||||
### Dashboard shows "Disconnected" in the sidebar
|
||||
|
||||
The WebSocket connection to the server failed. Ensure the server is running:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
The client will automatically reconnect every 2 seconds once the server is available.
|
||||
|
||||
---
|
||||
|
||||
### Events Today shows 0 despite recent activity
|
||||
|
||||
This was a known timezone bug (fixed in current version). If you are still seeing this, ensure you are running the latest code and restart the server.
|
||||
|
||||
---
|
||||
|
||||
### Port 4820 already in use
|
||||
|
||||
```bash
|
||||
DASHBOARD_PORT=4821 npm run dev
|
||||
```
|
||||
|
||||
Then update the Vite proxy in `client/vite.config.ts`:
|
||||
|
||||
```ts
|
||||
proxy: {
|
||||
"/api": "http://localhost:4821",
|
||||
"/ws": { target: "ws://localhost:4821", ws: true }
|
||||
}
|
||||
```
|
||||
|
||||
And make sure Claude Code posts hooks to the new port:
|
||||
|
||||
```bash
|
||||
CLAUDE_DASHBOARD_PORT=4821 claude
|
||||
# or edit scripts/hook-handler.js and change the default port
|
||||
```
|
||||
This guide has moved into **[INSTALL.md](./INSTALL.md)** — the one install and
|
||||
setup guide (it and this file had grown into near-duplicates). Everything that
|
||||
was here is there:
|
||||
|
||||
| Was in SETUP.md | Now in INSTALL.md |
|
||||
|---|---|
|
||||
| How it works | [How it works](./INSTALL.md#how-it-works) |
|
||||
| Hook auto-installation, environment variables, agent extensions, PWA | [Configuration](./INSTALL.md#configuration) |
|
||||
| Database (clear, Settings page, seed) | [Database](./INSTALL.md#database) |
|
||||
| Importing existing Claude Code history | [Step 5](./INSTALL.md#step-5--optional-importing-existing-claude-code-history) |
|
||||
| Scripts reference, Makefile targets | [Scripts reference](./INSTALL.md#scripts-reference) |
|
||||
| Troubleshooting (incl. "Port 4820 already in use") | [Troubleshooting](./INSTALL.md#troubleshooting) |
|
||||
|
||||
+87
-6
@@ -2855,8 +2855,8 @@ const COMMAND_GROUPS = [
|
||||
],
|
||||
[
|
||||
"accounts",
|
||||
"list|add|remove [name] [--tool codex]",
|
||||
"Claude/Codex account pool: new sessions spread over these accounts",
|
||||
"list|add|remove [name]|pin <account> <user>|unpin <user> [--tool codex]",
|
||||
"Claude/Codex account pool: new sessions spread over these accounts; pin = one user always on one",
|
||||
],
|
||||
["repl", "", "Open the interactive shell (also: shell, i)"],
|
||||
],
|
||||
@@ -3814,7 +3814,7 @@ const SUBCOMMANDS = {
|
||||
service: ["install", "uninstall", "status"],
|
||||
server: ["setup", "off", "status"],
|
||||
users: ["list", "add", "passwd", "role", "disable", "enable", "assign", "audit"],
|
||||
accounts: ["list", "add", "remove"],
|
||||
accounts: ["list", "add", "remove", "pin", "unpin"],
|
||||
pricing: ["set", "delete", "reset"],
|
||||
webhooks: ["test"],
|
||||
import: ["rescan", "path"],
|
||||
@@ -4286,7 +4286,18 @@ async function cmdCodexAccounts(sub, name, flags) {
|
||||
}
|
||||
pool.resetQuota();
|
||||
table(
|
||||
["codex account", "kind", "live", "$ 5h", "$ 7d", "tok 5h", "tok 7d", "quota", "state"],
|
||||
[
|
||||
"codex account",
|
||||
"kind",
|
||||
"live",
|
||||
"$ 5h",
|
||||
"$ 7d",
|
||||
"tok 5h",
|
||||
"tok 7d",
|
||||
"quota",
|
||||
"state",
|
||||
"pinned",
|
||||
],
|
||||
pool
|
||||
.poolStatus()
|
||||
.map((a) => [
|
||||
@@ -4301,10 +4312,64 @@ async function cmdCodexAccounts(sub, name, flags) {
|
||||
? a.quota.windows.map((w) => `${w.label} ${Math.round(w.usedPercent)}%`).join(" ")
|
||||
: "–",
|
||||
a.full ? "full" : "ok",
|
||||
pinnedUsers("codex", a.name),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* `agenthub accounts pin <account> <user>` / `unpin <user>` [--tool codex] —
|
||||
* that user's new sessions run on that account (server/lib/account-pins.js).
|
||||
*/
|
||||
async function cmdAccountPin(sub, positional, tool) {
|
||||
const pins = require(path.join(REPO_ROOT, "server", "lib", "account-pins.js"));
|
||||
const [first, second] = positional;
|
||||
const username = sub === "pin" ? second : first;
|
||||
if (!username || (sub === "pin" && !first)) {
|
||||
throw new Error("usage: agenthub accounts pin <account> <user> | unpin <user> [--tool codex]");
|
||||
}
|
||||
const user = require(path.join(REPO_ROOT, "server", "db.js"))
|
||||
.db.prepare("SELECT id FROM users WHERE username = ?")
|
||||
.get(username);
|
||||
if (!user) throw new Error(`no user ${username}`);
|
||||
const pin = pins.setPin(user.id, tool, sub === "pin" ? first : null);
|
||||
if (!require(path.join(REPO_ROOT, "server", "lib", "auth.js")).isServerMode()) {
|
||||
console.log(c.dim(" Pins apply in server mode only."));
|
||||
}
|
||||
if (!pin.account) {
|
||||
console.log(`${c.green("✔")} ${pin.username} unpinned — new ${tool} sessions use the balancer`);
|
||||
return;
|
||||
}
|
||||
const switched = await pins.applyPin(user.id, tool);
|
||||
console.log(`${c.green("✔")} ${pin.username}'s ${tool} sessions run on ${pin.account}`);
|
||||
console.log(c.dim(` ${SWITCH_NOTE[switched] || SWITCH_NOTE["next-session"]}`));
|
||||
}
|
||||
|
||||
/** What `applyPin` did, for the CLI. */
|
||||
const SWITCH_NOTE = {
|
||||
switched: "Switched now: running sessions take it at their next login check, new ones at once.",
|
||||
kept: "Their home already holds it.",
|
||||
"own-login":
|
||||
"They signed in with their own login, which is left alone: no pool login is written over it.",
|
||||
expired: "That login has expired: new sessions fall back to the balancer until it is re-added.",
|
||||
"next-session": "New sessions use it; running ones keep their account until they end.",
|
||||
};
|
||||
|
||||
/** The `pinned` column: who an admin pinned to `account`. */
|
||||
function pinnedUsers(tool, account) {
|
||||
try {
|
||||
return (
|
||||
require(path.join(REPO_ROOT, "server", "lib", "account-pins.js"))
|
||||
.listPins(tool)
|
||||
.filter((p) => p.account === account)
|
||||
.map((p) => p.username)
|
||||
.join(",") || "–"
|
||||
);
|
||||
} catch {
|
||||
return "–";
|
||||
}
|
||||
}
|
||||
|
||||
/** `agenthub accounts …` — the Claude account pool (server/lib/claude-pool.js). */
|
||||
async function cmdAccounts(sub, positional, flags = {}) {
|
||||
serverAuth(); // the same settings + database the server reads
|
||||
@@ -4316,6 +4381,8 @@ async function cmdAccounts(sub, positional, flags = {}) {
|
||||
if (flags.tool != null && flags.tool !== "claude" && flags.tool !== "codex") {
|
||||
throw new Error("--tool is claude (the default) or codex");
|
||||
}
|
||||
if (sub === "pin" || sub === "unpin")
|
||||
return cmdAccountPin(sub, positional, flags.tool || "claude");
|
||||
if (flags.tool === "codex") return cmdCodexAccounts(sub, name, flags);
|
||||
if (sub === "add") {
|
||||
console.log(
|
||||
@@ -4337,7 +4404,18 @@ async function cmdAccounts(sub, positional, flags = {}) {
|
||||
await pool.refreshQuotas({ force: true });
|
||||
const pct = (w) => (w?.utilization != null ? `${Math.round(w.utilization)}%` : "–");
|
||||
table(
|
||||
["account", "live", "$ 5h", "$ 7d", "tok 5h", "tok 7d", "quota 5h", "quota wk", "state"],
|
||||
[
|
||||
"account",
|
||||
"live",
|
||||
"$ 5h",
|
||||
"$ 7d",
|
||||
"tok 5h",
|
||||
"tok 7d",
|
||||
"quota 5h",
|
||||
"quota wk",
|
||||
"state",
|
||||
"pinned",
|
||||
],
|
||||
pool
|
||||
.poolStatus()
|
||||
.map((a) => [
|
||||
@@ -4356,6 +4434,7 @@ async function cmdAccounts(sub, positional, flags = {}) {
|
||||
: a.quota?.error
|
||||
? `no quota (${a.quota.error})`
|
||||
: "ok",
|
||||
pinnedUsers("claude", a.name),
|
||||
])
|
||||
);
|
||||
const codex = require(path.join(REPO_ROOT, "server", "lib", "codex-pool.js"));
|
||||
@@ -4363,7 +4442,9 @@ async function cmdAccounts(sub, positional, flags = {}) {
|
||||
return;
|
||||
}
|
||||
console.error(
|
||||
c.red("✖ Usage: agenthub accounts list | add <name> | remove <name> [--tool codex]")
|
||||
c.red(
|
||||
"✖ Usage: agenthub accounts list | add <name> | remove <name> | pin <account> <user> | unpin <user> [--tool codex]"
|
||||
)
|
||||
);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
|
||||
@@ -76,7 +76,7 @@
|
||||
*
|
||||
* ----------------------------------------------------------------------------- */
|
||||
|
||||
import { useState, useCallback, useEffect, useSyncExternalStore } from "react";
|
||||
import { lazy, Suspense, useState, useCallback, useEffect, useSyncExternalStore } from "react";
|
||||
import { Outlet, useLocation } from "react-router-dom";
|
||||
import { Menu } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -85,9 +85,15 @@ import { UpdateNotifier } from "./UpdateNotifier";
|
||||
import { InterruptedSessionsPrompt } from "./lanes/InterruptedSessionsPrompt";
|
||||
import { SagiMount } from "./Sagi/SagiMount";
|
||||
import { StatusBar } from "./StatusBar";
|
||||
import { OnboardingWizard } from "./onboarding/OnboardingWizard";
|
||||
import { useOnboarding } from "../lib/userPrefs";
|
||||
import { OnboardingTour } from "./onboarding/OnboardingTour";
|
||||
|
||||
// Loaded only for an account that has not finished onboarding: the wizard
|
||||
// carries the appearance, pet and notification settings screens.
|
||||
const OnboardingWizard = lazy(() =>
|
||||
import("./onboarding/OnboardingWizard").then((m) => ({ default: m.OnboardingWizard }))
|
||||
);
|
||||
|
||||
const WIDTH_KEY = "agenthub.sidebar.width";
|
||||
/** The default width, and the narrowest the edge drags to. */
|
||||
export const SIDEBAR_MIN = 240;
|
||||
@@ -136,6 +142,7 @@ export function Layout({ wsConnected }: LayoutProps) {
|
||||
const { t } = useTranslation("nav");
|
||||
const [collapsed, setCollapsed] = useState(loadCollapsed);
|
||||
const [connectionOpen, setConnectionOpen] = useState(false);
|
||||
const onboarding = useOnboarding();
|
||||
const [updateAvailable, setUpdateAvailable] = useState(false);
|
||||
const drawer = useMedia(DRAWER_QUERY);
|
||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||
@@ -177,7 +184,11 @@ export function Layout({ wsConnected }: LayoutProps) {
|
||||
<UpdateNotifier />
|
||||
<InterruptedSessionsPrompt />
|
||||
<SagiMount />
|
||||
<OnboardingWizard />
|
||||
{onboarding.loaded && !onboarding.onboardedAt && (
|
||||
<Suspense fallback={null}>
|
||||
<OnboardingWizard />
|
||||
</Suspense>
|
||||
)}
|
||||
<OnboardingTour />
|
||||
{drawer && drawerOpen && (
|
||||
<div
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
/**
|
||||
* @file PetChat.tsx
|
||||
* @description The pet's chat window. A question its Ask box cannot answer
|
||||
* locally opens here instead of leaving the page: the first message starts a
|
||||
* @description The pet's chat window — its whole UI: clicking the pet opens
|
||||
* it. Above the conversation sits what the pet knows (`info`: live / waiting /
|
||||
* errored, the sessions that need you, Mute, Clear alerts — `SagiInfo.tsx`).
|
||||
* Before a chat runs, a question the pet can answer itself (`onLocal`: status,
|
||||
* who are you…) is answered right here; anything else — and every message once
|
||||
* a chat runs — goes to the AI: the first message starts a
|
||||
* session of the user's DEFAULT AI tool (`agenthub.defaultTool`, Claude or
|
||||
* Codex — the two with a readable transcript) in the "Sagi" workspace, in its
|
||||
* first free tab (`startInFreeTabDetailed`), and the conversation is shown as
|
||||
@@ -11,16 +15,17 @@
|
||||
* attached pane, exactly like the workspace's own Chat view), so nothing new
|
||||
* reaches the server. A menu the CLI asks with (a permission or trust prompt)
|
||||
* is read off that pane and answered with `PaneMenuCard`. The chat is kept in
|
||||
* `localStorage` (`agenthub.pet.chat`) while its pane lives; **New chat**
|
||||
* forgets it (the session stays in the workspace), **Open in workspace**
|
||||
* `localStorage` (`agenthub.pet.chat`) while its pane lives, so closing and
|
||||
* reopening the window continues it; **New chat** STOPS that session (kills
|
||||
* its pane and archives it, asking first only mid-reply), **Open in workspace**
|
||||
* opens its pane there. Opening never resumes an ended session: once the pane
|
||||
* is gone, the next message starts a new one.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useRef, useState, type FormEvent } from "react";
|
||||
import { useCallback, useEffect, useRef, useState, type FormEvent, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ArrowLeft, ArrowUp, ExternalLink, Loader2, SquarePen, Wrench, X } from "lucide-react";
|
||||
import { ArrowUp, ExternalLink, Loader2, SquarePen, Wrench, X } from "lucide-react";
|
||||
import { api } from "../../lib/api";
|
||||
import type { TranscriptMessage } from "../../lib/types";
|
||||
import { readDefaultMode, readDefaultTool } from "../../lib/sessionDefaults";
|
||||
@@ -33,6 +38,8 @@ import {
|
||||
type PaneMenu,
|
||||
} from "../../lib/panePaste";
|
||||
import { isSubmitEnter } from "../../lib/keys";
|
||||
import { confirmDialog } from "../../lib/confirm";
|
||||
import { toast } from "../../lib/toast";
|
||||
import { startInFreeTabDetailed } from "../lanes/startSession";
|
||||
import { TerminalView } from "../run/TerminalView";
|
||||
import { PaneMenuCard } from "../run/PaneChat";
|
||||
@@ -141,14 +148,21 @@ function toolSummary(names: string[]): string {
|
||||
return [...counts].map(([n, c]) => (c > 1 ? `${n} ×${c}` : n)).join(" · ");
|
||||
}
|
||||
|
||||
/** What the container made of a message: an answer the pet gives itself, or
|
||||
* `handled` (it took the message elsewhere); null sends it to the AI. */
|
||||
export type PetLocalReply = { answer: string } | { handled: true } | null;
|
||||
|
||||
interface PetChatProps {
|
||||
/** The pet's shown name, for the header and greeting. */
|
||||
name: string;
|
||||
/** A question to send as soon as the chat opens (the Ask box's handoff). */
|
||||
initialPrompt?: string | null;
|
||||
/** Called once the initial prompt has been taken, so a re-render never sends it twice. */
|
||||
onPromptTaken?: () => void;
|
||||
onBack: () => void;
|
||||
/** Shown in place of the plain name (the rename button). */
|
||||
title?: ReactNode;
|
||||
/** Extra header buttons, before Open in workspace (the pat heart). */
|
||||
headerActions?: ReactNode;
|
||||
/** Under the header: what the pet knows (status, sessions that need you). */
|
||||
info?: ReactNode;
|
||||
/** Asked first while no chat runs. */
|
||||
onLocal?: (text: string) => PetLocalReply;
|
||||
onClose: () => void;
|
||||
/** Opens the chat's pane in its workspace. */
|
||||
onOpenWorkspace: (laneId: number, runId: string) => void;
|
||||
@@ -158,9 +172,10 @@ interface PetChatProps {
|
||||
|
||||
export function PetChat({
|
||||
name,
|
||||
initialPrompt,
|
||||
onPromptTaken,
|
||||
onBack,
|
||||
title,
|
||||
headerActions,
|
||||
info,
|
||||
onLocal,
|
||||
onClose,
|
||||
onOpenWorkspace,
|
||||
onBusy,
|
||||
@@ -175,6 +190,8 @@ export function PetChat({
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [draft, setDraft] = useState("");
|
||||
const [menu, setMenu] = useState<PaneMenu | null>(null);
|
||||
// The pet's own answers, given before any chat ran.
|
||||
const [local, setLocal] = useState<Line[]>([]);
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const remember = (ref: PetChatRef | null) => {
|
||||
@@ -248,7 +265,7 @@ export function PetChat({
|
||||
return () => window.clearInterval(timer);
|
||||
}, [chat]);
|
||||
|
||||
const lines = chatLines(messages);
|
||||
const lines = [...local, ...chatLines(messages)];
|
||||
// The pending line shows until the transcript has it.
|
||||
useEffect(() => {
|
||||
if (pending && lines.some((l) => l.role === "user" && l.text === pending.trim()))
|
||||
@@ -269,6 +286,19 @@ export function PetChat({
|
||||
const prompt = text.trim();
|
||||
if (!prompt || starting) return;
|
||||
setError(null);
|
||||
if (!chat && onLocal) {
|
||||
const reply = onLocal(prompt);
|
||||
if (reply && "handled" in reply) return;
|
||||
if (reply) {
|
||||
const n = Date.now();
|
||||
setLocal((prev) => [
|
||||
...prev,
|
||||
{ key: `lu${n}`, role: "user", text: prompt },
|
||||
{ key: `la${n}`, role: "assistant", text: reply.answer },
|
||||
]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
setPending(prompt);
|
||||
if (chat) {
|
||||
// Typed into the attached pane; it may still be attaching.
|
||||
@@ -302,17 +332,35 @@ export function PetChat({
|
||||
}
|
||||
},
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[chat, starting, t]
|
||||
[chat, starting, t, onLocal]
|
||||
);
|
||||
|
||||
// The Ask box's question, sent once.
|
||||
const taken = useRef(false);
|
||||
useEffect(() => {
|
||||
if (!initialPrompt || taken.current) return;
|
||||
taken.current = true;
|
||||
onPromptTaken?.();
|
||||
void send(initialPrompt);
|
||||
}, [initialPrompt, onPromptTaken, send]);
|
||||
// New chat: the old one's session is stopped, not left running unseen —
|
||||
// asking first only while it is still writing a reply.
|
||||
const newChat = async () => {
|
||||
if (chat) {
|
||||
if (
|
||||
busy &&
|
||||
!(await confirmDialog({
|
||||
title: t("sagi.chat.endTitle"),
|
||||
message: t("sagi.chat.endBody"),
|
||||
confirmLabel: t("sagi.chat.endConfirm"),
|
||||
destructive: true,
|
||||
}))
|
||||
)
|
||||
return;
|
||||
try {
|
||||
await api.run.kill(chat.runId, { archive: true });
|
||||
} catch (err) {
|
||||
toast.error(err);
|
||||
return;
|
||||
}
|
||||
}
|
||||
remember(null);
|
||||
setLocal([]);
|
||||
setPending(null);
|
||||
setError(null);
|
||||
};
|
||||
|
||||
const submit = (e?: FormEvent) => {
|
||||
e?.preventDefault();
|
||||
@@ -333,11 +381,11 @@ export function PetChat({
|
||||
>
|
||||
{/* header */}
|
||||
<div className="pet-chat-head flex items-center gap-1 px-2 py-2">
|
||||
<IconButton label={t("sagi.chat.back")} onClick={onBack}>
|
||||
<ArrowLeft size={16} />
|
||||
</IconButton>
|
||||
<span className="pl-1.5 text-base leading-none" aria-hidden>
|
||||
🐾
|
||||
</span>
|
||||
<div className="min-w-0 flex-1 px-1">
|
||||
<div className="truncate text-sm font-semibold text-fg-primary">{name}</div>
|
||||
{title ?? <div className="truncate text-sm font-semibold text-fg-primary">{name}</div>}
|
||||
<div className="flex items-center gap-1 text-[10px] uppercase tracking-wider text-fg-muted">
|
||||
<span
|
||||
className={`inline-block h-1.5 w-1.5 rounded-full ${
|
||||
@@ -352,6 +400,7 @@ export function PetChat({
|
||||
{busy ? t("sagi.chat.typing") : toolLabel}
|
||||
</div>
|
||||
</div>
|
||||
{headerActions}
|
||||
{chat && (
|
||||
<IconButton
|
||||
label={t("sagi.chat.openWorkspace")}
|
||||
@@ -362,8 +411,8 @@ export function PetChat({
|
||||
)}
|
||||
<IconButton
|
||||
label={t("sagi.chat.new")}
|
||||
onClick={() => remember(null)}
|
||||
disabled={!chat || starting}
|
||||
onClick={() => void newChat()}
|
||||
disabled={(!chat && !local.length) || starting}
|
||||
>
|
||||
<SquarePen size={15} />
|
||||
</IconButton>
|
||||
@@ -372,6 +421,8 @@ export function PetChat({
|
||||
</IconButton>
|
||||
</div>
|
||||
|
||||
{info}
|
||||
|
||||
{/* conversation */}
|
||||
<div ref={listRef} className="flex-1 space-y-2 overflow-y-auto px-3 py-3">
|
||||
{empty && (
|
||||
@@ -475,10 +526,9 @@ export function PetChat({
|
||||
e.preventDefault();
|
||||
submit();
|
||||
} else if (e.key === "Escape") {
|
||||
// Esc leaves the chat for the panel, not the whole mascot.
|
||||
e.stopPropagation();
|
||||
e.nativeEvent.stopImmediatePropagation();
|
||||
onBack();
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -5,17 +5,20 @@
|
||||
* enabled; `Sagi` gates on the same preference itself, and the body (brain,
|
||||
* tick, WS reducer) runs only while it is on. Persists across routes and
|
||||
* shares the single WebSocket.
|
||||
* Owns the open/closed panel state, the ⌘B / Esc shortcuts, reduced-motion
|
||||
* Clicking the pet opens its chat window (`PetChat`), which is its whole UI:
|
||||
* the status strip (`SagiInfo`) sits on top, a question the pet can answer
|
||||
* itself is answered there, anything else goes to the AI.
|
||||
* Owns the open/closed chat state, the ⌘B / Esc shortcuts, reduced-motion
|
||||
* detection, and route navigation. Reactive personality + status/Ask come
|
||||
* from useSagiBrain; the avatar is draggable (AssistiveTouch-style) via
|
||||
* useSagiPosition (a v2 Codex pet also looks toward the pointer), and the
|
||||
* bubble/panel render in a self-clamping flyout so
|
||||
* they never spill off any screen edge regardless of where the mascot is docked.
|
||||
*
|
||||
* The "do the job" path: an unmatched Ask query starts a claude session in
|
||||
* the "Sagi" workspace carrying it as the first prompt, then opens that
|
||||
* workspace's session view (`/workspace?lane=<id>&run=<runId>`) — no new LLM
|
||||
* backend. ⌘B/Ctrl+B is taken only while the mascot is shown and focus is not
|
||||
* The "do the job" path: an unmatched question is the chat's — it starts a
|
||||
* session of the default AI tool in the "Sagi" workspace; a default tool the
|
||||
* chat cannot read back starts there and its session view opens
|
||||
* (`/workspace?lane=<id>&run=<runId>`) — no new LLM backend. ⌘B/Ctrl+B is taken only while the mascot is shown and focus is not
|
||||
* in an editable field (a terminal's Ctrl+B is tmux's prefix).
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
@@ -39,7 +42,7 @@
|
||||
* ## Internal dependencies
|
||||
* - `./SagiAvatar`
|
||||
* - `./SpeechBubble`
|
||||
* - `./SagiPanel`
|
||||
* - `./SagiInfo`
|
||||
* - `./useSagiBrain`
|
||||
* - `./useSagiPosition`
|
||||
* - `./intents`
|
||||
@@ -78,12 +81,13 @@ import {
|
||||
} from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useSettingsHref } from "../../lib/settingsLink";
|
||||
import { usePrefersReducedMotion } from "../../hooks/usePrefersReducedMotion";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { SagiAvatar } from "./SagiAvatar";
|
||||
import { PetSprite } from "./PetSprite";
|
||||
import { PetMenu } from "./PetMenu";
|
||||
import { SpeechBubble } from "./SpeechBubble";
|
||||
import { SagiPanel } from "./SagiPanel";
|
||||
import { PetNameButton, SagiInfo } from "./SagiInfo";
|
||||
import { useSagiBrain } from "./useSagiBrain";
|
||||
import { useSagiPosition } from "./useSagiPosition";
|
||||
import { useSagiEnabled } from "./SagiMount";
|
||||
@@ -94,7 +98,8 @@ import { api } from "../../lib/api";
|
||||
import { readDefaultTool } from "../../lib/sessionDefaults";
|
||||
import { startInFreeTabDetailed } from "../lanes/startSession";
|
||||
import { workspaceHref } from "../SessionRowMenu";
|
||||
import { PetChat, petChatTool } from "./PetChat";
|
||||
import { Heart } from "lucide-react";
|
||||
import { PetChat, petChatTool, type PetLocalReply } from "./PetChat";
|
||||
|
||||
// Stroking: this many left/right turns of the pointer over the pet, within
|
||||
// STROKE_MS and with no button held, is a pat; then a pause before the next.
|
||||
@@ -126,23 +131,6 @@ interface Anchor {
|
||||
dragging: boolean;
|
||||
}
|
||||
|
||||
/** The OS "reduce motion" preference, followed live. */
|
||||
export function usePrefersReducedMotion(): boolean {
|
||||
const [reduced, setReduced] = useState(
|
||||
() =>
|
||||
typeof window !== "undefined" &&
|
||||
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches
|
||||
);
|
||||
useEffect(() => {
|
||||
const mq = window.matchMedia?.("(prefers-reduced-motion: reduce)");
|
||||
if (!mq) return;
|
||||
const onChange = () => setReduced(mq.matches);
|
||||
mq.addEventListener?.("change", onChange);
|
||||
return () => mq.removeEventListener?.("change", onChange);
|
||||
}, []);
|
||||
return reduced;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fixed-position wrapper that places its content next to the avatar and clamps
|
||||
* it inside the viewport. It measures itself (and re-measures on content/size
|
||||
@@ -241,10 +229,8 @@ function SagiBody() {
|
||||
// The name it goes by: the user's nickname, the pet's own, else Sagi.
|
||||
const [name, setName] = useState(() => petName(sagiPrefs.getPet()));
|
||||
const [size, setSize] = useState(() => sagiPrefs.getSize());
|
||||
// The chat window (PetChat.tsx): the pet's whole UI.
|
||||
const [open, setOpen] = useState(false);
|
||||
// The chat window (PetChat.tsx), and the Ask question it should send.
|
||||
const [chatOpen, setChatOpen] = useState(false);
|
||||
const [chatPrompt, setChatPrompt] = useState<string | null>(null);
|
||||
// The right-click pet menu (`PetMenu.tsx`).
|
||||
const [menu, setMenu] = useState(false);
|
||||
const [hover, setHover] = useState(false);
|
||||
@@ -296,7 +282,6 @@ function SagiBody() {
|
||||
setOpen((v) => !v);
|
||||
} else if (e.key === "Escape") {
|
||||
setOpen(false);
|
||||
setChatOpen(false);
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
@@ -346,7 +331,6 @@ function SagiBody() {
|
||||
navigate(workspaceHref(s, runs) ?? `/sessions/${encodeURIComponent(s.id)}`);
|
||||
brain.dismissBubble();
|
||||
setOpen(false);
|
||||
setChatOpen(false);
|
||||
};
|
||||
api.run
|
||||
.list()
|
||||
@@ -356,21 +340,17 @@ function SagiBody() {
|
||||
[brain, navigate]
|
||||
);
|
||||
|
||||
const onAsk = useCallback(
|
||||
(query: string): string | null => {
|
||||
// Asked by the chat before any session runs.
|
||||
const onLocal = useCallback(
|
||||
(query: string): PetLocalReply => {
|
||||
const result = matchIntent(query, brain.status, { name, attention: brain.attention });
|
||||
if (result.kind === "answer") {
|
||||
if (result.moment) brain.playMoment(result.moment);
|
||||
return result.text;
|
||||
}
|
||||
// Handoff: a question the pet cannot answer goes to the chat window,
|
||||
// which starts a session of the default AI tool and shows it as chat.
|
||||
if (petChatTool()) {
|
||||
setChatPrompt(result.prompt);
|
||||
setOpen(false);
|
||||
setChatOpen(true);
|
||||
return null;
|
||||
return { answer: result.text };
|
||||
}
|
||||
// A question the pet cannot answer: the chat starts a session of the
|
||||
// default AI tool and shows it as chat.
|
||||
if (petChatTool()) return null;
|
||||
// A default tool the chat cannot read back (not Claude/Codex): start it
|
||||
// in the "Sagi" workspace and open its pane there, as before.
|
||||
const prompt = result.prompt;
|
||||
@@ -392,7 +372,7 @@ function SagiBody() {
|
||||
brain.setThinking(false);
|
||||
}
|
||||
})();
|
||||
return null;
|
||||
return { handled: true };
|
||||
},
|
||||
[brain, navigate, t, name]
|
||||
);
|
||||
@@ -431,46 +411,49 @@ function SagiBody() {
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* The panel is too big to drag around, so it hides mid-drag. The bubble
|
||||
does not - it is Sagi talking, and it has to stay by its mouth. */}
|
||||
{!place.dragging && open && (
|
||||
<SagiFlyout anchor={anchor}>
|
||||
<SagiPanel
|
||||
name={name}
|
||||
ownName={"kind" in pet ? pet.name || "Sagi" : "Sagi"}
|
||||
nickname={sagiPrefs.getNickname(pet.id)}
|
||||
onRename={(next) => sagiPrefs.setNickname(pet.id, next)}
|
||||
onPat={brain.pat}
|
||||
attention={brain.attention}
|
||||
onOpenSession={openSession}
|
||||
status={brain.status}
|
||||
muted={brain.muted}
|
||||
onToggleMute={brain.toggleMute}
|
||||
onClearAlerts={brain.clearAlerts}
|
||||
onNavigate={onNavigate}
|
||||
onAsk={onAsk}
|
||||
onClose={() => setOpen(false)}
|
||||
/>
|
||||
</SagiFlyout>
|
||||
)}
|
||||
|
||||
{/* Beside the pet, riding along with it mid-drag too (SagiFlyout follows
|
||||
it 1:1), and kept mounted: unmounting would detach its terminal and
|
||||
lose a half-typed message. */}
|
||||
{chatOpen && (
|
||||
it 1:1). Closing unmounts it; its chat is remembered, so reopening
|
||||
re-attaches the same session. */}
|
||||
{open && (
|
||||
<SagiFlyout anchor={anchor} beside>
|
||||
<PetChat
|
||||
name={name}
|
||||
initialPrompt={chatPrompt}
|
||||
onPromptTaken={() => setChatPrompt(null)}
|
||||
onBack={() => {
|
||||
setChatOpen(false);
|
||||
setOpen(true);
|
||||
}}
|
||||
onClose={() => setChatOpen(false)}
|
||||
title={
|
||||
<PetNameButton
|
||||
name={name}
|
||||
ownName={"kind" in pet ? pet.name || "Sagi" : "Sagi"}
|
||||
nickname={sagiPrefs.getNickname(pet.id)}
|
||||
onRename={(next) => sagiPrefs.setNickname(pet.id, next)}
|
||||
/>
|
||||
}
|
||||
headerActions={
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-full p-1.5 text-fg-muted transition-colors hover:bg-surface-4 hover:text-status-danger"
|
||||
onClick={brain.pat}
|
||||
aria-label={t("sagi.panel.pat", { name })}
|
||||
title={t("sagi.panel.pat", { name })}
|
||||
>
|
||||
<Heart size={15} />
|
||||
</button>
|
||||
}
|
||||
info={
|
||||
<SagiInfo
|
||||
attention={brain.attention}
|
||||
onOpenSession={openSession}
|
||||
status={brain.status}
|
||||
muted={brain.muted}
|
||||
onToggleMute={brain.toggleMute}
|
||||
onClearAlerts={brain.clearAlerts}
|
||||
onNavigate={onNavigate}
|
||||
defaultOpen={brain.attention.length > 0}
|
||||
/>
|
||||
}
|
||||
onLocal={onLocal}
|
||||
onClose={() => setOpen(false)}
|
||||
onOpenWorkspace={(laneId, runId) => {
|
||||
navigate(`/workspace?lane=${laneId}&run=${encodeURIComponent(runId)}`);
|
||||
setChatOpen(false);
|
||||
setOpen(false);
|
||||
}}
|
||||
onBusy={onBusy}
|
||||
/>
|
||||
@@ -491,7 +474,7 @@ function SagiBody() {
|
||||
</SagiFlyout>
|
||||
)}
|
||||
|
||||
{!open && !menu && !chatOpen && brain.bubble && (
|
||||
{!open && !menu && brain.bubble && (
|
||||
<SagiFlyout anchor={anchor}>
|
||||
<SpeechBubble
|
||||
bubble={brain.bubble}
|
||||
@@ -519,18 +502,16 @@ function SagiBody() {
|
||||
// A drag just ended - swallow the synthetic click so the panel
|
||||
// doesn't toggle when the user only repositioned the avatar.
|
||||
if (place.consumeDrag()) return;
|
||||
if (chatOpen) setChatOpen(false);
|
||||
else setOpen((v) => !v);
|
||||
setOpen((v) => !v);
|
||||
}}
|
||||
// Right-click: the pet menu (hide, size, choose, upload, import).
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault();
|
||||
setOpen(false);
|
||||
setChatOpen(false);
|
||||
setMenu(true);
|
||||
}}
|
||||
aria-label={open || chatOpen ? t("sagi.closeAvatar", { name }) : t("sagi.open", { name })}
|
||||
aria-expanded={open || chatOpen}
|
||||
aria-label={open ? t("sagi.closeAvatar", { name }) : t("sagi.open", { name })}
|
||||
aria-expanded={open}
|
||||
title={t("sagi.avatarTitle", { name })}
|
||||
>
|
||||
{pet.id === "sagi" || !("kind" in pet) ? (
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
/**
|
||||
* @file SagiInfo.tsx
|
||||
* @description What the pet knows, shown inside its chat window (`PetChat`):
|
||||
* the name you rename by clicking it (`PetNameButton`), and a status strip
|
||||
* (`SagiInfo`) — live / waiting / errored counts and the connection state
|
||||
* always in sight, and on expanding, the sessions that need the user, by
|
||||
* name, plus Mute and Clear alerts. Pure presentational: all data and
|
||||
* behavior are injected by the container (`Sagi.tsx`).
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { useState } from "react";
|
||||
import {
|
||||
AlertTriangle,
|
||||
Bell,
|
||||
BellOff,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
Hourglass,
|
||||
Radio,
|
||||
Trash2,
|
||||
type LucideIcon,
|
||||
} from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { subjectLabel, type AttentionItem, type SagiStatus, type SagiSubject } from "./brain";
|
||||
import { PET_NAME_MAX } from "./prefs";
|
||||
|
||||
/** How many sessions the "Needs you" list shows before pointing at Sessions. */
|
||||
const ATTENTION_SHOWN = 4;
|
||||
|
||||
/** The pet's name; a click renames it in place (empty = its own name). */
|
||||
export function PetNameButton({
|
||||
name,
|
||||
ownName,
|
||||
nickname,
|
||||
onRename,
|
||||
}: {
|
||||
name: string;
|
||||
ownName: string;
|
||||
nickname: string;
|
||||
onRename: (name: string) => void;
|
||||
}) {
|
||||
const { t } = useTranslation("settings");
|
||||
// The name being typed, or null while not renaming.
|
||||
const [renaming, setRenaming] = useState<string | null>(null);
|
||||
const save = () => {
|
||||
if (renaming === null) return;
|
||||
onRename(renaming);
|
||||
setRenaming(null);
|
||||
};
|
||||
return renaming === null ? (
|
||||
<button
|
||||
type="button"
|
||||
className="max-w-full truncate rounded px-0.5 text-sm font-semibold text-fg-primary hover:bg-surface-4"
|
||||
onClick={() => setRenaming(nickname)}
|
||||
aria-label={t("sagi.panel.rename", { name })}
|
||||
title={t("sagi.panel.rename", { name })}
|
||||
>
|
||||
{name}
|
||||
</button>
|
||||
) : (
|
||||
<input
|
||||
autoFocus
|
||||
className="w-28 rounded border border-accent bg-surface-1 px-1 py-0.5 text-sm text-fg-primary focus:outline-none"
|
||||
value={renaming}
|
||||
maxLength={PET_NAME_MAX}
|
||||
placeholder={ownName}
|
||||
aria-label={t("sagi.panel.renameLabel")}
|
||||
title={t("sagi.panel.renameHint")}
|
||||
onChange={(e) => setRenaming(e.target.value)}
|
||||
onBlur={save}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
save();
|
||||
} else if (e.key === "Escape") {
|
||||
// Esc cancels the rename only, not the whole chat.
|
||||
e.stopPropagation();
|
||||
e.nativeEvent.stopImmediatePropagation();
|
||||
setRenaming(null);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface SagiInfoProps {
|
||||
attention: ReadonlyArray<AttentionItem>;
|
||||
onOpenSession: (s: SagiSubject) => void;
|
||||
status: SagiStatus;
|
||||
muted: boolean;
|
||||
onToggleMute: () => void;
|
||||
onClearAlerts: () => void;
|
||||
onNavigate: (route: string) => void;
|
||||
/** Expanded at first: the sessions that need the user and the actions. */
|
||||
defaultOpen?: boolean;
|
||||
}
|
||||
|
||||
/** The status strip under the chat's header. */
|
||||
export function SagiInfo({
|
||||
attention,
|
||||
onOpenSession,
|
||||
status,
|
||||
muted,
|
||||
onToggleMute,
|
||||
onClearAlerts,
|
||||
onNavigate,
|
||||
defaultOpen = false,
|
||||
}: SagiInfoProps) {
|
||||
const { t } = useTranslation("settings");
|
||||
const [open, setOpen] = useState(defaultOpen);
|
||||
const Chevron = open ? ChevronDown : ChevronRight;
|
||||
return (
|
||||
<div className="pet-chat-info border-b border-border/60 px-3 py-2">
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-center gap-1.5 rounded-lg text-left"
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
aria-expanded={open}
|
||||
aria-label={t("sagi.chat.status")}
|
||||
title={t("sagi.chat.status")}
|
||||
>
|
||||
<StatChip
|
||||
icon={Radio}
|
||||
label={t("sagi.panel.statLive")}
|
||||
value={status.liveCount}
|
||||
tone={status.liveCount > 0 ? "accent" : "muted"}
|
||||
/>
|
||||
<StatChip
|
||||
icon={Hourglass}
|
||||
label={t("sagi.panel.statWaiting")}
|
||||
value={status.waitingCount}
|
||||
tone={status.waitingCount > 0 ? "amber" : "muted"}
|
||||
/>
|
||||
<StatChip
|
||||
icon={AlertTriangle}
|
||||
label={t("sagi.panel.statErrored")}
|
||||
value={status.errorCount}
|
||||
tone={status.errorCount > 0 ? "red" : "muted"}
|
||||
/>
|
||||
<span
|
||||
className={`ml-auto inline-flex items-center gap-1 rounded-full px-1.5 py-0.5 text-[10px] font-medium ${
|
||||
status.connected
|
||||
? "bg-status-success/15 text-status-success"
|
||||
: "bg-status-danger/15 text-status-danger"
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`inline-block h-1.5 w-1.5 rounded-full ${
|
||||
status.connected ? "bg-status-success" : "bg-status-danger"
|
||||
}`}
|
||||
aria-hidden
|
||||
/>
|
||||
{status.connected ? t("sagi.panel.live") : t("sagi.panel.offline")}
|
||||
</span>
|
||||
<Chevron size={13} className="shrink-0 text-fg-muted" aria-hidden />
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<div className="mt-2 max-h-48 overflow-y-auto">
|
||||
{/* the sessions that need the user, by name */}
|
||||
{attention.length > 0 && (
|
||||
<div className="mb-2">
|
||||
<div className="mb-1 text-[10px] font-medium uppercase tracking-wider text-fg-muted">
|
||||
{t("sagi.panel.attention")}
|
||||
</div>
|
||||
<ul className="space-y-1">
|
||||
{attention.slice(0, ATTENTION_SHOWN).map((item) => (
|
||||
<li key={item.id}>
|
||||
<button
|
||||
className="group flex w-full items-center gap-2 rounded-lg bg-surface-1 px-2 py-1.5 text-left text-xs transition-colors hover:bg-surface-4"
|
||||
onClick={() => onOpenSession(item)}
|
||||
title={item.cwd ?? item.id}
|
||||
>
|
||||
{item.kind === "error" ? (
|
||||
<AlertTriangle
|
||||
size={13}
|
||||
className="shrink-0 text-status-danger"
|
||||
aria-hidden
|
||||
/>
|
||||
) : (
|
||||
<Hourglass size={13} className="shrink-0 text-status-warning" aria-hidden />
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate text-fg-secondary group-hover:text-fg-primary">
|
||||
{subjectLabel(item)}
|
||||
</span>
|
||||
<span className="shrink-0 text-[10px] text-fg-muted">
|
||||
{item.kind === "error"
|
||||
? t("sagi.panel.attentionError")
|
||||
: t("sagi.panel.attentionWaiting")}
|
||||
</span>
|
||||
<ChevronRight size={12} className="shrink-0 text-fg-muted" aria-hidden />
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{attention.length > ATTENTION_SHOWN && (
|
||||
<button
|
||||
className="mt-1 text-[11px] text-accent hover:underline"
|
||||
onClick={() => onNavigate("/sessions")}
|
||||
>
|
||||
{t("sagi.panel.attentionMore", { count: attention.length - ATTENTION_SHOWN })}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-2 gap-1.5">
|
||||
<ActionButton
|
||||
icon={muted ? BellOff : Bell}
|
||||
label={muted ? t("sagi.panel.unmute") : t("sagi.panel.mute")}
|
||||
onClick={onToggleMute}
|
||||
/>
|
||||
<ActionButton
|
||||
icon={Trash2}
|
||||
label={t("sagi.panel.clearAlerts")}
|
||||
disabled={status.errorCount === 0}
|
||||
onClick={onClearAlerts}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface Tone {
|
||||
wrap: string;
|
||||
value: string;
|
||||
icon: string;
|
||||
}
|
||||
|
||||
const TONE_MUTED: Tone = {
|
||||
wrap: "border-border bg-surface-1",
|
||||
value: "text-fg-secondary",
|
||||
icon: "text-fg-muted",
|
||||
};
|
||||
|
||||
const TONES: Record<string, Tone> = {
|
||||
accent: { wrap: "border-accent/30 bg-accent/10", value: "text-fg-primary", icon: "text-accent" },
|
||||
amber: {
|
||||
wrap: "border-status-warning/30 bg-status-warning/10",
|
||||
value: "text-status-warning",
|
||||
icon: "text-status-warning",
|
||||
},
|
||||
red: {
|
||||
wrap: "border-status-danger/30 bg-status-danger/10",
|
||||
value: "text-status-danger",
|
||||
icon: "text-status-danger",
|
||||
},
|
||||
muted: TONE_MUTED,
|
||||
};
|
||||
|
||||
/** One count, compact: icon, number, label on one line. */
|
||||
function StatChip({
|
||||
icon: Icon,
|
||||
label,
|
||||
value,
|
||||
tone,
|
||||
}: {
|
||||
icon: LucideIcon;
|
||||
label: string;
|
||||
value: number;
|
||||
tone: string;
|
||||
}) {
|
||||
const t = TONES[tone] ?? TONE_MUTED;
|
||||
return (
|
||||
<span className={`inline-flex items-center gap-1 rounded-full border px-1.5 py-0.5 ${t.wrap}`}>
|
||||
<Icon size={11} className={t.icon} aria-hidden />
|
||||
<span className={`text-xs font-semibold tabular-nums ${t.value}`}>{value}</span>
|
||||
<span className="text-[9px] uppercase tracking-wider text-fg-muted">{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function ActionButton({
|
||||
icon: Icon,
|
||||
label,
|
||||
onClick,
|
||||
disabled,
|
||||
}: {
|
||||
icon: LucideIcon;
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
className="flex w-full items-center gap-1.5 rounded-lg bg-surface-1 px-2 py-1.5 text-xs text-fg-secondary transition-colors hover:bg-surface-4 hover:text-fg-primary disabled:cursor-not-allowed disabled:opacity-40"
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
>
|
||||
<Icon size={14} className="shrink-0" />
|
||||
<span className="truncate">{label}</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -1,392 +0,0 @@
|
||||
/**
|
||||
* @file SagiPanel.tsx
|
||||
* @description Expanded Sagi panel: a live status strip (live / waiting /
|
||||
* errored stat chips + connection state), quick navigation actions, and a
|
||||
* local "Ask" box. Pure presentational - all data and the ask/navigation
|
||||
* behavior are injected by the container.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
/* =============================================================================
|
||||
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
|
||||
* =============================================================================
|
||||
* **Purpose:** Sagi is the optional on-screen mascot assistant — quips, intents, and lightweight event reactions layered above the dashboard chrome.
|
||||
*
|
||||
* ## Design constraints
|
||||
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
|
||||
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
|
||||
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
|
||||
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
|
||||
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
|
||||
*
|
||||
* ## Remote data & SSH
|
||||
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
|
||||
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
|
||||
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
|
||||
*
|
||||
* ## Internal dependencies
|
||||
* - `./brain`
|
||||
*
|
||||
* ## Public surface
|
||||
* - `SagiPanel` — exported API; see TSDoc on the symbol for behavior.
|
||||
*
|
||||
* ## Testing pointers
|
||||
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
|
||||
* - Server contract changes require `npm run test:server` and OpenAPI sync.
|
||||
*
|
||||
* ## Related docs
|
||||
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
|
||||
* - `docs/API.md` — REST reference.
|
||||
* - `skills/file-headers/` — mandatory `@author` header policy.
|
||||
* ============================================================================= */
|
||||
/* -----------------------------------------------------------------------------
|
||||
* EXPORT CATALOG — quick index of symbols defined below (documentation only).
|
||||
* -----------------------------------------------------------------------------
|
||||
* **SagiPanel**
|
||||
* Part of this module's public contract. Downstream imports should treat
|
||||
* the signature and return type as stable unless release notes say otherwise.
|
||||
* When behavior changes, update the `@file` overview and relevant tests.
|
||||
*
|
||||
* ----------------------------------------------------------------------------- */
|
||||
|
||||
import { useState, type FormEvent, type ReactNode } from "react";
|
||||
import {
|
||||
Bell,
|
||||
BellOff,
|
||||
Trash2,
|
||||
X,
|
||||
Send,
|
||||
AlertTriangle,
|
||||
Hourglass,
|
||||
Radio,
|
||||
Heart,
|
||||
ChevronRight,
|
||||
type LucideIcon,
|
||||
} from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { subjectLabel, type AttentionItem, type SagiStatus, type SagiSubject } from "./brain";
|
||||
import { PET_NAME_MAX } from "./prefs";
|
||||
|
||||
/** How many sessions the "Needs you" list shows before pointing at Sessions. */
|
||||
const ATTENTION_SHOWN = 4;
|
||||
|
||||
interface SagiPanelProps {
|
||||
/** The name the pet goes by now. */
|
||||
name: string;
|
||||
/** The pet's own name, which an empty nickname falls back to. */
|
||||
ownName: string;
|
||||
/** The user's nickname for the pet, "" when none. */
|
||||
nickname: string;
|
||||
onRename: (name: string) => void;
|
||||
onPat: () => void;
|
||||
/** Errored, then waiting sessions, named. */
|
||||
attention: ReadonlyArray<AttentionItem>;
|
||||
onOpenSession: (s: SagiSubject) => void;
|
||||
status: SagiStatus;
|
||||
muted: boolean;
|
||||
onToggleMute: () => void;
|
||||
onClearAlerts: () => void;
|
||||
onNavigate: (route: string) => void;
|
||||
/** Returns an answer to display, or null when the query was handed off. */
|
||||
onAsk: (query: string) => string | null;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function SagiPanel({
|
||||
name,
|
||||
ownName,
|
||||
nickname,
|
||||
onRename,
|
||||
onPat,
|
||||
attention,
|
||||
onOpenSession,
|
||||
status,
|
||||
muted,
|
||||
onToggleMute,
|
||||
onClearAlerts,
|
||||
onNavigate,
|
||||
onAsk,
|
||||
onClose,
|
||||
}: SagiPanelProps) {
|
||||
const { t } = useTranslation("settings");
|
||||
const [query, setQuery] = useState("");
|
||||
const [answer, setAnswer] = useState<string | null>(null);
|
||||
// The name being typed, or null while not renaming.
|
||||
const [renaming, setRenaming] = useState<string | null>(null);
|
||||
const saveName = () => {
|
||||
if (renaming === null) return;
|
||||
onRename(renaming);
|
||||
setRenaming(null);
|
||||
};
|
||||
|
||||
const submit = (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
const result = onAsk(query);
|
||||
setAnswer(result); // null means it handed off (container navigates/closes)
|
||||
setQuery("");
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className="w-72 overflow-hidden rounded-2xl border border-border-light bg-surface-2/95 shadow-2xl backdrop-blur-md animate-slide-up"
|
||||
role="dialog"
|
||||
aria-label={t("sagi.panel.label", { name })}
|
||||
>
|
||||
{/* header */}
|
||||
<div className="flex items-center justify-between gap-2 border-b border-border/70 bg-gradient-to-r from-accent/10 to-transparent px-3.5 py-2.5">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<span className="text-base leading-none" aria-hidden>
|
||||
🐾
|
||||
</span>
|
||||
{renaming === null ? (
|
||||
<button
|
||||
type="button"
|
||||
className="min-w-0 truncate rounded px-0.5 text-sm font-semibold text-fg-primary hover:bg-surface-4"
|
||||
onClick={() => setRenaming(nickname)}
|
||||
aria-label={t("sagi.panel.rename", { name })}
|
||||
title={t("sagi.panel.rename", { name })}
|
||||
>
|
||||
{name}
|
||||
</button>
|
||||
) : (
|
||||
<input
|
||||
autoFocus
|
||||
className="w-28 rounded border border-accent bg-surface-1 px-1 py-0.5 text-sm text-fg-primary focus:outline-none"
|
||||
value={renaming}
|
||||
maxLength={PET_NAME_MAX}
|
||||
placeholder={ownName}
|
||||
aria-label={t("sagi.panel.renameLabel")}
|
||||
title={t("sagi.panel.renameHint")}
|
||||
onChange={(e) => setRenaming(e.target.value)}
|
||||
onBlur={saveName}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
saveName();
|
||||
} else if (e.key === "Escape") {
|
||||
// Esc cancels the rename only, not the whole panel.
|
||||
e.stopPropagation();
|
||||
e.nativeEvent.stopImmediatePropagation();
|
||||
setRenaming(null);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<span
|
||||
className={`ml-0.5 inline-flex items-center gap-1 rounded-full px-1.5 py-0.5 text-[10px] font-medium ${
|
||||
status.connected
|
||||
? "bg-status-success/15 text-status-success"
|
||||
: "bg-status-danger/15 text-status-danger"
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`inline-block h-1.5 w-1.5 rounded-full ${
|
||||
status.connected ? "bg-status-success" : "bg-status-danger"
|
||||
}`}
|
||||
aria-hidden
|
||||
/>
|
||||
{status.connected ? t("sagi.panel.live") : t("sagi.panel.offline")}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center">
|
||||
<button
|
||||
className="rounded-md p-1 text-fg-muted transition-colors hover:bg-surface-4 hover:text-status-danger"
|
||||
onClick={onPat}
|
||||
aria-label={t("sagi.panel.pat", { name })}
|
||||
title={t("sagi.panel.pat", { name })}
|
||||
>
|
||||
<Heart size={15} />
|
||||
</button>
|
||||
<button
|
||||
className="rounded-md p-1 text-fg-muted transition-colors hover:bg-surface-4 hover:text-fg-secondary"
|
||||
onClick={onClose}
|
||||
aria-label={t("sagi.panel.close", { name })}
|
||||
>
|
||||
<X size={15} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-3">
|
||||
{/* status stat chips */}
|
||||
<div className="mb-3 grid grid-cols-3 gap-1.5">
|
||||
<StatChip
|
||||
icon={Radio}
|
||||
label={t("sagi.panel.statLive")}
|
||||
value={status.liveCount}
|
||||
tone={status.liveCount > 0 ? "accent" : "muted"}
|
||||
/>
|
||||
<StatChip
|
||||
icon={Hourglass}
|
||||
label={t("sagi.panel.statWaiting")}
|
||||
value={status.waitingCount}
|
||||
tone={status.waitingCount > 0 ? "amber" : "muted"}
|
||||
/>
|
||||
<StatChip
|
||||
icon={AlertTriangle}
|
||||
label={t("sagi.panel.statErrored")}
|
||||
value={status.errorCount}
|
||||
tone={status.errorCount > 0 ? "red" : "muted"}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* the sessions that need the user, by name */}
|
||||
{attention.length > 0 && (
|
||||
<div className="mb-3">
|
||||
<div className="mb-1 text-[10px] font-medium uppercase tracking-wider text-fg-muted">
|
||||
{t("sagi.panel.attention")}
|
||||
</div>
|
||||
<ul className="space-y-1">
|
||||
{attention.slice(0, ATTENTION_SHOWN).map((item) => (
|
||||
<li key={item.id}>
|
||||
<button
|
||||
className="group flex w-full items-center gap-2 rounded-lg bg-surface-1 px-2 py-1.5 text-left text-xs transition-colors hover:bg-surface-4"
|
||||
onClick={() => onOpenSession(item)}
|
||||
title={item.cwd ?? item.id}
|
||||
>
|
||||
{item.kind === "error" ? (
|
||||
<AlertTriangle
|
||||
size={13}
|
||||
className="shrink-0 text-status-danger"
|
||||
aria-hidden
|
||||
/>
|
||||
) : (
|
||||
<Hourglass size={13} className="shrink-0 text-status-warning" aria-hidden />
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate text-fg-secondary group-hover:text-fg-primary">
|
||||
{subjectLabel(item)}
|
||||
</span>
|
||||
<span className="shrink-0 text-[10px] text-fg-muted">
|
||||
{item.kind === "error"
|
||||
? t("sagi.panel.attentionError")
|
||||
: t("sagi.panel.attentionWaiting")}
|
||||
</span>
|
||||
<ChevronRight size={12} className="shrink-0 text-fg-muted" aria-hidden />
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{attention.length > ATTENTION_SHOWN && (
|
||||
<button
|
||||
className="mt-1 text-[11px] text-accent hover:underline"
|
||||
onClick={() => onNavigate("/sessions")}
|
||||
>
|
||||
{t("sagi.panel.attentionMore", { count: attention.length - ATTENTION_SHOWN })}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* quick actions */}
|
||||
<div className="mb-3 grid grid-cols-2 gap-1.5">
|
||||
<ActionButton
|
||||
icon={muted ? BellOff : Bell}
|
||||
label={muted ? t("sagi.panel.unmute") : t("sagi.panel.mute")}
|
||||
onClick={onToggleMute}
|
||||
/>
|
||||
<ActionButton
|
||||
icon={Trash2}
|
||||
label={t("sagi.panel.clearAlerts")}
|
||||
disabled={status.errorCount === 0}
|
||||
onClick={onClearAlerts}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* ask */}
|
||||
<form onSubmit={submit} className="flex items-center gap-1.5">
|
||||
<input
|
||||
className="flex-1 rounded-lg border border-border bg-surface-1 px-2.5 py-1.5 text-xs text-fg-secondary placeholder-fg-muted transition-colors focus:border-accent focus:outline-none focus:ring-1 focus:ring-accent/30"
|
||||
placeholder={t("sagi.panel.askPlaceholder", { name })}
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
aria-label={t("sagi.panel.ask", { name })}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
className="btn-primary justify-center px-2.5 py-2"
|
||||
aria-label={t("sagi.panel.send")}
|
||||
>
|
||||
<Send size={14} />
|
||||
</button>
|
||||
</form>
|
||||
{answer && (
|
||||
<p className="mt-2 rounded-lg bg-surface-1/70 px-2.5 py-2 text-xs leading-relaxed text-fg-secondary">
|
||||
{answer}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface Tone {
|
||||
wrap: string;
|
||||
value: string;
|
||||
icon: string;
|
||||
}
|
||||
|
||||
const TONE_MUTED: Tone = {
|
||||
wrap: "border-border bg-surface-1",
|
||||
value: "text-fg-secondary",
|
||||
icon: "text-fg-muted",
|
||||
};
|
||||
|
||||
const TONES: Record<string, Tone> = {
|
||||
accent: { wrap: "border-accent/30 bg-accent/10", value: "text-fg-primary", icon: "text-accent" },
|
||||
amber: {
|
||||
wrap: "border-status-warning/30 bg-status-warning/10",
|
||||
value: "text-status-warning",
|
||||
icon: "text-status-warning",
|
||||
},
|
||||
red: {
|
||||
wrap: "border-status-danger/30 bg-status-danger/10",
|
||||
value: "text-status-danger",
|
||||
icon: "text-status-danger",
|
||||
},
|
||||
muted: TONE_MUTED,
|
||||
};
|
||||
|
||||
function StatChip({
|
||||
icon: Icon,
|
||||
label,
|
||||
value,
|
||||
tone,
|
||||
}: {
|
||||
icon: LucideIcon;
|
||||
label: string;
|
||||
value: number;
|
||||
tone: string;
|
||||
}): ReactNode {
|
||||
const t = TONES[tone] ?? TONE_MUTED;
|
||||
return (
|
||||
<div className={`flex flex-col items-center gap-0.5 rounded-xl border py-1.5 ${t.wrap}`}>
|
||||
<Icon size={13} className={t.icon} aria-hidden />
|
||||
<span className={`text-base font-semibold leading-none tabular-nums ${t.value}`}>
|
||||
{value}
|
||||
</span>
|
||||
<span className="text-[9px] uppercase tracking-wider text-fg-muted">{label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ActionButton({
|
||||
icon: Icon,
|
||||
label,
|
||||
onClick,
|
||||
disabled,
|
||||
}: {
|
||||
icon: LucideIcon;
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
className="flex w-full items-center gap-1.5 rounded-lg bg-surface-1 px-2 py-1.5 text-xs text-fg-secondary transition-colors hover:bg-surface-4 hover:text-fg-primary disabled:cursor-not-allowed disabled:opacity-40"
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
>
|
||||
<Icon size={14} className="shrink-0" />
|
||||
<span className="truncate">{label}</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* @file Sagi.test.tsx
|
||||
* @description Render tests for the Sagi companion component — mounting, mood rendering, the ⌘B panel toggle, and accessibility attributes.
|
||||
* @description Render tests for the Sagi companion component — mounting, mood rendering, the ⌘B chat toggle (the chat window is the pet's whole UI: status strip, local answers, New chat stopping the old session), and accessibility attributes.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
@@ -18,6 +18,7 @@ import { useSagiPosition } from "../useSagiPosition";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { Sagi } from "../Sagi";
|
||||
import { eventBus } from "../../../lib/eventBus";
|
||||
import { api } from "../../../lib/api";
|
||||
import type { WSMessage, Session } from "../../../lib/types";
|
||||
|
||||
function renderSagi() {
|
||||
@@ -54,13 +55,13 @@ describe("Sagi widget", () => {
|
||||
expect(screen.getByRole("img", { name: /sagi/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("opens the panel on click and answers a local status question", () => {
|
||||
it("opens the chat on click and answers a local status question there", () => {
|
||||
renderSagi();
|
||||
fireEvent.click(screen.getByRole("button", { name: /open sagi companion/i }));
|
||||
const panel = screen.getByRole("dialog", { name: /sagi companion/i });
|
||||
const panel = screen.getByRole("dialog", { name: /chat with sagi/i });
|
||||
expect(panel).toBeInTheDocument();
|
||||
|
||||
const input = within(panel).getByLabelText(/ask sagi/i);
|
||||
const input = within(panel).getByLabelText(/ask sagi anything/i);
|
||||
fireEvent.change(input, { target: { value: "status" } });
|
||||
fireEvent.submit(input.closest("form")!);
|
||||
expect(within(panel).getByText(/live ·/i)).toBeInTheDocument();
|
||||
@@ -88,7 +89,7 @@ describe("Sagi widget", () => {
|
||||
expect(within(btn).getByText("1")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("names the errored session in its bubble and in the panel", () => {
|
||||
it("names the errored session in its bubble and in the chat", () => {
|
||||
renderSagi();
|
||||
act(() => {
|
||||
eventBus.publish({
|
||||
@@ -101,7 +102,7 @@ describe("Sagi widget", () => {
|
||||
expect(within(bubble).getByText("Fix login")).toBeInTheDocument();
|
||||
expect(within(bubble).getByRole("button", { name: "Open" })).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: /open sagi companion/i }));
|
||||
const panel = screen.getByRole("dialog", { name: /sagi companion/i });
|
||||
const panel = screen.getByRole("dialog", { name: /chat with sagi/i });
|
||||
expect(within(panel).getByText("Needs you")).toBeInTheDocument();
|
||||
expect(within(panel).getByRole("button", { name: /Fix login/ })).toBeInTheDocument();
|
||||
});
|
||||
@@ -121,43 +122,54 @@ describe("Sagi widget", () => {
|
||||
expect(JSON.parse(localStorage.getItem("agenthub.pet.dismissedErrors")!)).toEqual(["a"]);
|
||||
});
|
||||
|
||||
it("renames the pet from the panel header", () => {
|
||||
it("renames the pet from the chat header", () => {
|
||||
renderSagi();
|
||||
fireEvent.click(screen.getByRole("button", { name: /open sagi companion/i }));
|
||||
fireEvent.click(screen.getByRole("button", { name: /rename sagi/i }));
|
||||
const input = screen.getByLabelText("Pet name");
|
||||
fireEvent.change(input, { target: { value: "Mochi" } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
expect(screen.getByRole("dialog", { name: /mochi companion/i })).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/ask mochi/i)).toBeInTheDocument();
|
||||
expect(screen.getByRole("dialog", { name: /chat with mochi/i })).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/ask mochi anything/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("hands a question it cannot answer to the chat window", () => {
|
||||
it("hands a question it cannot answer to the AI", () => {
|
||||
localStorage.setItem("agenthub.defaultTool", "claude");
|
||||
const ensure = vi.spyOn(api.lanes, "ensure").mockReturnValue(new Promise(() => {}));
|
||||
renderSagi();
|
||||
fireEvent.click(screen.getByRole("button", { name: /open sagi companion/i }));
|
||||
const input = screen.getByLabelText(/ask sagi/i);
|
||||
fireEvent.change(input, { target: { value: "write me a haiku" } });
|
||||
fireEvent.submit(input.closest("form")!);
|
||||
const chat = screen.getByRole("dialog", { name: /chat with sagi/i });
|
||||
expect(within(chat).getByText("write me a haiku")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("dialog", { name: /sagi companion/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("has no Chat button — Ask opens the chat — and Back returns to the panel", () => {
|
||||
localStorage.setItem("agenthub.defaultTool", "claude");
|
||||
renderSagi();
|
||||
fireEvent.click(screen.getByRole("button", { name: /open sagi companion/i }));
|
||||
expect(screen.queryByRole("button", { name: /chat with sagi/i })).not.toBeInTheDocument();
|
||||
const input = screen.getByLabelText(/ask sagi/i);
|
||||
const input = within(chat).getByLabelText(/ask sagi anything/i);
|
||||
fireEvent.change(input, { target: { value: "write me a haiku" } });
|
||||
fireEvent.submit(input.closest("form")!);
|
||||
expect(screen.getByRole("dialog", { name: /chat with sagi/i })).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Back" }));
|
||||
expect(screen.getByRole("dialog", { name: /sagi companion/i })).toBeInTheDocument();
|
||||
expect(within(chat).getByText("write me a haiku")).toBeInTheDocument();
|
||||
expect(ensure).toHaveBeenCalledWith({ title: "Sagi" });
|
||||
ensure.mockRestore();
|
||||
});
|
||||
|
||||
it("a pat shows its reaction on the pet even while the panel is open", () => {
|
||||
it("reopens the remembered chat, and New chat stops its session", async () => {
|
||||
localStorage.setItem(
|
||||
"agenthub.pet.chat",
|
||||
JSON.stringify({ laneId: 7, runId: "agenthub-lane-7-1", tool: "claude" })
|
||||
);
|
||||
const get = vi
|
||||
.spyOn(api.run, "get")
|
||||
.mockReturnValue(new Promise(() => {}) as ReturnType<typeof api.run.get>);
|
||||
const kill = vi.spyOn(api.run, "kill").mockResolvedValue({ ok: true });
|
||||
renderSagi();
|
||||
fireEvent.click(screen.getByRole("button", { name: /open sagi companion/i }));
|
||||
expect(screen.getByRole("button", { name: /open in workspace/i })).toBeInTheDocument();
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: /new chat/i }));
|
||||
});
|
||||
expect(kill).toHaveBeenCalledWith("agenthub-lane-7-1", { archive: true });
|
||||
expect(localStorage.getItem("agenthub.pet.chat")).toBeNull();
|
||||
expect(screen.queryByRole("button", { name: /open in workspace/i })).not.toBeInTheDocument();
|
||||
get.mockRestore();
|
||||
kill.mockRestore();
|
||||
});
|
||||
|
||||
it("a pat shows its reaction on the pet even while the chat is open", () => {
|
||||
renderSagi();
|
||||
fireEvent.click(screen.getByRole("button", { name: /open sagi companion/i }));
|
||||
fireEvent.click(screen.getByRole("button", { name: /pat sagi/i }));
|
||||
@@ -175,16 +187,16 @@ describe("Sagi widget", () => {
|
||||
expect(pet.querySelector(".sagi-reaction-text")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("reflects the live count in the panel status", () => {
|
||||
it("reflects the live count in the chat status", () => {
|
||||
renderSagi();
|
||||
act(() => {
|
||||
eventBus.publish(sessionMsg("a", "active"));
|
||||
eventBus.publish(sessionMsg("b", "active"));
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: /open sagi companion/i }));
|
||||
const panel = screen.getByRole("dialog", { name: /sagi companion/i });
|
||||
const panel = screen.getByRole("dialog", { name: /chat with sagi/i });
|
||||
// The "live" stat chip shows value 2 next to its label.
|
||||
const liveChip = within(panel).getByText("live").closest("div")!;
|
||||
const liveChip = within(panel).getByText("live").closest("span.rounded-full")! as HTMLElement;
|
||||
expect(within(liveChip).getByText("2")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -194,7 +206,7 @@ describe("Sagi widget", () => {
|
||||
expect(screen.queryByRole("button", { name: /open sagi companion/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("a tap (no movement) still opens the panel", () => {
|
||||
it("a tap (no movement) still opens the chat", () => {
|
||||
renderSagi();
|
||||
const btn = screen.getByRole("button", { name: /open sagi companion/i });
|
||||
act(() => {
|
||||
@@ -202,7 +214,7 @@ describe("Sagi widget", () => {
|
||||
fireEvent.pointerUp(btn, { clientX: 990, clientY: 700 });
|
||||
});
|
||||
fireEvent.click(btn);
|
||||
expect(screen.getByRole("dialog", { name: /sagi companion/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole("dialog", { name: /chat with sagi/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("dragging snaps to an edge, persists position, and does not open the panel", () => {
|
||||
@@ -231,7 +243,7 @@ describe("Sagi widget", () => {
|
||||
fireEvent.pointerUp(btn, { clientX: 992, clientY: 701 });
|
||||
});
|
||||
fireEvent.click(btn);
|
||||
expect(screen.getByRole("dialog", { name: /sagi companion/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole("dialog", { name: /chat with sagi/i })).toBeInTheDocument();
|
||||
// No position was persisted because no real drag happened.
|
||||
expect(localStorage.getItem("agent-dashboard-sagi-pos")).toBeNull();
|
||||
});
|
||||
|
||||
@@ -9,8 +9,12 @@
|
||||
* Workspace page, the open workspace's total (`?lane=` on the same call: the
|
||||
* sessions it owns) and the shown session's (`GET /api/pricing/cost/:id` for
|
||||
* the URL's `session`, or the focused pane's session from the page's run poll,
|
||||
* `LIVE_RUNS_EVENT`), all re-read every 30 s while the tab is visible and
|
||||
* whenever the URL names another workspace or session. Each figure carries its
|
||||
* `LIVE_RUNS_EVENT`), all re-read at once whenever the URL names another
|
||||
* workspace or session, then at most every 30 s while events or session
|
||||
* updates arrive (spend only moves with work) and every 2 min otherwise, while
|
||||
* the tab is visible. The session counts re-read only when a session is
|
||||
* created or its status / waiting / archived state changes (every 60 s
|
||||
* otherwise). Each figure carries its
|
||||
* token total, and hovering it lists tokens and cost per model. At the right
|
||||
* end, the plan quota spent per native tool (`GET /api/pricing/quota`, every
|
||||
* 5 min while visible; a click forces a re-read): one "N% used" chip per tool —
|
||||
@@ -31,9 +35,15 @@ import { fmt, fmtCostFull, formatModelName, timeAgo } from "../lib/format";
|
||||
import { AiToolIcon } from "./AiToolIcon";
|
||||
import { useLiveRefresh } from "../hooks/useLiveRefresh";
|
||||
import { useSpin } from "../hooks/useSpin";
|
||||
import { sessionChangeMatcher } from "../lib/sessionChange";
|
||||
import { LIVE_RUNS_EVENT, selectedFrom } from "./WorkspaceTree";
|
||||
|
||||
/** Spend moves only with work: at most this often while events arrive… */
|
||||
const COST_POLL_MS = 30_000;
|
||||
/** …and this often regardless (date rollover, budget period, a missed frame). */
|
||||
const COST_FALLBACK_MS = 120_000;
|
||||
/** The counts' safety poll; session frames that change a count drive the rest. */
|
||||
const COUNTS_FALLBACK_MS = 60_000;
|
||||
const QUOTA_POLL_MS = 5 * 60_000;
|
||||
const QUOTA_TOOL_LABEL: Record<ToolQuota["id"], string> = {
|
||||
claude: "Claude",
|
||||
@@ -384,51 +394,57 @@ export function StatusBar({
|
||||
.catch(() => undefined);
|
||||
}, []);
|
||||
useEffect(loadCounts, [loadCounts]);
|
||||
useLiveRefresh(loadCounts, {
|
||||
intervalMs: 15_000,
|
||||
match: (msg) => msg.type === "session_updated" || msg.type === "session_created",
|
||||
});
|
||||
// Only a frame that moves a session between the counted states (a new
|
||||
// session, a status / waiting / archived change) re-reads: a session row is
|
||||
// re-broadcast on almost every hook.
|
||||
const [countsChanged] = useState(() => sessionChangeMatcher());
|
||||
useLiveRefresh(loadCounts, { intervalMs: COUNTS_FALLBACK_MS, match: countsChanged });
|
||||
|
||||
// Bumped on every lane/session switch: an answer for the previous one is dropped.
|
||||
const costGen = useRef(0);
|
||||
const loadCosts = useCallback(() => {
|
||||
const gen = costGen.current;
|
||||
const live = () => gen === costGen.current;
|
||||
api.pricing
|
||||
.totalCost({ date: localDate() })
|
||||
.then((r) => live() && setToday(r))
|
||||
.catch(() => undefined);
|
||||
api.budgets
|
||||
.status()
|
||||
.then(({ budgets }) => {
|
||||
const hit = budgets.filter((b) => b.crossed.length > 0).sort((a, b) => b.pct - a.pct);
|
||||
if (live()) setBudget(hit[0] ?? null);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
if (lane !== null) {
|
||||
api.pricing
|
||||
.totalCost({ lane })
|
||||
.then((r) => live() && setLaneCost(r))
|
||||
.catch(() => undefined);
|
||||
}
|
||||
if (sessionId) {
|
||||
api.pricing
|
||||
.sessionCost(sessionId)
|
||||
.then((r) => live() && setSessionCost(r))
|
||||
.catch(() => undefined);
|
||||
}
|
||||
}, [lane, sessionId]);
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
costGen.current++;
|
||||
// Another workspace or session: never show the previous one's figure.
|
||||
setLaneCost(null);
|
||||
setSessionCost(null);
|
||||
const tick = () => {
|
||||
if (document.visibilityState !== "visible") return;
|
||||
api.pricing
|
||||
.totalCost({ date: localDate() })
|
||||
.then((r) => live && setToday(r))
|
||||
.catch(() => undefined);
|
||||
api.budgets
|
||||
.status()
|
||||
.then(({ budgets }) => {
|
||||
const hit = budgets.filter((b) => b.crossed.length > 0).sort((a, b) => b.pct - a.pct);
|
||||
if (live) setBudget(hit[0] ?? null);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
if (lane !== null) {
|
||||
api.pricing
|
||||
.totalCost({ lane })
|
||||
.then((r) => live && setLaneCost(r))
|
||||
.catch(() => undefined);
|
||||
}
|
||||
if (sessionId) {
|
||||
api.pricing
|
||||
.sessionCost(sessionId)
|
||||
.then((r) => live && setSessionCost(r))
|
||||
.catch(() => undefined);
|
||||
}
|
||||
};
|
||||
tick();
|
||||
const id = setInterval(tick, COST_POLL_MS);
|
||||
document.addEventListener("visibilitychange", tick);
|
||||
if (document.visibilityState === "visible") loadCosts();
|
||||
return () => {
|
||||
live = false;
|
||||
clearInterval(id);
|
||||
document.removeEventListener("visibilitychange", tick);
|
||||
costGen.current++;
|
||||
};
|
||||
}, [lane, sessionId]);
|
||||
}, [loadCosts]);
|
||||
useLiveRefresh(loadCosts, {
|
||||
intervalMs: COST_FALLBACK_MS,
|
||||
throttleMs: COST_POLL_MS,
|
||||
match: (msg) =>
|
||||
msg.type === "new_event" || msg.type === "session_updated" || msg.type === "session_created",
|
||||
});
|
||||
|
||||
return (
|
||||
<footer
|
||||
|
||||
@@ -33,13 +33,16 @@ export function Switch({
|
||||
// On: the solid accent (white knob clears 3:1 in every theme). Off: a
|
||||
// border-light track with an inset fg-muted/80 ring (≥3:1 in every theme), so the control's edge
|
||||
// is visible on any surface (surface-4 alone was ~1:1 on a light card).
|
||||
className={`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-1 focus-visible:ring-offset-surface-0 disabled:cursor-not-allowed disabled:opacity-50 ${
|
||||
checked ? "bg-accent-solid" : "bg-border-light ring-1 ring-inset ring-fg-muted/80"
|
||||
// Hover darkens the track (enabled only), so it reads as clickable.
|
||||
className={`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-1 focus-visible:ring-offset-surface-0 disabled:cursor-not-allowed disabled:opacity-40 ${
|
||||
checked
|
||||
? "bg-accent-solid enabled:hover:bg-accent-solid-hover"
|
||||
: "bg-border-light ring-1 ring-inset ring-fg-muted/80 enabled:hover:ring-fg-secondary"
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className={`inline-block h-4 w-4 rounded-full bg-white shadow transition-transform ${
|
||||
className={`inline-block h-4 w-4 rounded-full bg-white shadow-sm ring-1 ring-black/10 transition-transform duration-200 ease-out ${
|
||||
checked ? "translate-x-[18px]" : "translate-x-0.5"
|
||||
}`}
|
||||
/>
|
||||
|
||||
@@ -14,6 +14,10 @@
|
||||
* `onOpenTerminal`) and hears how full the context is (`onContext`) and
|
||||
* whether its session has started (`onNotStarted`: no row yet — the CLI may
|
||||
* be asking in the terminal, e.g. to trust the folder, which this then says).
|
||||
* A caller that knows the session has ended passes `ended`: nothing more is
|
||||
* being written, so the catch-up poll drops from 3 s to 60 s and the
|
||||
* sub-agent list stops being rescanned — a `new_event` frame, a reconnect or
|
||||
* the view being shown again still fetch the tail at once.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
/* =============================================================================
|
||||
@@ -79,6 +83,9 @@ import type { TranscriptMessage, TranscriptInfo, WSMessage } from "../../lib/typ
|
||||
// hook event. A short visibility-gated poll closes that gap and also rescues
|
||||
// the conversation from missed/late WebSocket frames.
|
||||
const POLL_INTERVAL_MS = 3000;
|
||||
// An ended session writes nothing more: a slow safety poll only, in case it was
|
||||
// resumed somewhere whose frames this view missed.
|
||||
const ENDED_POLL_INTERVAL_MS = 60000;
|
||||
// Rescan the transcripts list periodically so new subagents that spawn
|
||||
// mid-session appear in the dropdown without a page reload.
|
||||
const TRANSCRIPTS_REFRESH_MS = 15000;
|
||||
@@ -110,6 +117,8 @@ interface ConversationViewProps {
|
||||
onContext?: (tokens: number, model: string | null) => void;
|
||||
/** A live pane's session has no row yet: the CLI has not started it. */
|
||||
onNotStarted?: (notStarted: boolean) => void;
|
||||
/** The session has ended (and no pane holds it): poll slowly, if at all. */
|
||||
ended?: boolean;
|
||||
}
|
||||
|
||||
function ConversationViewPane({
|
||||
@@ -124,6 +133,7 @@ function ConversationViewPane({
|
||||
stopped = 0,
|
||||
onContext,
|
||||
onNotStarted,
|
||||
ended = false,
|
||||
}: ConversationViewProps) {
|
||||
const { t } = useTranslation("sessions");
|
||||
const [messages, setMessages] = useState<TranscriptMessage[]>([]);
|
||||
@@ -188,14 +198,18 @@ function ConversationViewPane({
|
||||
}
|
||||
}
|
||||
loadTranscripts();
|
||||
const interval = window.setInterval(() => {
|
||||
if (isShown(onScreen)) loadTranscripts();
|
||||
}, TRANSCRIPTS_REFRESH_MS);
|
||||
// An ended session spawns no new sub-agents: the load above (re-run when
|
||||
// it ends, for the last ones) is enough.
|
||||
const interval = ended
|
||||
? undefined
|
||||
: window.setInterval(() => {
|
||||
if (isShown(onScreen)) loadTranscripts();
|
||||
}, TRANSCRIPTS_REFRESH_MS);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.clearInterval(interval);
|
||||
};
|
||||
}, [sessionId]);
|
||||
}, [sessionId, ended]);
|
||||
|
||||
// Sync external initialTranscriptId to internal state
|
||||
useEffect(() => {
|
||||
@@ -355,9 +369,12 @@ function ConversationViewPane({
|
||||
let interval: number | null = null;
|
||||
function start() {
|
||||
if (interval !== null) return;
|
||||
interval = window.setInterval(() => {
|
||||
if (isShown(onScreen)) fetchNewMessages();
|
||||
}, POLL_INTERVAL_MS);
|
||||
interval = window.setInterval(
|
||||
() => {
|
||||
if (isShown(onScreen)) fetchNewMessages();
|
||||
},
|
||||
ended ? ENDED_POLL_INTERVAL_MS : POLL_INTERVAL_MS
|
||||
);
|
||||
}
|
||||
function stop() {
|
||||
if (interval !== null) {
|
||||
@@ -382,7 +399,7 @@ function ConversationViewPane({
|
||||
stop();
|
||||
document.removeEventListener("visibilitychange", onVisibility);
|
||||
};
|
||||
}, [fetchNewMessages, onScreen]);
|
||||
}, [fetchNewMessages, onScreen, ended]);
|
||||
|
||||
// Manual refresh - surfaces a control in the toolbar so users can force
|
||||
// a sync without reloading the page.
|
||||
|
||||
@@ -132,7 +132,11 @@ export function SessionReplay({
|
||||
</div>
|
||||
)}
|
||||
<div className="min-h-0 flex-1 overflow-hidden">
|
||||
<ConversationView sessionId={sessionId} fill />
|
||||
<ConversationView
|
||||
sessionId={sessionId}
|
||||
fill
|
||||
ended={!livePane && !!session && session.status !== "active"}
|
||||
/>
|
||||
</div>
|
||||
{livePane ? (
|
||||
<div
|
||||
|
||||
@@ -59,7 +59,13 @@ import { useTranslation } from "react-i18next";
|
||||
import { ArrowUp, FileText, Square, SquareCheck } from "lucide-react";
|
||||
import { isSubmitEnter } from "../../lib/keys";
|
||||
import { ConversationView } from "../conversation/ConversationView";
|
||||
import { ModelMenu, PromptEditor, promptWithImages, type PromptImage } from "./RunSetup";
|
||||
import {
|
||||
ModelMenu,
|
||||
PromptEditor,
|
||||
promptForPane,
|
||||
promptWithImages,
|
||||
type PromptImage,
|
||||
} from "./RunSetup";
|
||||
import { ChatAddMenu } from "./ChatAddMenu";
|
||||
import { addAttachments, dragAttachments } from "../../lib/promptAttach";
|
||||
import { readChatDraft, writeChatDraft } from "../../lib/chatDraft";
|
||||
@@ -491,7 +497,7 @@ export const PaneChat = memo(function PaneChat({
|
||||
const [notStarted, setNotStarted] = useState(false);
|
||||
|
||||
// A control is a command typed into the pane, like the user would.
|
||||
const command = async (line: string) => {
|
||||
const command = async (line: string, files: string[] = []) => {
|
||||
if (
|
||||
notStarted &&
|
||||
!(await confirmDialog({
|
||||
@@ -501,14 +507,15 @@ export const PaneChat = memo(function PaneChat({
|
||||
}))
|
||||
)
|
||||
return false;
|
||||
const ok = submitToRun(runId, line);
|
||||
const ok = submitToRun(runId, line, files);
|
||||
if (!ok) toast.error(t("chat.notSent"));
|
||||
return ok;
|
||||
};
|
||||
|
||||
const send = async () => {
|
||||
if (!text || uploading) return;
|
||||
if (!(await command(text))) return;
|
||||
const out = promptForPane(prompt, images);
|
||||
if (!(await command(out.text, out.files))) return;
|
||||
setFollow((n) => n + 1);
|
||||
setPrompt("");
|
||||
images.forEach((i) => i.url && URL.revokeObjectURL(i.url));
|
||||
|
||||
@@ -73,7 +73,7 @@ import { RunDot, type RunState } from "./ConsoleTabs";
|
||||
import { setSessionChat, useSessionChat } from "../../lib/chatUi";
|
||||
import { readChatDraft, writeChatDraft } from "../../lib/chatDraft";
|
||||
import { pasteToRun, takeRunInput } from "../../lib/panePaste";
|
||||
import { promptWithImages } from "./RunSetup";
|
||||
import { promptForPane } from "./RunSetup";
|
||||
|
||||
export const PANE_DRAG_TYPE = "application/x-agenthub-pane";
|
||||
/** The slot being dragged: `dataTransfer` data cannot be read during dragover. */
|
||||
@@ -246,8 +246,8 @@ const ITEM =
|
||||
* the CLI's input box, without Enter. */
|
||||
export function showTerminal(runId: string, sessionId: string) {
|
||||
const draft = readChatDraft(sessionId);
|
||||
const text = promptWithImages(draft.prompt, draft.images);
|
||||
if (text && pasteToRun(runId, text)) writeChatDraft(sessionId, "", []);
|
||||
const { text, files } = promptForPane(draft.prompt, draft.images);
|
||||
if ((text || files.length) && pasteToRun(runId, text, files)) writeChatDraft(sessionId, "", []);
|
||||
setSessionChat(sessionId, false);
|
||||
}
|
||||
|
||||
|
||||
@@ -208,6 +208,23 @@ export function promptWithImages(text: string, images: PromptImage[]): string {
|
||||
return [text.trim(), ...images.map((i) => i.path)].filter(Boolean).join(" ");
|
||||
}
|
||||
|
||||
const IMAGE_PATH = /^[^@].*\.(png|jpe?g|gif|webp)$/i;
|
||||
|
||||
/** The prompt as pasted into a live pane: the text with every non-image file
|
||||
* in it (as `promptWithImages`), and the images' paths apart — each goes in
|
||||
* a paste of its own, the one shape `claude` turns into `[Image #n]` on every
|
||||
* platform (a Windows path inside a paste of text stayed a plain path). */
|
||||
export function promptForPane(
|
||||
text: string,
|
||||
images: PromptImage[]
|
||||
): { text: string; files: string[] } {
|
||||
const isImage = (i: PromptImage) => IMAGE_PATH.test(i.path);
|
||||
return {
|
||||
text: promptWithImages(text, images.filter((i) => !isImage(i))),
|
||||
files: images.filter(isImage).map((i) => i.path),
|
||||
};
|
||||
}
|
||||
|
||||
/** A plain-text paste longer than this is attached as `pasted-text.txt`. */
|
||||
export const PASTE_AS_FILE_CHARS = 5000;
|
||||
|
||||
|
||||
@@ -666,8 +666,12 @@ export const TerminalView = memo(function TerminalView({
|
||||
() =>
|
||||
registerPane(
|
||||
runId,
|
||||
(text, submit) => {
|
||||
termRef.current?.paste(text);
|
||||
(text, submit, files = []) => {
|
||||
const term = termRef.current;
|
||||
// The text, then each image's path in a paste of its own — the one
|
||||
// shape `claude` turns into `[Image #n]` on every platform.
|
||||
if (text) term?.paste(files.length ? `${text} ` : text);
|
||||
files.forEach((f, i) => term?.paste(i < files.length - 1 ? `${f} ` : f));
|
||||
// Enter a beat after the paste, so a TUI that times its paste
|
||||
// detection never reads it as a newline inside the paste. A submit
|
||||
// comes from the pane's Chat view, which keeps the keyboard.
|
||||
|
||||
@@ -267,7 +267,7 @@ describe("PaneChat — model, effort and permission mode", () => {
|
||||
renderChat();
|
||||
fireEvent.click(screen.getByRole("button", { name: /Opus/ }));
|
||||
fireEvent.click(await screen.findByRole("menuitemradio", { name: /Sonnet/ }));
|
||||
expect(submitToRun).toHaveBeenCalledWith("agenthub-lane-1", "/model sonnet");
|
||||
expect(submitToRun).toHaveBeenCalledWith("agenthub-lane-1", "/model sonnet", []);
|
||||
});
|
||||
|
||||
it("shows the mode the pane shows, and asks the server to step it", async () => {
|
||||
@@ -430,7 +430,7 @@ describe("PaneChat — the unsent prompt", () => {
|
||||
expect(screen.getByPlaceholderText("Write a message…")).toHaveValue("half typed");
|
||||
expect(screen.getByText("a.ts")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByTestId("pane-chat-send"));
|
||||
expect(submitToRun).toHaveBeenCalledWith("agenthub-lane-1", "half typed @src/a.ts");
|
||||
expect(submitToRun).toHaveBeenCalledWith("agenthub-lane-1", "half typed @src/a.ts", []);
|
||||
await waitFor(() => expect(localStorage.getItem("agenthub.chat.draft.s1")).toBeNull());
|
||||
});
|
||||
|
||||
@@ -462,7 +462,8 @@ describe("PaneChat — the unsent prompt", () => {
|
||||
fireEvent.click(screen.getByTestId("pane-chat-send"));
|
||||
expect(submitToRun).toHaveBeenCalledWith(
|
||||
"agenthub-lane-1",
|
||||
'read @"/home/u/My Docs/spec.md" @/home/u/b.ts'
|
||||
'read @"/home/u/My Docs/spec.md" @/home/u/b.ts',
|
||||
[]
|
||||
);
|
||||
});
|
||||
|
||||
@@ -490,7 +491,7 @@ describe("PaneChat — the unsent prompt", () => {
|
||||
expect(box).toHaveValue("hello");
|
||||
confirmDialog.mockResolvedValueOnce(true);
|
||||
fireEvent.click(screen.getByTestId("pane-chat-send"));
|
||||
await waitFor(() => expect(submitToRun).toHaveBeenCalledWith("agenthub-lane-1", "hello"));
|
||||
await waitFor(() => expect(submitToRun).toHaveBeenCalledWith("agenthub-lane-1", "hello", []));
|
||||
});
|
||||
|
||||
it("sends without asking once the session has started", async () => {
|
||||
@@ -499,7 +500,7 @@ describe("PaneChat — the unsent prompt", () => {
|
||||
renderChat();
|
||||
fireEvent.change(screen.getByPlaceholderText("Write a message…"), { target: { value: "hi" } });
|
||||
fireEvent.click(screen.getByTestId("pane-chat-send"));
|
||||
await waitFor(() => expect(submitToRun).toHaveBeenCalledWith("agenthub-lane-1", "hi"));
|
||||
await waitFor(() => expect(submitToRun).toHaveBeenCalledWith("agenthub-lane-1", "hi", []));
|
||||
expect(confirmDialog).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
ModelPicker,
|
||||
PASTE_AS_FILE_CHARS,
|
||||
PromptEditor,
|
||||
promptForPane,
|
||||
promptWithImages,
|
||||
type PromptImage,
|
||||
} from "../RunSetup";
|
||||
@@ -586,3 +587,23 @@ describe("ModelMenu", () => {
|
||||
expect(onChange).toHaveBeenCalledWith("claude-sonnet-5-5");
|
||||
});
|
||||
});
|
||||
|
||||
describe("promptForPane — images apart, every other file in the text", () => {
|
||||
it("keeps @-mentions and other files in the text, and takes images out", () => {
|
||||
// A Windows path inside a paste of text stayed a plain path in claude; a
|
||||
// paste that is only the path becomes [Image #n].
|
||||
const images: PromptImage[] = [
|
||||
{ path: "C:\\Users\\u\\.claude\\agenthub\\drops\\f326fc666d3bdd92-image.png", name: "image.png" },
|
||||
{ path: "/data/drops/0123456789abcdef-log.txt", name: "log.txt" },
|
||||
{ path: '@"/home/u/My Docs/a.PNG"', name: "a.PNG" },
|
||||
{ path: "/data/drops/0123456789abcdef.JPG", name: "b.jpg" },
|
||||
];
|
||||
expect(promptForPane(" look ", images)).toEqual({
|
||||
text: 'look /data/drops/0123456789abcdef-log.txt @"/home/u/My Docs/a.PNG"',
|
||||
files: [
|
||||
"C:\\Users\\u\\.claude\\agenthub\\drops\\f326fc666d3bdd92-image.png",
|
||||
"/data/drops/0123456789abcdef.JPG",
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,17 +9,24 @@
|
||||
* boot/login while the switch is on. Between them, the status-area icon switch
|
||||
* (`GET/PUT /api/settings/tray`, on by default — server/lib/tray.js). Last,
|
||||
* **Uninstall AgentHub**: `POST /api/settings/uninstall` removes AgentHub from
|
||||
* the machine, database included (scripts/uninstall.js).
|
||||
* the machine, database included (scripts/uninstall.js). Quit is a plain
|
||||
* button and Uninstall a danger one, both the same width with an icon, and
|
||||
* each spins while its request runs.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Loader2, Power, Trash2 } from "lucide-react";
|
||||
import { api, type AutostartStatus, type TrayStatus } from "../../lib/api";
|
||||
import { toast } from "../../lib/toast";
|
||||
import { confirmDialog } from "../../lib/confirm";
|
||||
import { SettingsRow, SettingsSection, SettingsSwitchRow } from "./SettingsRow";
|
||||
|
||||
// The two action buttons share one width, so they line up under the switches.
|
||||
const ACTION = "min-w-[6.5rem] justify-center text-xs";
|
||||
const ICON = "h-3.5 w-3.5 shrink-0";
|
||||
|
||||
export function AutostartSettings() {
|
||||
const { t } = useTranslation("settings");
|
||||
const [status, setStatus] = useState<AutostartStatus | null>(null);
|
||||
@@ -126,9 +133,11 @@ export function AutostartSettings() {
|
||||
type="button"
|
||||
data-testid="quit-agenthub"
|
||||
disabled={quitting}
|
||||
aria-busy={quitting}
|
||||
onClick={() => void quit()}
|
||||
className="btn-ghost text-xs text-status-danger disabled:opacity-40"
|
||||
className={`btn-secondary ${ACTION}`}
|
||||
>
|
||||
{quitting ? <Loader2 className={ICON + " animate-spin"} /> : <Power className={ICON} />}
|
||||
{t("quit.button")}
|
||||
</button>
|
||||
}
|
||||
@@ -141,9 +150,15 @@ export function AutostartSettings() {
|
||||
type="button"
|
||||
data-testid="uninstall-agenthub"
|
||||
disabled={uninstalling}
|
||||
aria-busy={uninstalling}
|
||||
onClick={() => void uninstall()}
|
||||
className="btn-ghost text-xs text-status-danger disabled:opacity-40"
|
||||
className={`btn-danger ${ACTION}`}
|
||||
>
|
||||
{uninstalling ? (
|
||||
<Loader2 className={ICON + " animate-spin"} />
|
||||
) : (
|
||||
<Trash2 className={ICON} />
|
||||
)}
|
||||
{t("uninstall.button")}
|
||||
</button>
|
||||
}
|
||||
|
||||
@@ -13,7 +13,8 @@
|
||||
* that same file, so a plain `ssh://git-codecommit…` URL works), and for
|
||||
* SEVERAL accounts (two AWS accounts, a second GitHub user) named keys made
|
||||
* beside the default ones plus a login per account NAME (`ssh://<name>/…`),
|
||||
* each tied to the one key it uses — and, for
|
||||
* each tied to the one key it uses (the SSH part is split into tabs: one per
|
||||
* kind of host, the extra keys, the other hosts) — and, for
|
||||
* a user with their own Linux account (S3), their own HTTPS
|
||||
* logins. The host account's HTTPS logins are the shared Git credentials
|
||||
* table above it, so this lists them only for a member. The private key and
|
||||
@@ -23,12 +24,23 @@
|
||||
*/
|
||||
import { useCallback, useEffect, useState, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Copy, KeyRound, Plus, RefreshCw, Trash2 } from "lucide-react";
|
||||
import {
|
||||
Cloud,
|
||||
Copy,
|
||||
GitBranch,
|
||||
KeyRound,
|
||||
KeySquare,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Server,
|
||||
Trash2,
|
||||
} from "lucide-react";
|
||||
import { api, type GitIdentity } from "../../lib/api";
|
||||
import { confirmDialog } from "../../lib/confirm";
|
||||
import { copyText } from "../../lib/clipboard";
|
||||
import { toast } from "../../lib/toast";
|
||||
import { useAuth } from "../AuthGate";
|
||||
import { PageTabs } from "../PageTabs";
|
||||
import { Switch } from "../Switch";
|
||||
|
||||
const INPUT =
|
||||
@@ -180,6 +192,8 @@ export function GitIdentitySettings() {
|
||||
const me = auth.mode === "server" ? auth.user : null;
|
||||
// null = not edited: the field shows the saved value, else the account's.
|
||||
const [author, setAuthor] = useState<{ name: string; email: string } | null>(null);
|
||||
// null = not picked: opens on the first kind of host that has a key.
|
||||
const [sshTab, setSshTab] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
@@ -378,6 +392,31 @@ export function GitIdentitySettings() {
|
||||
authorUnset ||
|
||||
authorShown.name.trim() !== (id.author.name ?? "") ||
|
||||
authorShown.email.trim() !== (id.author.email ?? "");
|
||||
// The SSH keys, one tab per kind of host — every section at once was a wall.
|
||||
const sshTabs = [
|
||||
{ id: "git", label: t("gitIdentity.tabGit"), Icon: GitBranch },
|
||||
{ id: "aws", label: t("gitIdentity.awsTitle"), Icon: Cloud },
|
||||
...(named.length > 0 || id.writable
|
||||
? [
|
||||
{
|
||||
id: "more",
|
||||
label: named.length
|
||||
? `${t("gitIdentity.tabMore")} (${named.length})`
|
||||
: t("gitIdentity.tabMore"),
|
||||
Icon: KeySquare,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(id.sshUsers !== undefined && (otherRows.length > 0 || id.writable)
|
||||
? [{ id: "other", label: t("gitIdentity.tabOther"), Icon: Server }]
|
||||
: []),
|
||||
];
|
||||
const activeSshTab =
|
||||
sshTab && sshTabs.some((x) => x.id === sshTab)
|
||||
? sshTab
|
||||
: !keyOf("ed25519") && keyOf("rsa")
|
||||
? "aws"
|
||||
: "git";
|
||||
const saveAuthor = async () => {
|
||||
const ok = await run(
|
||||
() =>
|
||||
@@ -452,43 +491,252 @@ export function GitIdentitySettings() {
|
||||
</div>
|
||||
<p className="text-[11px] text-fg-muted">{t("gitIdentity.sshIntro")}</p>
|
||||
|
||||
<KeyCard
|
||||
title={t("gitIdentity.gitHubTitle")}
|
||||
sub={t("gitIdentity.gitHubSub")}
|
||||
type="ed25519"
|
||||
k={keyOf("ed25519")}
|
||||
id={id}
|
||||
busy={busy}
|
||||
onGenerate={generate}
|
||||
onRemove={removeKey}
|
||||
<PageTabs
|
||||
ariaLabel={t("gitIdentity.sshTitle")}
|
||||
tabs={sshTabs}
|
||||
activeId={activeSshTab}
|
||||
onSelect={setSshTab}
|
||||
>
|
||||
<Step n={2}>{t("gitIdentity.gitHubStepAdd")}</Step>
|
||||
<Step n={3}>
|
||||
{t("gitIdentity.gitHubStepClone")}
|
||||
<Code>git clone git@github.com:<org>/<repo>.git</Code>
|
||||
</Step>
|
||||
</KeyCard>
|
||||
{activeSshTab === "git" && (
|
||||
<KeyCard
|
||||
title={t("gitIdentity.gitHubTitle")}
|
||||
sub={t("gitIdentity.gitHubSub")}
|
||||
type="ed25519"
|
||||
k={keyOf("ed25519")}
|
||||
id={id}
|
||||
busy={busy}
|
||||
onGenerate={generate}
|
||||
onRemove={removeKey}
|
||||
>
|
||||
<Step n={2}>{t("gitIdentity.gitHubStepAdd")}</Step>
|
||||
<Step n={3}>
|
||||
{t("gitIdentity.gitHubStepClone")}
|
||||
<Code>git clone git@github.com:<org>/<repo>.git</Code>
|
||||
</Step>
|
||||
</KeyCard>
|
||||
)}
|
||||
|
||||
<KeyCard
|
||||
title={t("gitIdentity.awsTitle")}
|
||||
sub={t("gitIdentity.awsSub")}
|
||||
type="rsa"
|
||||
k={keyOf("rsa")}
|
||||
id={id}
|
||||
busy={busy}
|
||||
onGenerate={generate}
|
||||
onRemove={removeKey}
|
||||
>
|
||||
<Step n={2}>{t("gitIdentity.awsStepUpload")}</Step>
|
||||
<Step n={3}>
|
||||
{t("gitIdentity.awsStepKeyId")}
|
||||
{id.sshUsers === undefined ? null : (
|
||||
<>
|
||||
{awsRows.map((r) => (
|
||||
<div key={r.alias ?? r.host} className="mt-1 flex items-center gap-2">
|
||||
{activeSshTab === "aws" && (
|
||||
<KeyCard
|
||||
title={t("gitIdentity.awsTitle")}
|
||||
sub={t("gitIdentity.awsSub")}
|
||||
type="rsa"
|
||||
k={keyOf("rsa")}
|
||||
id={id}
|
||||
busy={busy}
|
||||
onGenerate={generate}
|
||||
onRemove={removeKey}
|
||||
>
|
||||
<Step n={2}>{t("gitIdentity.awsStepUpload")}</Step>
|
||||
<Step n={3}>
|
||||
{t("gitIdentity.awsStepKeyId")}
|
||||
{id.sshUsers === undefined ? null : (
|
||||
<>
|
||||
{awsRows.map((r) => (
|
||||
<div key={r.alias ?? r.host} className="mt-1 flex items-center gap-2">
|
||||
<span className="min-w-0 flex-1 truncate font-mono text-[11px] text-fg-secondary">
|
||||
{r.alias ? `${r.alias} · ` : ""}
|
||||
{r.region} · {r.user} · {keyLabel(r.key)}
|
||||
</span>
|
||||
{id.writable && (
|
||||
<button
|
||||
type="button"
|
||||
className={`${BTN} hover:text-status-danger`}
|
||||
disabled={busy}
|
||||
aria-label={`${t("gitIdentity.remove")} ${r.alias ?? r.host}`}
|
||||
onClick={() =>
|
||||
void run(() => api.gitIdentity.removeSshUser(r.alias ?? r.host))
|
||||
}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{id.writable && (
|
||||
<form
|
||||
className="mt-1 grid gap-2 sm:grid-cols-[2fr_1fr_1fr_1fr_auto]"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void saveAws();
|
||||
}}
|
||||
>
|
||||
<input
|
||||
aria-label={t("gitIdentity.awsKeyId")}
|
||||
placeholder="APKA…"
|
||||
autoComplete="off"
|
||||
value={aws.keyId}
|
||||
onChange={(e) => setAws({ ...aws, keyId: e.target.value })}
|
||||
className={`${INPUT} font-mono`}
|
||||
/>
|
||||
<select
|
||||
aria-label={t("gitIdentity.awsRegion")}
|
||||
value={aws.region}
|
||||
onChange={(e) => setAws({ ...aws, region: e.target.value })}
|
||||
className="select !py-1 !text-xs"
|
||||
>
|
||||
{AWS_REGIONS.map((r) => (
|
||||
<option key={r} value={r}>
|
||||
{r}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<input
|
||||
aria-label={t("gitIdentity.alias")}
|
||||
title={t("gitIdentity.aliasHint")}
|
||||
placeholder={t("gitIdentity.aliasPlaceholder")}
|
||||
autoComplete="off"
|
||||
value={aws.alias}
|
||||
onChange={(e) => setAws({ ...aws, alias: e.target.value })}
|
||||
className={`${INPUT} font-mono`}
|
||||
/>
|
||||
{keySelect(aws.key, (key) => setAws({ ...aws, key }), "rsa")}
|
||||
<button type="submit" className={BTN} disabled={busy || !aws.keyId.trim()}>
|
||||
{t("gitIdentity.awsSave")}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
<div className="mt-1 text-[10px] text-fg-muted">{t("gitIdentity.awsMany")}</div>
|
||||
</>
|
||||
)}
|
||||
</Step>
|
||||
{awsRows.length > 0 && (
|
||||
<div className="rounded border border-status-success/40 bg-status-success/10 p-2 text-[11px] text-fg-primary">
|
||||
{t("gitIdentity.awsReady")}
|
||||
{awsRows.map((r) => (
|
||||
<Code key={r.alias ?? r.host}>
|
||||
git clone ssh://{r.alias ?? r.host}/v1/repos/<repo>
|
||||
</Code>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</KeyCard>
|
||||
)}
|
||||
|
||||
{activeSshTab === "more" && (
|
||||
<section
|
||||
aria-label={t("gitIdentity.moreKeysTitle")}
|
||||
className="space-y-2 rounded border border-border p-2.5"
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-xs font-medium text-fg-primary">
|
||||
{t("gitIdentity.moreKeysTitle")}
|
||||
</div>
|
||||
<div className="text-[10px] text-fg-muted">{t("gitIdentity.moreKeysSub")}</div>
|
||||
</div>
|
||||
{id.writable && !newKey && (
|
||||
<button
|
||||
type="button"
|
||||
className={BTN}
|
||||
disabled={busy}
|
||||
onClick={() => setNewKey({ name: "", type: "rsa" })}
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
{t("gitIdentity.newKey")}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{newKey && (
|
||||
<form
|
||||
className="grid gap-2 sm:grid-cols-[2fr_1fr_auto_auto]"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void makeNamed();
|
||||
}}
|
||||
>
|
||||
<input
|
||||
aria-label={t("gitIdentity.keyName")}
|
||||
placeholder={t("gitIdentity.keyNamePlaceholder")}
|
||||
autoComplete="off"
|
||||
autoFocus
|
||||
value={newKey.name}
|
||||
onChange={(e) => setNewKey({ ...newKey, name: e.target.value })}
|
||||
className={`${INPUT} font-mono`}
|
||||
/>
|
||||
<select
|
||||
aria-label={t("gitIdentity.keyType")}
|
||||
value={newKey.type}
|
||||
onChange={(e) =>
|
||||
setNewKey({ ...newKey, type: e.target.value === "rsa" ? "rsa" : "ed25519" })
|
||||
}
|
||||
className="select !py-1 !text-xs"
|
||||
>
|
||||
<option value="rsa">RSA 4096 (AWS)</option>
|
||||
<option value="ed25519">ED25519</option>
|
||||
</select>
|
||||
<button type="submit" className={BTN} disabled={busy || !newKey.name.trim()}>
|
||||
{t("gitIdentity.generate")}
|
||||
</button>
|
||||
<button type="button" className={BTN} onClick={() => setNewKey(null)}>
|
||||
{t("gitCreds.cancel")}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
{named.map((k) => (
|
||||
<div
|
||||
key={k.id}
|
||||
className="space-y-1 rounded border border-border-light p-2"
|
||||
data-testid="git-named-key"
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-mono text-[11px] font-medium text-fg-primary">
|
||||
{k.name}
|
||||
</span>
|
||||
<span className="rounded bg-surface-3 px-1.5 py-0.5 text-[10px] text-fg-secondary">
|
||||
{k.type === "rsa" ? "RSA" : "ED25519"}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate font-mono text-[10px] text-fg-muted">
|
||||
{k.fingerprint}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className={BTN}
|
||||
onClick={() => void copyText(k.publicKey)}
|
||||
>
|
||||
<Copy className="h-3.5 w-3.5" />
|
||||
{t("gitIdentity.copy")}
|
||||
</button>
|
||||
{id.writable && (
|
||||
<button
|
||||
type="button"
|
||||
className={`${BTN} hover:text-status-danger`}
|
||||
disabled={busy}
|
||||
aria-label={`${t("gitIdentity.remove")} ${k.name}`}
|
||||
onClick={() => void removeNamed(k.id!)}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<textarea
|
||||
readOnly
|
||||
aria-label={`${t("gitIdentity.publicKey")} ${k.name}`}
|
||||
value={k.publicKey}
|
||||
rows={2}
|
||||
onFocus={(e) => e.currentTarget.select()}
|
||||
className={`${INPUT} resize-none break-all font-mono text-[10px]`}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{activeSshTab === "other" && (
|
||||
<section
|
||||
aria-label={t("gitIdentity.otherTitle")}
|
||||
className="space-y-1.5 rounded border border-border p-2.5"
|
||||
>
|
||||
<div className="text-xs font-medium text-fg-primary">
|
||||
{t("gitIdentity.otherTitle")}
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<div className="text-[10px] text-fg-muted">{t("gitIdentity.otherHint")}</div>
|
||||
{otherRows.map((r) => (
|
||||
<div key={r.alias ?? r.host} className="flex items-center gap-2">
|
||||
<span className="min-w-0 flex-1 truncate font-mono text-[11px] text-fg-secondary">
|
||||
{r.alias ? `${r.alias} · ` : ""}
|
||||
{r.region} · {r.user} · {keyLabel(r.key)}
|
||||
{r.alias ? `ssh://${r.alias}/ → ` : ""}
|
||||
{r.user}@{r.host} · {keyLabel(r.key)}
|
||||
</span>
|
||||
{id.writable && (
|
||||
<button
|
||||
@@ -507,167 +755,50 @@ export function GitIdentitySettings() {
|
||||
))}
|
||||
{id.writable && (
|
||||
<form
|
||||
className="mt-1 grid gap-2 sm:grid-cols-[2fr_1fr_1fr_1fr_auto]"
|
||||
className="grid gap-2 sm:grid-cols-[2fr_1fr_1fr_1fr_auto]"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void saveAws();
|
||||
void saveOther();
|
||||
}}
|
||||
>
|
||||
<input
|
||||
aria-label={t("gitIdentity.awsKeyId")}
|
||||
placeholder="APKA…"
|
||||
autoComplete="off"
|
||||
value={aws.keyId}
|
||||
onChange={(e) => setAws({ ...aws, keyId: e.target.value })}
|
||||
aria-label={t("gitIdentity.otherHost")}
|
||||
placeholder="git.example.com"
|
||||
value={other.host}
|
||||
onChange={(e) => setOther({ ...other, host: e.target.value })}
|
||||
className={`${INPUT} font-mono`}
|
||||
/>
|
||||
<input
|
||||
aria-label={t("gitIdentity.otherUser")}
|
||||
placeholder={t("gitIdentity.otherUser")}
|
||||
autoComplete="off"
|
||||
value={other.user}
|
||||
onChange={(e) => setOther({ ...other, user: e.target.value })}
|
||||
className={`${INPUT} font-mono`}
|
||||
/>
|
||||
<select
|
||||
aria-label={t("gitIdentity.awsRegion")}
|
||||
value={aws.region}
|
||||
onChange={(e) => setAws({ ...aws, region: e.target.value })}
|
||||
className="select !py-1 !text-xs"
|
||||
>
|
||||
{AWS_REGIONS.map((r) => (
|
||||
<option key={r} value={r}>
|
||||
{r}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<input
|
||||
aria-label={t("gitIdentity.alias")}
|
||||
title={t("gitIdentity.aliasHint")}
|
||||
placeholder={t("gitIdentity.aliasPlaceholder")}
|
||||
autoComplete="off"
|
||||
value={aws.alias}
|
||||
onChange={(e) => setAws({ ...aws, alias: e.target.value })}
|
||||
value={other.alias}
|
||||
onChange={(e) => setOther({ ...other, alias: e.target.value })}
|
||||
className={`${INPUT} font-mono`}
|
||||
/>
|
||||
{keySelect(aws.key, (key) => setAws({ ...aws, key }), "rsa")}
|
||||
<button type="submit" className={BTN} disabled={busy || !aws.keyId.trim()}>
|
||||
{keySelect(other.key, (key) => setOther({ ...other, key }))}
|
||||
<button
|
||||
type="submit"
|
||||
className={BTN}
|
||||
disabled={busy || !other.host.trim() || !other.user.trim()}
|
||||
>
|
||||
{t("gitIdentity.awsSave")}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
<div className="mt-1 text-[10px] text-fg-muted">{t("gitIdentity.awsMany")}</div>
|
||||
</>
|
||||
)}
|
||||
</Step>
|
||||
{awsRows.length > 0 && (
|
||||
<div className="rounded border border-status-success/40 bg-status-success/10 p-2 text-[11px] text-fg-primary">
|
||||
{t("gitIdentity.awsReady")}
|
||||
{awsRows.map((r) => (
|
||||
<Code key={r.alias ?? r.host}>
|
||||
git clone ssh://{r.alias ?? r.host}/v1/repos/<repo>
|
||||
</Code>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</KeyCard>
|
||||
|
||||
{(named.length > 0 || id.writable) && (
|
||||
<section
|
||||
aria-label={t("gitIdentity.moreKeysTitle")}
|
||||
className="space-y-2 rounded border border-border p-2.5"
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-xs font-medium text-fg-primary">
|
||||
{t("gitIdentity.moreKeysTitle")}
|
||||
</div>
|
||||
<div className="text-[10px] text-fg-muted">{t("gitIdentity.moreKeysSub")}</div>
|
||||
</div>
|
||||
{id.writable && !newKey && (
|
||||
<button
|
||||
type="button"
|
||||
className={BTN}
|
||||
disabled={busy}
|
||||
onClick={() => setNewKey({ name: "", type: "rsa" })}
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
{t("gitIdentity.newKey")}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{newKey && (
|
||||
<form
|
||||
className="grid gap-2 sm:grid-cols-[2fr_1fr_auto_auto]"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void makeNamed();
|
||||
}}
|
||||
>
|
||||
<input
|
||||
aria-label={t("gitIdentity.keyName")}
|
||||
placeholder={t("gitIdentity.keyNamePlaceholder")}
|
||||
autoComplete="off"
|
||||
autoFocus
|
||||
value={newKey.name}
|
||||
onChange={(e) => setNewKey({ ...newKey, name: e.target.value })}
|
||||
className={`${INPUT} font-mono`}
|
||||
/>
|
||||
<select
|
||||
aria-label={t("gitIdentity.keyType")}
|
||||
value={newKey.type}
|
||||
onChange={(e) =>
|
||||
setNewKey({ ...newKey, type: e.target.value === "rsa" ? "rsa" : "ed25519" })
|
||||
}
|
||||
className="select !py-1 !text-xs"
|
||||
>
|
||||
<option value="rsa">RSA 4096 (AWS)</option>
|
||||
<option value="ed25519">ED25519</option>
|
||||
</select>
|
||||
<button type="submit" className={BTN} disabled={busy || !newKey.name.trim()}>
|
||||
{t("gitIdentity.generate")}
|
||||
</button>
|
||||
<button type="button" className={BTN} onClick={() => setNewKey(null)}>
|
||||
{t("gitCreds.cancel")}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
{named.map((k) => (
|
||||
<div
|
||||
key={k.id}
|
||||
className="space-y-1 rounded border border-border-light p-2"
|
||||
data-testid="git-named-key"
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-mono text-[11px] font-medium text-fg-primary">
|
||||
{k.name}
|
||||
</span>
|
||||
<span className="rounded bg-surface-3 px-1.5 py-0.5 text-[10px] text-fg-secondary">
|
||||
{k.type === "rsa" ? "RSA" : "ED25519"}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate font-mono text-[10px] text-fg-muted">
|
||||
{k.fingerprint}
|
||||
</span>
|
||||
<button type="button" className={BTN} onClick={() => void copyText(k.publicKey)}>
|
||||
<Copy className="h-3.5 w-3.5" />
|
||||
{t("gitIdentity.copy")}
|
||||
</button>
|
||||
{id.writable && (
|
||||
<button
|
||||
type="button"
|
||||
className={`${BTN} hover:text-status-danger`}
|
||||
disabled={busy}
|
||||
aria-label={`${t("gitIdentity.remove")} ${k.name}`}
|
||||
onClick={() => void removeNamed(k.id!)}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<textarea
|
||||
readOnly
|
||||
aria-label={`${t("gitIdentity.publicKey")} ${k.name}`}
|
||||
value={k.publicKey}
|
||||
rows={2}
|
||||
onFocus={(e) => e.currentTarget.select()}
|
||||
className={`${INPUT} resize-none break-all font-mono text-[10px]`}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
</PageTabs>
|
||||
|
||||
{terminal && (
|
||||
<div className="flex items-start gap-2 rounded border border-border p-2">
|
||||
@@ -687,80 +818,6 @@ export function GitIdentitySettings() {
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{id.sshUsers !== undefined && (otherRows.length > 0 || id.writable) && (
|
||||
<details className="rounded border border-border p-2" open={otherRows.length > 0}>
|
||||
<summary className="cursor-pointer text-[11px] text-fg-primary">
|
||||
{t("gitIdentity.otherTitle")}
|
||||
</summary>
|
||||
<div className="mt-1.5 space-y-1.5">
|
||||
<div className="text-[10px] text-fg-muted">{t("gitIdentity.otherHint")}</div>
|
||||
{otherRows.map((r) => (
|
||||
<div key={r.alias ?? r.host} className="flex items-center gap-2">
|
||||
<span className="min-w-0 flex-1 truncate font-mono text-[11px] text-fg-secondary">
|
||||
{r.alias ? `ssh://${r.alias}/ → ` : ""}
|
||||
{r.user}@{r.host} · {keyLabel(r.key)}
|
||||
</span>
|
||||
{id.writable && (
|
||||
<button
|
||||
type="button"
|
||||
className={`${BTN} hover:text-status-danger`}
|
||||
disabled={busy}
|
||||
aria-label={`${t("gitIdentity.remove")} ${r.alias ?? r.host}`}
|
||||
onClick={() =>
|
||||
void run(() => api.gitIdentity.removeSshUser(r.alias ?? r.host))
|
||||
}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{id.writable && (
|
||||
<form
|
||||
className="grid gap-2 sm:grid-cols-[2fr_1fr_1fr_1fr_auto]"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void saveOther();
|
||||
}}
|
||||
>
|
||||
<input
|
||||
aria-label={t("gitIdentity.otherHost")}
|
||||
placeholder="git.example.com"
|
||||
value={other.host}
|
||||
onChange={(e) => setOther({ ...other, host: e.target.value })}
|
||||
className={`${INPUT} font-mono`}
|
||||
/>
|
||||
<input
|
||||
aria-label={t("gitIdentity.otherUser")}
|
||||
placeholder={t("gitIdentity.otherUser")}
|
||||
autoComplete="off"
|
||||
value={other.user}
|
||||
onChange={(e) => setOther({ ...other, user: e.target.value })}
|
||||
className={`${INPUT} font-mono`}
|
||||
/>
|
||||
<input
|
||||
aria-label={t("gitIdentity.alias")}
|
||||
title={t("gitIdentity.aliasHint")}
|
||||
placeholder={t("gitIdentity.aliasPlaceholder")}
|
||||
autoComplete="off"
|
||||
value={other.alias}
|
||||
onChange={(e) => setOther({ ...other, alias: e.target.value })}
|
||||
className={`${INPUT} font-mono`}
|
||||
/>
|
||||
{keySelect(other.key, (key) => setOther({ ...other, key }))}
|
||||
<button
|
||||
type="submit"
|
||||
className={BTN}
|
||||
disabled={busy || !other.host.trim() || !other.user.trim()}
|
||||
>
|
||||
{t("gitIdentity.awsSave")}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
<p className="text-[10px] text-fg-muted">{t("gitIdentity.privateNote")}</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ import { SettingsRow, SettingsSwitchRow } from "./SettingsRow";
|
||||
import { SagiAvatar } from "../Sagi/SagiAvatar";
|
||||
import { PetSprite } from "../Sagi/PetSprite";
|
||||
import { PET_SIZE, sagiPrefs } from "../Sagi/prefs";
|
||||
import { usePrefersReducedMotion } from "../Sagi/Sagi";
|
||||
import { usePrefersReducedMotion } from "../../hooks/usePrefersReducedMotion";
|
||||
import { confirmDialog } from "../../lib/confirm";
|
||||
import { toast } from "../../lib/toast";
|
||||
import { usePets, useWornPet } from "../Sagi/usePets";
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
/**
|
||||
* @file RetentionSettings.tsx
|
||||
* @description Settings → Data → Session cleanup, under the manual purge: the
|
||||
* OPT-IN automatic cleanup (`AGENTHUB_RETENTION_DAYS`, 0 = off, the default)
|
||||
* that the hourly maintenance applies, the database's size and free space, and
|
||||
* **Compact now** — a full VACUUM behind a confirm, polled through
|
||||
* `GET /api/settings/retention` while it runs, then toasted. Backed by
|
||||
* `server/lib/db-retention.js`; a value the environment set is read-only.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { AlertTriangle, Minimize2, RefreshCw } from "lucide-react";
|
||||
import { api } from "../../lib/api";
|
||||
import type { RetentionState } from "../../lib/api";
|
||||
import { confirmDialog } from "../../lib/confirm";
|
||||
import { formatBytes, formatDateTime } from "../../lib/format";
|
||||
import { toast } from "../../lib/toast";
|
||||
|
||||
export function RetentionSettings() {
|
||||
const { t } = useTranslation("settings");
|
||||
const [state, setState] = useState<RetentionState | null>(null);
|
||||
const [days, setDays] = useState("0");
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
api.settings.retention
|
||||
.get()
|
||||
.then((s) => {
|
||||
setState(s);
|
||||
setDays(String(s.days));
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
// A Compact takes a while on a large database: poll until it ends.
|
||||
const compacting = !!state?.compacting;
|
||||
useEffect(() => {
|
||||
if (!compacting) return;
|
||||
const id = window.setInterval(() => {
|
||||
api.settings.retention
|
||||
.get()
|
||||
.then((s) => {
|
||||
setState(s); // the draft keeps its value
|
||||
if (s.compacting || !s.last_compact) return;
|
||||
if (s.last_compact.ok) {
|
||||
toast.success(
|
||||
t("retention.compactDone", {
|
||||
before: formatBytes(s.last_compact.size_before ?? 0),
|
||||
after: formatBytes(s.last_compact.size_after ?? 0),
|
||||
})
|
||||
);
|
||||
} else {
|
||||
toast.error(t("retention.compactFailed", { error: s.last_compact.error }));
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, 2000);
|
||||
return () => window.clearInterval(id);
|
||||
}, [compacting, t]);
|
||||
|
||||
const max = state?.max_days ?? 3650;
|
||||
const n = Number(days);
|
||||
const valid = days.trim() !== "" && Number.isInteger(n) && n >= 0 && n <= max;
|
||||
const changed = state !== null && valid && n !== state.days;
|
||||
const owned = !!state?.env_owned.days;
|
||||
|
||||
async function save() {
|
||||
setSaving(true);
|
||||
try {
|
||||
const s = await api.settings.retention.save(n);
|
||||
setState(s);
|
||||
setDays(String(s.days));
|
||||
toast.success(t("retention.saved"));
|
||||
} catch (err) {
|
||||
toast.error(err);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function compact() {
|
||||
const ok = await confirmDialog({
|
||||
title: t("retention.compactConfirmTitle"),
|
||||
message: t("retention.compactConfirmBody"),
|
||||
confirmLabel: t("retention.compact"),
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
setState(await api.settings.retention.compact());
|
||||
} catch (err) {
|
||||
toast.error(err);
|
||||
}
|
||||
}
|
||||
|
||||
const purged = state?.last_run?.retention?.purged_sessions;
|
||||
|
||||
return (
|
||||
<div className="border-t border-border pt-4 space-y-3">
|
||||
<div>
|
||||
<h4 className="text-xs font-medium text-fg-secondary">{t("retention.title")}</h4>
|
||||
<p className="text-xs text-fg-muted">{t("retention.description")}</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<div className="bg-surface-2 rounded-lg px-4 py-3">
|
||||
<label htmlFor="retention-days" className="text-xs text-fg-secondary block mb-2">
|
||||
{t("retention.days")}
|
||||
</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
id="retention-days"
|
||||
type="number"
|
||||
min="0"
|
||||
max={max}
|
||||
step="1"
|
||||
inputMode="numeric"
|
||||
value={days}
|
||||
disabled={!state || owned}
|
||||
onChange={(e) => setDays(e.target.value)}
|
||||
aria-invalid={!valid || undefined}
|
||||
aria-describedby={!valid ? "retention-days-error" : undefined}
|
||||
className="input w-20 text-sm text-right font-mono"
|
||||
/>
|
||||
<span className="text-xs text-fg-muted">{t("common:days")}</span>
|
||||
</div>
|
||||
{!valid && (
|
||||
<p id="retention-days-error" className="mt-1 text-[11px] text-status-danger">
|
||||
{t("retention.invalid", { max })}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="btn-primary px-4 py-2 text-sm disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
disabled={saving || !changed || owned}
|
||||
onClick={() => void save()}
|
||||
>
|
||||
{saving ? t("homeDir.saving") : t("homeDir.save")}
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-xs text-fg-secondary">
|
||||
{state && state.days > 0 ? t("retention.on", { days: state.days }) : t("retention.off")}
|
||||
{state?.last_run && purged !== undefined && (
|
||||
<> {t("retention.lastRun", { time: formatDateTime(state.last_run.at), n: purged })}</>
|
||||
)}
|
||||
</p>
|
||||
{owned && (
|
||||
<p className="text-xs text-status-warning flex items-start gap-1.5">
|
||||
<AlertTriangle className="w-3.5 h-3.5 flex-shrink-0 mt-px" />
|
||||
{t("privacy.envOwned")}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void compact()}
|
||||
disabled={!state || compacting}
|
||||
className="text-xs px-3 py-1.5 rounded-md transition-colors disabled:opacity-50 text-fg-secondary hover:text-fg-primary hover:bg-surface-4 border border-border"
|
||||
>
|
||||
{compacting ? (
|
||||
<RefreshCw className="w-3 h-3 animate-spin inline mr-1" />
|
||||
) : (
|
||||
<Minimize2 className="w-3 h-3 inline mr-1" />
|
||||
)}
|
||||
{compacting ? t("retention.compacting") : t("retention.compact")}
|
||||
</button>
|
||||
{state?.space && (
|
||||
<span className="text-xs text-fg-muted">
|
||||
{t("retention.space", {
|
||||
size: formatBytes(state.db_size),
|
||||
free: formatBytes(state.space.free_bytes),
|
||||
mode: state.space.auto_vacuum,
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,7 +4,8 @@
|
||||
* switch row (`SettingsSwitchRow`) and a segmented radio group
|
||||
* (`SettingsSegmented`, arrow keys + one roving tab stop). Rows divide
|
||||
* themselves with a hairline, none after the last, so a section is just its
|
||||
* rows in order.
|
||||
* rows in order. A string description shows its `backticked` words as code,
|
||||
* and a `disabled` row dims its label, so an unavailable control reads as one.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
@@ -32,30 +33,55 @@ export function SettingsSection({
|
||||
);
|
||||
}
|
||||
|
||||
/** `text` with every `backticked` run drawn as inline code (a command to type). */
|
||||
export function withCode(text: string): ReactNode {
|
||||
const parts = text.split(/`([^`]+)`/);
|
||||
if (parts.length === 1) return text;
|
||||
return parts.map((p, i) =>
|
||||
i % 2 ? (
|
||||
<code
|
||||
key={i}
|
||||
className="whitespace-nowrap rounded border border-border bg-surface-2 px-1 py-px font-mono text-[11px] text-fg-secondary"
|
||||
>
|
||||
{p}
|
||||
</code>
|
||||
) : (
|
||||
p
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export function SettingsRow({
|
||||
label,
|
||||
description,
|
||||
control,
|
||||
alignTop = false,
|
||||
disabled = false,
|
||||
id,
|
||||
}: {
|
||||
label: ReactNode;
|
||||
description?: ReactNode;
|
||||
control: ReactNode;
|
||||
alignTop?: boolean;
|
||||
/** The control cannot be used here: the label is dimmed with it. */
|
||||
disabled?: boolean;
|
||||
/** A deep-link anchor (`#id`) for one row inside a grouped section. */
|
||||
id?: string;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
id={id}
|
||||
className={`${id ? "scroll-mt-24 " : ""}flex justify-between gap-4 border-b border-border/60 last:border-b-0 ${
|
||||
className={`${id ? "scroll-mt-24 " : ""}flex justify-between gap-6 border-b border-border/60 last:border-b-0 ${
|
||||
description ? "py-3" : "py-2"
|
||||
} ${alignTop ? "items-start" : "items-center"}`}
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm text-fg-secondary">{label}</p>
|
||||
{description && <p className="mt-0.5 text-xs text-fg-muted">{description}</p>}
|
||||
<p className={`text-sm ${disabled ? "text-fg-muted" : "text-fg-secondary"}`}>{label}</p>
|
||||
{description && (
|
||||
<p className="mt-0.5 text-xs leading-relaxed text-fg-muted">
|
||||
{typeof description === "string" ? withCode(description) : description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="shrink-0">{control}</div>
|
||||
</div>
|
||||
@@ -82,6 +108,7 @@ export function SettingsSwitchRow({
|
||||
id={id}
|
||||
label={label}
|
||||
description={description}
|
||||
disabled={disabled}
|
||||
control={<Switch checked={checked} onChange={onChange} label={label} disabled={disabled} />}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
* first, and a member (S3) adds an HTTPS login of their own while the host's
|
||||
* view leaves HTTPS to the shared Git credentials table, and an SSH user per
|
||||
* host is saved — AWS CodeCommit's key ID inside its own RSA section, any
|
||||
* other host under "Other SSH hosts" — so the sections never mix; a named key
|
||||
* other host under "Other SSH hosts" — each kind of host in its own tab, so
|
||||
* the sections never mix; a named key
|
||||
* is made beside the default ones, and a second AWS account is saved under
|
||||
* its own name with the one key it uses.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
@@ -47,6 +48,10 @@ const view = (over: Partial<GitIdentity> = {}): GitIdentity => ({
|
||||
...over,
|
||||
});
|
||||
|
||||
/** Opens one tab of the SSH keys. */
|
||||
const tab = async (name: string | RegExp) =>
|
||||
userEvent.click(await screen.findByRole("tab", { name }));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
@@ -100,6 +105,7 @@ describe("GitIdentitySettings", () => {
|
||||
view({ ssh: { ...KEY, type: "rsa", publicKey: "ssh-rsa AAAAB3 an@agenthub" } })
|
||||
);
|
||||
render(<GitIdentitySettings />);
|
||||
await tab("AWS CodeCommit");
|
||||
const aws = await screen.findByRole("region", { name: "AWS CodeCommit" });
|
||||
await userEvent.click(within(aws).getByRole("button", { name: "Generate key" }));
|
||||
expect(api.gitIdentity.generateKey).toHaveBeenCalledWith(false, "rsa");
|
||||
@@ -119,11 +125,14 @@ describe("GitIdentitySettings", () => {
|
||||
vi.mocked(api.gitIdentity.removeKey).mockResolvedValue(view({ ssh: ED, sshKeys: [ED] }));
|
||||
render(<GitIdentitySettings />);
|
||||
const gh = await screen.findByRole("region", { name: /GitHub/ });
|
||||
const aws = screen.getByRole("region", { name: "AWS CodeCommit" });
|
||||
expect(within(gh).getByLabelText("Public key ED25519")).toHaveValue(ED.publicKey);
|
||||
expect(within(aws).getByLabelText("Public key RSA")).toHaveValue(RSA.publicKey);
|
||||
// Each section explains only its own host.
|
||||
// One tab at a time: the other host's section is not on screen.
|
||||
expect(screen.queryByRole("region", { name: "AWS CodeCommit" })).toBeNull();
|
||||
expect(within(gh).queryByText(/IAM/)).toBeNull();
|
||||
await tab("AWS CodeCommit");
|
||||
const aws = screen.getByRole("region", { name: "AWS CodeCommit" });
|
||||
expect(screen.queryByRole("region", { name: /GitHub/ })).toBeNull();
|
||||
expect(within(aws).getByLabelText("Public key RSA")).toHaveValue(RSA.publicKey);
|
||||
expect(within(aws).queryByText(/GitHub/)).toBeNull();
|
||||
expect(screen.getByRole("switch", { name: /terminal/ })).toBeChecked();
|
||||
await userEvent.click(within(aws).getByRole("button", { name: "Delete" }));
|
||||
@@ -160,7 +169,7 @@ describe("GitIdentitySettings", () => {
|
||||
view({ ssh: KEY, sshUsers: [{ host: "git.example.com", user: "deploy" }] })
|
||||
);
|
||||
render(<GitIdentitySettings />);
|
||||
await userEvent.click(await screen.findByText("Other SSH hosts (advanced)"));
|
||||
await tab("Other hosts");
|
||||
await userEvent.type(screen.getByLabelText("Host"), "ssh://git.example.com/x");
|
||||
await userEvent.type(screen.getByLabelText("User name"), "deploy");
|
||||
const form = screen.getByLabelText("Host").closest("form")!;
|
||||
@@ -228,13 +237,17 @@ describe("GitIdentitySettings", () => {
|
||||
view({ sshKeys: [RSA], sshUsers: [] })
|
||||
);
|
||||
render(<GitIdentitySettings />);
|
||||
const more = await screen.findByRole("region", { name: "More SSH keys" });
|
||||
// Only an RSA key: the AWS tab opens first.
|
||||
expect(await screen.findByRole("region", { name: "AWS CodeCommit" })).toBeInTheDocument();
|
||||
await tab("More keys");
|
||||
let more = screen.getByRole("region", { name: "More SSH keys" });
|
||||
await userEvent.click(within(more).getByRole("button", { name: "New key" }));
|
||||
await userEvent.type(within(more).getByLabelText("Key name"), "AWS-Prod");
|
||||
await userEvent.click(within(more).getByRole("button", { name: "Generate key" }));
|
||||
expect(api.gitIdentity.generateKey).toHaveBeenCalledWith(false, "rsa", "aws-prod");
|
||||
expect(await within(more).findByLabelText("Public key aws-prod")).toHaveValue("ssh-rsa B prod");
|
||||
|
||||
await tab("AWS CodeCommit");
|
||||
const aws = screen.getByRole("region", { name: "AWS CodeCommit" });
|
||||
await userEvent.type(within(aws).getByLabelText("SSH key ID"), "APKA2");
|
||||
await userEvent.type(within(aws).getByLabelText("Account name"), "aws-prod");
|
||||
@@ -251,6 +264,8 @@ describe("GitIdentitySettings", () => {
|
||||
).toBeInTheDocument();
|
||||
expect(within(aws).getByText("git clone ssh://aws-prod/v1/repos/<repo>")).toBeInTheDocument();
|
||||
|
||||
await tab("More keys (1)");
|
||||
more = screen.getByRole("region", { name: "More SSH keys" });
|
||||
await userEvent.click(within(more).getByRole("button", { name: "Delete aws-prod" }));
|
||||
await waitFor(() =>
|
||||
expect(api.gitIdentity.removeKeyById).toHaveBeenCalledWith("id_rsa_aws-prod")
|
||||
|
||||
@@ -8,26 +8,31 @@
|
||||
* `.credentials.json`, or a `claude setup-token` token; for Codex an OpenAI
|
||||
* API key or a pasted `auth.json` — or removes one, each time with their own
|
||||
* password again; an analyst only reads. The secret only goes IN: the server
|
||||
* never sends it back.
|
||||
* never sends it back. An account's Edit (pencil) picks the users who run on
|
||||
* it (`PUT /api/accounts/:name/users`): their sessions skip the balancer, and
|
||||
* a Claude login goes into their home at once — no restart.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useState, type KeyboardEvent, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { TFunction } from "i18next";
|
||||
import { KeyRound, Plus, RefreshCw, Trash2 } from "lucide-react";
|
||||
import { KeyRound, Pencil, Plus, RefreshCw, Trash2 } from "lucide-react";
|
||||
import {
|
||||
api,
|
||||
type AccountPin,
|
||||
type AccountPool,
|
||||
type PoolAccountInput,
|
||||
type PoolProfile,
|
||||
type PoolTool,
|
||||
type ServerUserUsage,
|
||||
} from "../../lib/api";
|
||||
import { fmt, fmtCost, formatDateTime } from "../../lib/format";
|
||||
import { toast } from "../../lib/toast";
|
||||
import { isSubmitEnter } from "../../lib/keys";
|
||||
import { useSpin } from "../../hooks/useSpin";
|
||||
import { ConfirmModal } from "../ConfirmModal";
|
||||
import { Checkbox } from "../Checkbox";
|
||||
|
||||
type Row = {
|
||||
tool: PoolTool;
|
||||
@@ -59,6 +64,8 @@ function rowsOf(pool: AccountPool): Row[] {
|
||||
];
|
||||
}
|
||||
|
||||
const pinsOf = (pool: AccountPool, tool: PoolTool): AccountPin[] => pool.pins?.[tool] ?? [];
|
||||
|
||||
function errorText(t: TFunction<"users">, e: unknown): string {
|
||||
const err = e as Error & { code?: string };
|
||||
return err.code && t(`pool.errors.${err.code}`, { defaultValue: "" })
|
||||
@@ -72,6 +79,7 @@ export function AccountPoolCard({ isAdmin }: { isAdmin: boolean }) {
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [removing, setRemoving] = useState<Row | null>(null);
|
||||
const [editing, setEditing] = useState<Row | null>(null);
|
||||
|
||||
const load = useCallback(
|
||||
(force = false) =>
|
||||
@@ -148,6 +156,16 @@ export function AccountPoolCard({ isAdmin }: { isAdmin: boolean }) {
|
||||
<div className="text-[11px] text-fg-muted">
|
||||
{t("pool.added", { at: formatDateTime(r.addedAt) })}
|
||||
</div>
|
||||
{pool && pinsOf(pool, r.tool).some((p) => p.account === r.name) && (
|
||||
<div className="text-[11px] text-fg-secondary">
|
||||
{t("pool.pinned", {
|
||||
users: pinsOf(pool, r.tool)
|
||||
.filter((p) => p.account === r.name)
|
||||
.map((p) => p.username)
|
||||
.join(", "),
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-5 py-2.5 text-sm text-fg-secondary">
|
||||
{t(`pool.kind.${r.kind}`)}
|
||||
@@ -188,7 +206,16 @@ export function AccountPoolCard({ isAdmin }: { isAdmin: boolean }) {
|
||||
</div>
|
||||
</td>
|
||||
{isAdmin && (
|
||||
<td className="px-5 py-2 text-right">
|
||||
<td className="px-5 py-2 text-right whitespace-nowrap">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEditing(r)}
|
||||
title={t("pool.edit", { name: r.name })}
|
||||
aria-label={t("pool.edit", { name: r.name })}
|
||||
className="btn-icon"
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setRemoving(r)}
|
||||
@@ -206,7 +233,6 @@ export function AccountPoolCard({ isAdmin }: { isAdmin: boolean }) {
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{adding && (
|
||||
<AddAccountDialog
|
||||
onClose={() => setAdding(false)}
|
||||
@@ -228,10 +254,163 @@ export function AccountPoolCard({ isAdmin }: { isAdmin: boolean }) {
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{editing && pool && (
|
||||
<EditAccountDialog
|
||||
pool={pool}
|
||||
row={editing}
|
||||
onClose={() => setEditing(null)}
|
||||
onDone={(r) => {
|
||||
const left = r.added.filter(
|
||||
(u) => u.switched === "own-login" || u.switched === "expired"
|
||||
);
|
||||
toast.success(t("pool.editDone", { name: editing.name }));
|
||||
for (const u of left) {
|
||||
toast.info(
|
||||
t(`pool.pinDone.${u.switched}`, { user: u.username, account: editing.name })
|
||||
);
|
||||
}
|
||||
setEditing(null);
|
||||
void load();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One account's Edit: tick the users whose sessions run on it. A user already
|
||||
* on another account of the tool moves here when ticked; unticking one sends
|
||||
* them back to the least-used account. Saved in one request, password again.
|
||||
*/
|
||||
function EditAccountDialog({
|
||||
pool,
|
||||
row,
|
||||
onClose,
|
||||
onDone,
|
||||
}: {
|
||||
pool: AccountPool;
|
||||
row: Row;
|
||||
onClose: () => void;
|
||||
onDone: (r: Awaited<ReturnType<typeof api.accountPool.setUsers>>) => void;
|
||||
}) {
|
||||
const { t } = useTranslation("users");
|
||||
const pins = pinsOf(pool, row.tool);
|
||||
const initial = pins.filter((p) => p.account === row.name).map((p) => p.userId);
|
||||
const [users, setUsers] = useState<ServerUserUsage[] | null>(null);
|
||||
const [chosen, setChosen] = useState<Set<number>>(() => new Set(initial));
|
||||
const [current, setCurrent] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
api.users
|
||||
.list()
|
||||
.then((r) => setUsers(r.users))
|
||||
.catch(() => setUsers([]));
|
||||
}, []);
|
||||
|
||||
const changed = chosen.size !== initial.length || initial.some((id) => !chosen.has(id));
|
||||
const ready = changed && current.length > 0;
|
||||
const toggle = (id: number, on: boolean) =>
|
||||
setChosen((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (on) next.add(id);
|
||||
else next.delete(id);
|
||||
return next;
|
||||
});
|
||||
|
||||
const submit = async () => {
|
||||
if (!ready || busy) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
onDone(await api.accountPool.setUsers(row.tool, row.name, [...chosen], current));
|
||||
} catch (e) {
|
||||
setError(errorText(t, e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<ConfirmModal
|
||||
open
|
||||
title={t("pool.edit", { name: row.name })}
|
||||
message={t("pool.editHint")}
|
||||
confirmLabel={t("pool.save")}
|
||||
cancelLabel={t("common:cancel")}
|
||||
destructive={false}
|
||||
busy={busy}
|
||||
disabled={!ready}
|
||||
onConfirm={() => void submit()}
|
||||
onCancel={onClose}
|
||||
>
|
||||
<div
|
||||
className="mt-3 space-y-3"
|
||||
onKeyDown={(e) => {
|
||||
if ((e.target as HTMLElement).tagName === "INPUT" && isSubmitEnter(e)) {
|
||||
e.preventDefault();
|
||||
void submit();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<span className="text-xs font-medium text-fg-secondary">{t("pool.users")}</span>
|
||||
<div className="mt-1 max-h-56 overflow-y-auto rounded-md border border-border divide-y divide-border">
|
||||
{users === null && (
|
||||
<p className="px-3 py-2 text-xs text-fg-muted">{t("pool.loadingUsers")}</p>
|
||||
)}
|
||||
{users?.length === 0 && (
|
||||
<p className="px-3 py-2 text-xs text-fg-muted">{t("pool.noUsers")}</p>
|
||||
)}
|
||||
{users?.map((u) => {
|
||||
const elsewhere = pins.find((p) => p.userId === u.id && p.account !== row.name);
|
||||
return (
|
||||
<div key={u.id} className="px-3 py-2">
|
||||
<Checkbox
|
||||
checked={chosen.has(u.id)}
|
||||
onChange={(on) => toggle(u.id, on)}
|
||||
label={
|
||||
<span>
|
||||
{u.username}
|
||||
{u.disabled && (
|
||||
<span className="ml-1 text-fg-muted">({t("disabled")})</span>
|
||||
)}
|
||||
{elsewhere && (
|
||||
<span className="ml-1.5 text-[11px] text-fg-muted">
|
||||
{t("pool.onAccount", { account: elsewhere.account })}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
}
|
||||
labelClassName="text-sm text-fg-primary"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<Field label={t("yourPassword")} hint={t("yourPasswordHint")}>
|
||||
<input
|
||||
type="password"
|
||||
className="input w-full text-sm"
|
||||
value={current}
|
||||
onChange={(e) => setCurrent(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
aria-label={t("yourPassword")}
|
||||
/>
|
||||
</Field>
|
||||
{error && (
|
||||
<p role="alert" className="text-xs text-status-danger">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</ConfirmModal>
|
||||
);
|
||||
}
|
||||
|
||||
type ClaudeSource = "profile" | "credentials" | "token";
|
||||
|
||||
function AddAccountDialog({
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
* admin adds an account only with their own password typed (the token goes
|
||||
* in once and is not shown back) — a saved login moved in (the server's own
|
||||
* included), or a setup-token — and removes one the same way, and an analyst
|
||||
* sees no add or remove control.
|
||||
* sees no add or remove control. An account's Edit ticks the users who run on
|
||||
* it, saved with the admin's own password; the users show on the account.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
@@ -19,10 +20,12 @@ const accountPool = vi.hoisted(() => ({
|
||||
add: vi.fn(),
|
||||
remove: vi.fn(),
|
||||
profiles: vi.fn(),
|
||||
setUsers: vi.fn(),
|
||||
}));
|
||||
const users = vi.hoisted(() => ({ list: vi.fn() }));
|
||||
vi.mock("../../../lib/api", async (importOriginal) => {
|
||||
const actual = await importOriginal<Record<string, unknown>>();
|
||||
return { ...actual, api: { accountPool } };
|
||||
return { ...actual, api: { accountPool, users } };
|
||||
});
|
||||
|
||||
import { AccountPoolCard } from "../AccountPoolCard";
|
||||
@@ -66,6 +69,12 @@ const POOL: AccountPool = {
|
||||
beforeEach(() => {
|
||||
for (const fn of Object.values(accountPool)) fn.mockReset();
|
||||
accountPool.list.mockResolvedValue(POOL);
|
||||
users.list.mockResolvedValue({
|
||||
users: [
|
||||
{ id: 7, username: "mia", disabled: false },
|
||||
{ id: 8, username: "leo", disabled: false },
|
||||
],
|
||||
});
|
||||
accountPool.profiles.mockResolvedValue({
|
||||
profiles: [
|
||||
{
|
||||
@@ -158,4 +167,43 @@ describe("AccountPoolCard", () => {
|
||||
expect(accountPool.remove).toHaveBeenCalledWith("codex", "cx-1", "boss-pass")
|
||||
);
|
||||
});
|
||||
|
||||
it("sets who runs on an account from its Edit, with the admin's own password", async () => {
|
||||
accountPool.list.mockResolvedValue({
|
||||
...POOL,
|
||||
pins: {
|
||||
claude: [
|
||||
{ userId: 8, username: "leo", account: "team-1" },
|
||||
{ userId: 7, username: "mia", account: "team-0" },
|
||||
],
|
||||
codex: [],
|
||||
},
|
||||
});
|
||||
accountPool.setUsers.mockResolvedValue({
|
||||
added: [{ userId: 7, username: "mia", switched: "switched" }],
|
||||
removed: [{ userId: 8, username: "leo" }],
|
||||
});
|
||||
const user = userEvent.setup();
|
||||
render(<AccountPoolCard isAdmin />);
|
||||
expect(await screen.findByText("Used by: leo")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: /switch a user/i })).toBeNull();
|
||||
await user.click(screen.getByRole("button", { name: "Edit team-1" }));
|
||||
const dialog = await screen.findByRole("dialog");
|
||||
const leo = await screen.findByRole("checkbox", { name: /leo/ });
|
||||
const mia = screen.getByRole("checkbox", { name: /mia/ });
|
||||
expect(leo).toHaveAttribute("aria-checked", "true");
|
||||
expect(mia).toHaveAttribute("aria-checked", "false");
|
||||
expect(screen.getByText("now on team-0")).toBeInTheDocument();
|
||||
await user.click(mia);
|
||||
await user.click(leo);
|
||||
const save = Array.from(dialog.querySelectorAll("button")).find(
|
||||
(b) => b.textContent === "Save"
|
||||
)!;
|
||||
expect(save).toBeDisabled();
|
||||
await user.type(screen.getByLabelText("Your password"), "boss-pass");
|
||||
await user.click(save);
|
||||
await waitFor(() =>
|
||||
expect(accountPool.setUsers).toHaveBeenCalledWith("claude", "team-1", [7], "boss-pass")
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* @file usePrefersReducedMotion.ts
|
||||
* @description The OS "reduce motion" preference, followed live. Its own
|
||||
* module so a settings screen can read it without importing the pet overlay
|
||||
* (`components/Sagi/Sagi.tsx`), whose chat and pane UI would otherwise be
|
||||
* pulled into every page's first bundle.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
/** The OS "reduce motion" preference, followed live. */
|
||||
export function usePrefersReducedMotion(): boolean {
|
||||
const [reduced, setReduced] = useState(
|
||||
() =>
|
||||
typeof window !== "undefined" &&
|
||||
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches
|
||||
);
|
||||
useEffect(() => {
|
||||
const mq = window.matchMedia?.("(prefers-reduced-motion: reduce)");
|
||||
if (!mq) return;
|
||||
const onChange = () => setReduced(mq.matches);
|
||||
mq.addEventListener?.("change", onChange);
|
||||
return () => mq.removeEventListener?.("change", onChange);
|
||||
}, []);
|
||||
return reduced;
|
||||
}
|
||||
@@ -32,6 +32,7 @@
|
||||
"copyLink": "Copy link",
|
||||
"preview": "Preview",
|
||||
"download": "Download",
|
||||
"noPreview": "This file type cannot be shown here — download it to open it.",
|
||||
"install": "Install",
|
||||
"installs": "{{count}} installs",
|
||||
"installed": "Installed to {{path}}",
|
||||
|
||||
@@ -37,18 +37,14 @@
|
||||
"chooseDesc": "Featured pets come from codex-pets.net and are downloaded into this install the first time you pick one. Your choice and size are saved to your account.",
|
||||
"uploadHint": "An image (PNG, JPEG, GIF, WebP — no SVG) is shown still; a .codex-pet.zip (pet.json + a 1536×1872 spritesheet.webp) is animated by mood.",
|
||||
"panel": {
|
||||
"label": "{{name}} companion",
|
||||
"live": "Live",
|
||||
"offline": "Offline",
|
||||
"close": "Close {{name}}",
|
||||
"statLive": "live",
|
||||
"statWaiting": "waiting",
|
||||
"statErrored": "errored",
|
||||
"mute": "Mute",
|
||||
"unmute": "Unmute",
|
||||
"clearAlerts": "Clear alerts",
|
||||
"askPlaceholder": "Ask {{name}}… (e.g. any errors?)",
|
||||
"ask": "Ask {{name}}",
|
||||
"send": "Send",
|
||||
"rename": "Click to rename {{name}}",
|
||||
"renameLabel": "Pet name",
|
||||
@@ -217,9 +213,12 @@
|
||||
},
|
||||
"chat": {
|
||||
"label": "Chat with {{name}}",
|
||||
"back": "Back",
|
||||
"close": "Close {{name}}",
|
||||
"new": "New chat",
|
||||
"status": "Status — click to show the sessions that need you",
|
||||
"endTitle": "End this chat?",
|
||||
"endBody": "It is still writing a reply. A new chat stops this session.",
|
||||
"endConfirm": "Stop and start new",
|
||||
"openWorkspace": "Open in workspace",
|
||||
"typing": "typing…",
|
||||
"placeholder": "Ask {{name}} anything…",
|
||||
@@ -945,13 +944,16 @@
|
||||
"alias": "Account name",
|
||||
"aliasPlaceholder": "name (optional)",
|
||||
"aliasHint": "Leave empty for the default account of this host. Give a name (e.g. aws-prod, lowercase, no dot) for one more account: clone it as ssh://<name>/…",
|
||||
"awsMany": "Several AWS accounts? Make one more RSA key below for each, upload it to that account, then save its SSH key ID here with an account name and that key. Clone each with ssh://<account name>/v1/repos/<repo>.",
|
||||
"awsMany": "Several AWS accounts? Make one more RSA key in the More keys tab for each, upload it to that account, then save its SSH key ID here with an account name and that key. Clone each with ssh://<account name>/v1/repos/<repo>.",
|
||||
"moreKeysTitle": "More SSH keys",
|
||||
"moreKeysSub": "One per extra account — another AWS account, a second GitHub user. A login that names its key uses only that key.",
|
||||
"newKey": "New key",
|
||||
"keyName": "Key name",
|
||||
"keyNamePlaceholder": "e.g. aws-prod",
|
||||
"keyType": "Key type"
|
||||
"keyType": "Key type",
|
||||
"tabGit": "GitHub · GitLab",
|
||||
"tabMore": "More keys",
|
||||
"tabOther": "Other hosts"
|
||||
},
|
||||
"gitCreds": {
|
||||
"title": "Git credentials",
|
||||
@@ -1214,6 +1216,23 @@
|
||||
"ignoreHint": "One absolute path per line. Hooks from these folders, and anything under them, are dropped whole; history import and the Codex reader skip their sessions. AGENTHUB_IGNORE_CWD sets the same list.",
|
||||
"envOwned": "A value here is set by the environment the dashboard started in, and cannot be changed from this page."
|
||||
},
|
||||
"retention": {
|
||||
"title": "Automatic cleanup",
|
||||
"description": "Off by default. When on, the hourly maintenance deletes finished sessions (completed, error, abandoned) that started more than this many days ago — with their events, agents and token usage — a little at a time.",
|
||||
"days": "Delete sessions older than",
|
||||
"off": "Automatic cleanup is off.",
|
||||
"on": "Sessions older than {{days}} days are deleted every hour.",
|
||||
"invalid": "A whole number from 0 (off) to {{max}}",
|
||||
"saved": "Automatic cleanup saved",
|
||||
"lastRun": "Last run {{time}}: {{n}} session(s) deleted",
|
||||
"space": "Database {{size}} · {{free}} free inside it · auto-vacuum: {{mode}}",
|
||||
"compact": "Compact now",
|
||||
"compacting": "Compacting…",
|
||||
"compactConfirmTitle": "Compact the database?",
|
||||
"compactConfirmBody": "This rewrites the whole database file to give free space back to the disk and turns on incremental auto-vacuum. On a large database it takes a while, and new hook events wait until it finishes.",
|
||||
"compactDone": "Database compacted: {{before}} → {{after}}",
|
||||
"compactFailed": "Compact failed: {{error}}"
|
||||
},
|
||||
"backup": {
|
||||
"title": "Daily backup",
|
||||
"description": "A full copy of the database once a day, into a folder you choose — best on another disk, so a failed drive does not take the backups with it.",
|
||||
|
||||
@@ -166,7 +166,8 @@
|
||||
"EACTIVE": "This server's Claude Code keeps that login in the macOS Keychain. Switch it to another profile first.",
|
||||
"ENOTFOUND": "That saved login no longer exists.",
|
||||
"ESTALE": "That login was already refreshed elsewhere. Log in again and save it anew.",
|
||||
"EUPSTREAM": "Anthropic could not be reached. Try again."
|
||||
"EUPSTREAM": "Anthropic could not be reached. Try again.",
|
||||
"ENOUSER": "That user no longer exists."
|
||||
},
|
||||
"source": "From",
|
||||
"sources": {
|
||||
@@ -196,7 +197,20 @@
|
||||
"token": "The sk-ant-… that `claude setup-token` printed.",
|
||||
"codex": "An OpenAI API key (sk-…), or the whole ~/.codex/auth.json after `codex login` with a ChatGPT account."
|
||||
},
|
||||
"refreshFailed": "refresh failed"
|
||||
"refreshFailed": "refresh failed",
|
||||
"pinned": "Used by: {{users}}",
|
||||
"loadingUsers": "Loading…",
|
||||
"pinDone": {
|
||||
"own-login": "{{user}} signed in with their own login, which was left alone",
|
||||
"expired": "{{account}} has expired — {{user}}'s new sessions fall back to the least-used account"
|
||||
},
|
||||
"edit": "Edit {{name}}",
|
||||
"editHint": "Tick the users whose sessions run on this account instead of the least-used one — even when it is full. A user on another account moves here. A Claude login is written into their home at once: sessions already running move to it at their next login check, with no restart. A setup-token or Codex account applies to new sessions. Untick to send a user back to the least-used account.",
|
||||
"save": "Save",
|
||||
"users": "Users on this account",
|
||||
"noUsers": "No users yet.",
|
||||
"onAccount": "now on {{account}}",
|
||||
"editDone": "{{name}} saved"
|
||||
},
|
||||
"delete": {
|
||||
"button": "Delete user",
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
"copyLink": "Sao chép link",
|
||||
"preview": "Xem",
|
||||
"download": "Tải về",
|
||||
"noPreview": "Không xem trước được loại file này — hãy tải về để mở.",
|
||||
"install": "Cài",
|
||||
"installs": "{{count}} lượt cài",
|
||||
"installed": "Đã cài vào {{path}}",
|
||||
|
||||
@@ -37,18 +37,14 @@
|
||||
"chooseDesc": "Pet nổi bật lấy từ codex-pets.net và được tải về máy ở lần đầu bạn chọn. Lựa chọn và kích thước được lưu vào tài khoản của bạn.",
|
||||
"uploadHint": "Ảnh (PNG, JPEG, GIF, WebP — không nhận SVG) hiển thị tĩnh; file .codex-pet.zip (pet.json + spritesheet.webp 1536×1872) chuyển động theo tâm trạng.",
|
||||
"panel": {
|
||||
"label": "Trợ lý {{name}}",
|
||||
"live": "Trực tuyến",
|
||||
"offline": "Ngoại tuyến",
|
||||
"close": "Đóng {{name}}",
|
||||
"statLive": "đang chạy",
|
||||
"statWaiting": "đang chờ",
|
||||
"statErrored": "lỗi",
|
||||
"mute": "Tắt tiếng",
|
||||
"unmute": "Bật tiếng",
|
||||
"clearAlerts": "Xoá cảnh báo",
|
||||
"askPlaceholder": "Hỏi {{name}}… (vd: có lỗi nào không?)",
|
||||
"ask": "Hỏi {{name}}",
|
||||
"send": "Gửi",
|
||||
"rename": "Bấm để đổi tên {{name}}",
|
||||
"renameLabel": "Tên pet",
|
||||
@@ -217,9 +213,12 @@
|
||||
},
|
||||
"chat": {
|
||||
"label": "Trò chuyện với {{name}}",
|
||||
"back": "Quay lại",
|
||||
"close": "Đóng {{name}}",
|
||||
"new": "Cuộc trò chuyện mới",
|
||||
"status": "Trạng thái — bấm để xem các phiên cần bạn",
|
||||
"endTitle": "Kết thúc chat này?",
|
||||
"endBody": "Nó vẫn đang trả lời. Chat mới sẽ dừng phiên này.",
|
||||
"endConfirm": "Dừng và bắt đầu mới",
|
||||
"openWorkspace": "Mở trong workspace",
|
||||
"typing": "đang trả lời…",
|
||||
"placeholder": "Hỏi {{name}} bất cứ điều gì…",
|
||||
@@ -945,13 +944,16 @@
|
||||
"alias": "Tên tài khoản",
|
||||
"aliasPlaceholder": "tên (tuỳ chọn)",
|
||||
"aliasHint": "Để trống cho tài khoản mặc định của host này. Đặt tên (vd aws-prod, chữ thường, không dấu chấm) cho thêm một tài khoản: clone bằng ssh://<tên>/…",
|
||||
"awsMany": "Nhiều tài khoản AWS? Tạo thêm một RSA key bên dưới cho mỗi tài khoản, upload lên tài khoản đó, rồi lưu SSH key ID ở đây kèm tên tài khoản và key đó. Clone từng cái bằng ssh://<tên tài khoản>/v1/repos/<repo>.",
|
||||
"awsMany": "Nhiều tài khoản AWS? Tạo thêm một RSA key ở tab Key khác cho mỗi tài khoản, upload lên tài khoản đó, rồi lưu SSH key ID ở đây kèm tên tài khoản và key đó. Clone từng cái bằng ssh://<tên tài khoản>/v1/repos/<repo>.",
|
||||
"moreKeysTitle": "Thêm SSH key",
|
||||
"moreKeysSub": "Mỗi key cho một tài khoản phụ — tài khoản AWS khác, user GitHub thứ hai. Tài khoản nào gắn key thì chỉ dùng đúng key đó.",
|
||||
"newKey": "Key mới",
|
||||
"keyName": "Tên key",
|
||||
"keyNamePlaceholder": "vd aws-prod",
|
||||
"keyType": "Loại key"
|
||||
"keyType": "Loại key",
|
||||
"tabGit": "GitHub · GitLab",
|
||||
"tabMore": "Key khác",
|
||||
"tabOther": "Host khác"
|
||||
},
|
||||
"gitCreds": {
|
||||
"title": "Git credentials",
|
||||
@@ -1214,6 +1216,23 @@
|
||||
"ignoreHint": "Mỗi dòng một đường dẫn tuyệt đối. Hook từ các thư mục này, và mọi thứ bên trong, bị bỏ hoàn toàn; việc nhập lịch sử và bộ đọc Codex cũng bỏ qua phiên của chúng. AGENTHUB_IGNORE_CWD đặt cùng danh sách này.",
|
||||
"envOwned": "Một giá trị ở đây do môi trường khởi động dashboard đặt, và không thể đổi từ trang này."
|
||||
},
|
||||
"retention": {
|
||||
"title": "Tự động dọn dẹp",
|
||||
"description": "Mặc định tắt. Khi bật, bảo trì hằng giờ xóa các phiên đã kết thúc (hoàn tất, lỗi, bỏ dở) bắt đầu cách đây hơn số ngày này — cùng sự kiện, agent và token của chúng — từng ít một.",
|
||||
"days": "Xóa phiên cũ hơn",
|
||||
"off": "Tự động dọn dẹp đang tắt.",
|
||||
"on": "Phiên cũ hơn {{days}} ngày được xóa mỗi giờ.",
|
||||
"invalid": "Số nguyên từ 0 (tắt) đến {{max}}",
|
||||
"saved": "Đã lưu tự động dọn dẹp",
|
||||
"lastRun": "Lần chạy gần nhất {{time}}: đã xóa {{n}} phiên",
|
||||
"space": "Cơ sở dữ liệu {{size}} · {{free}} trống bên trong · auto-vacuum: {{mode}}",
|
||||
"compact": "Nén ngay",
|
||||
"compacting": "Đang nén…",
|
||||
"compactConfirmTitle": "Nén cơ sở dữ liệu?",
|
||||
"compactConfirmBody": "Thao tác này ghi lại toàn bộ tệp cơ sở dữ liệu để trả dung lượng trống cho ổ đĩa và bật auto-vacuum tăng dần. Với cơ sở dữ liệu lớn sẽ mất một lúc, và sự kiện hook mới phải chờ đến khi xong.",
|
||||
"compactDone": "Đã nén cơ sở dữ liệu: {{before}} → {{after}}",
|
||||
"compactFailed": "Nén thất bại: {{error}}"
|
||||
},
|
||||
"backup": {
|
||||
"title": "Backup hằng ngày",
|
||||
"description": "Mỗi ngày một bản sao đầy đủ của cơ sở dữ liệu vào thư mục bạn chọn — tốt nhất là trên một ổ đĩa khác, để hỏng một ổ không mất luôn bản backup.",
|
||||
|
||||
@@ -166,7 +166,8 @@
|
||||
"EACTIVE": "Claude Code của server giữ login này trong macOS Keychain. Hãy chuyển nó sang profile khác trước.",
|
||||
"ENOTFOUND": "Login đã lưu đó không còn nữa.",
|
||||
"ESTALE": "Login này đã được làm mới ở nơi khác. Đăng nhập lại và lưu lại.",
|
||||
"EUPSTREAM": "Không kết nối được Anthropic. Thử lại."
|
||||
"EUPSTREAM": "Không kết nối được Anthropic. Thử lại.",
|
||||
"ENOUSER": "User đó không còn tồn tại."
|
||||
},
|
||||
"source": "Nguồn",
|
||||
"sources": {
|
||||
@@ -196,7 +197,20 @@
|
||||
"token": "Chuỗi sk-ant-… mà `claude setup-token` in ra.",
|
||||
"codex": "OpenAI API key (sk-…), hoặc toàn bộ ~/.codex/auth.json sau khi `codex login` bằng tài khoản ChatGPT."
|
||||
},
|
||||
"refreshFailed": "làm mới lỗi"
|
||||
"refreshFailed": "làm mới lỗi",
|
||||
"pinned": "Đang dùng: {{users}}",
|
||||
"loadingUsers": "Đang tải…",
|
||||
"pinDone": {
|
||||
"own-login": "{{user}} đang dùng login riêng của họ, nên không bị ghi đè",
|
||||
"expired": "{{account}} đã hết hạn — phiên mới của {{user}} quay về tài khoản ít tải nhất"
|
||||
},
|
||||
"edit": "Sửa {{name}}",
|
||||
"editHint": "Tick các user mà phiên của họ chạy trên tài khoản này thay vì tài khoản ít tải nhất — kể cả khi nó đã đầy. User đang ở tài khoản khác sẽ chuyển sang đây. Login Claude được ghi ngay vào home của họ: phiên đang chạy chuyển sang ở lần kiểm tra đăng nhập kế tiếp, không cần khởi động lại. Setup-token hoặc tài khoản Codex áp dụng cho phiên mới. Bỏ tick để trả user về tài khoản ít tải nhất.",
|
||||
"save": "Lưu",
|
||||
"users": "User dùng tài khoản này",
|
||||
"noUsers": "Chưa có user nào.",
|
||||
"onAccount": "đang ở {{account}}",
|
||||
"editDone": "Đã lưu {{name}}"
|
||||
},
|
||||
"delete": {
|
||||
"button": "Xoá user",
|
||||
|
||||
@@ -207,6 +207,35 @@ describe("panePaste", () => {
|
||||
expect(m.options.map((o) => o.n)).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
it("reads Claude's unnumbered trust prompt and picks by arrows", () => {
|
||||
vi.useFakeTimers();
|
||||
const m = parsePaneMenu(TRUST)!;
|
||||
expect(m.options.map((o) => o.label)).toEqual(["No, exit", "Yes, I trust this folder"]);
|
||||
expect(m.options.every((o) => o.n === null)).toBe(true);
|
||||
expect(m.cursor).toBe(0);
|
||||
expect(m.question.split("\n")[0]).toBe("Accessing workspace:");
|
||||
expect(m.question).toContain("Security guide");
|
||||
const keys: string[] = [];
|
||||
const off = registerPane(
|
||||
"agenthub-lane-12",
|
||||
() => {},
|
||||
() => true,
|
||||
(k) => keys.push(k)
|
||||
);
|
||||
expect(chooseRunOption("agenthub-lane-12", m, 1)).toBe(true);
|
||||
vi.runAllTimers();
|
||||
expect(keys).toEqual(["\x1b[B", "\r"]);
|
||||
off();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("finds no unnumbered menu in Claude's input box or a wrapped prompt above it", () => {
|
||||
expect(parsePaneMenu(CLAUDE)).toBeNull();
|
||||
expect(
|
||||
parsePaneMenu(["❯ a long prompt that", " wrapped onto two rows", "", RULE, "❯\u00a0", RULE])
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("finds no menu in a reply's numbered list or a typed `1.`", () => {
|
||||
// No cursor on the list.
|
||||
expect(parsePaneMenu(["● Steps:", " 1. one", " 2. two", "", RULE, "❯ ", RULE])).toBeNull();
|
||||
@@ -313,12 +342,35 @@ const CODEX_APPROVAL = [
|
||||
" enteresc",
|
||||
];
|
||||
|
||||
// Claude Code's folder-trust prompt: no numbers, its footer dim (left out).
|
||||
const TRUST = [
|
||||
RULE,
|
||||
" Accessing workspace:",
|
||||
"",
|
||||
" /home/me",
|
||||
"",
|
||||
" Quick safety check: Is this a project you created or one you trust?",
|
||||
"",
|
||||
" Security guide",
|
||||
"",
|
||||
" ❯ No, exit",
|
||||
" Yes, I trust this folder",
|
||||
"",
|
||||
"",
|
||||
];
|
||||
|
||||
describe("MENU_CURSOR_ROW", () => {
|
||||
// The chat's 700 ms poll reads the screen cell by cell only when a row
|
||||
// matches it, so every menu parsePaneMenu finds must have such a row.
|
||||
it("matches a row of every menu, and no row of an idle prompt", () => {
|
||||
const has = (rows: string[]) => rows.some((r) => MENU_CURSOR_ROW.test(r));
|
||||
for (const menu of [ASK, MULTI, PERMISSION, CODEX_APPROVAL]) {
|
||||
for (const menu of [
|
||||
ASK,
|
||||
MULTI,
|
||||
PERMISSION,
|
||||
CODEX_APPROVAL,
|
||||
[...TRUST, " Enter to confirm · Esc to cancel"],
|
||||
]) {
|
||||
expect(parsePaneMenu(menu)).not.toBeNull();
|
||||
expect(has(menu)).toBe(true);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* @file sessionChange.test.ts
|
||||
* @description Unit tests for `sessionChangeMatcher`: fires on a new session
|
||||
* and on a change of the keyed columns, never on a re-broadcast that moved none.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { sessionChangeMatcher } from "../sessionChange";
|
||||
import type { WSMessage } from "../types";
|
||||
|
||||
const msg = (type: string, data: unknown) => ({ type, data, timestamp: "" }) as WSMessage;
|
||||
|
||||
describe("sessionChangeMatcher", () => {
|
||||
it("fires on a new session and on a state change, not on a same-state re-broadcast", () => {
|
||||
const m = sessionChangeMatcher();
|
||||
expect(m(msg("session_created", { id: "a", status: "active" }))).toBe(true);
|
||||
expect(m(msg("session_updated", { id: "a", status: "active", name: "x" }))).toBe(false);
|
||||
expect(
|
||||
m(msg("session_updated", { id: "a", status: "active", awaiting_input_since: "t" }))
|
||||
).toBe(true);
|
||||
expect(m(msg("session_updated", { id: "a", status: "completed" }))).toBe(true);
|
||||
expect(m(msg("session_updated", { id: "a", status: "completed", archived_at: "t" }))).toBe(
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
it("takes an unseen or unkeyable session as a change, and ignores other types", () => {
|
||||
const m = sessionChangeMatcher();
|
||||
expect(m(msg("session_updated", { id: "b", status: "active" }))).toBe(true);
|
||||
expect(m(msg("session_updated", null))).toBe(true);
|
||||
expect(m(msg("new_event", { session_id: "b" }))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -676,9 +676,18 @@ export type CodexPoolAccount = {
|
||||
quotaPercent: number | null;
|
||||
full: boolean;
|
||||
};
|
||||
/** A user an admin pinned to one pool account: their new sessions skip the balancer. */
|
||||
export type AccountPin = {
|
||||
userId: number;
|
||||
username: string;
|
||||
account: string;
|
||||
pinnedAt?: string;
|
||||
};
|
||||
export type AccountPool = {
|
||||
accounts: PoolAccount[];
|
||||
codex: CodexPoolAccount[];
|
||||
/** Per tool; absent from an older server, empty in local mode. */
|
||||
pins?: { claude: AccountPin[]; codex: AccountPin[] };
|
||||
blockPercent: number;
|
||||
};
|
||||
export type PoolTool = "claude" | "codex";
|
||||
@@ -1052,6 +1061,20 @@ export const api = {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ ...body, currentPassword }),
|
||||
}),
|
||||
/** PUT /api/accounts/:name/users — admin: exactly these users run on this account. */
|
||||
setUsers: (tool: PoolTool, name: string, userIds: number[], currentPassword: string) =>
|
||||
request<{
|
||||
/** Users moved onto it; `switched`: what happened now (a Claude login goes into their home). */
|
||||
added: {
|
||||
userId: number;
|
||||
username: string;
|
||||
switched: "switched" | "kept" | "own-login" | "expired" | "next-session";
|
||||
}[];
|
||||
removed: { userId: number; username: string }[];
|
||||
}>(`/accounts/${encodeURIComponent(name)}/users`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ tool, userIds, currentPassword }),
|
||||
}),
|
||||
/** DELETE /api/accounts/:name — admin, with their OWN password again. */
|
||||
remove: (tool: PoolTool, name: string, currentPassword: string) =>
|
||||
request<{ ok: true }>(`/accounts/${encodeURIComponent(name)}`, {
|
||||
@@ -1649,6 +1672,23 @@ export const api = {
|
||||
/** POST /api/settings/backup/run — starts one; poll `get` while `running` */
|
||||
run: () => request<BackupState & { ok: boolean }>("/settings/backup/run", { method: "POST" }),
|
||||
},
|
||||
/** Opt-in automatic retention and Compact (`server/lib/db-retention.js`). */
|
||||
retention: {
|
||||
/** GET /api/settings/retention */
|
||||
get: () => request<RetentionState>("/settings/retention"),
|
||||
/** PUT /api/settings/retention — `days` 0 turns it off */
|
||||
save: (days: number) =>
|
||||
request<RetentionState & { ok: boolean }>("/settings/retention", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ days }),
|
||||
}),
|
||||
/** POST /api/settings/compact — a full VACUUM; poll `get` while `compacting` */
|
||||
compact: () =>
|
||||
request<RetentionState & { ok: boolean }>("/settings/compact", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ confirm: true }),
|
||||
}),
|
||||
},
|
||||
/** The bearer token for `POST /api/hooks/ingest-batch`. Only its hash is
|
||||
* stored: `rotate` returns the new token this once, `get` never does. */
|
||||
pushToken: {
|
||||
@@ -5461,6 +5501,36 @@ export interface BackupState {
|
||||
env_owned: { dir: boolean; hour: boolean; keep: boolean };
|
||||
}
|
||||
|
||||
/** GET /api/settings/retention. `days` 0 = automatic retention off;
|
||||
* `last_run`/`last_compact` are this server process's own. */
|
||||
export interface RetentionState {
|
||||
days: number;
|
||||
max_days: number;
|
||||
env_owned: { days: boolean };
|
||||
last_run: {
|
||||
at: string;
|
||||
retention?: { purged_sessions: number; purged_events: number; error?: string };
|
||||
reclaim?: { reclaimed_pages: number; error?: string };
|
||||
} | null;
|
||||
space: {
|
||||
auto_vacuum: "none" | "full" | "incremental";
|
||||
page_size: number;
|
||||
page_count: number;
|
||||
freelist_pages: number;
|
||||
free_bytes: number;
|
||||
} | null;
|
||||
db_size: number;
|
||||
compacting: boolean;
|
||||
last_compact: {
|
||||
at: string;
|
||||
ok: boolean;
|
||||
size_before?: number;
|
||||
size_after?: number;
|
||||
ms?: number;
|
||||
error?: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
/** GET /api/settings/push-token — whether push ingest is on; never the token. */
|
||||
export interface PushTokenStatus {
|
||||
enabled: boolean;
|
||||
|
||||
@@ -14,6 +14,9 @@
|
||||
* terminal moves the unsent prompt across (`takeRunInput` reads the TUI's
|
||||
* input box off the screen and empties it; the chat's draft is pasted back
|
||||
* without Enter), so the half-typed text is never left behind on the other side.
|
||||
* Attached images' paths go after the text, each in a paste of its own: `claude`
|
||||
* turns a paste that is only an image's path into `[Image #n]`, but left a
|
||||
* Windows path (`C:\…\drops\…png`) inside a paste of text as a plain path.
|
||||
* The Chat view also answers a menu the CLI asks with (`parsePaneMenu` reads
|
||||
* it off the screen; `chooseRunOption`/`answerRunMenu` press its digit, the
|
||||
* arrows and Enter, or type into its "Type something" row).
|
||||
@@ -24,7 +27,8 @@
|
||||
export type PaneScreen = { rows: string[]; cols: number };
|
||||
|
||||
interface Pane {
|
||||
paste: (text: string, submit?: boolean) => void;
|
||||
/** `files`: image paths pasted after `text`, one paste each. */
|
||||
paste: (text: string, submit?: boolean, files?: string[]) => void;
|
||||
visible: () => boolean;
|
||||
key?: (data: string) => void;
|
||||
/** `menuOnly`: null at once unless a row could be a menu's cursor row. */
|
||||
@@ -62,19 +66,19 @@ function ofLane(runId: string, laneId: number): boolean {
|
||||
|
||||
/** Pastes `text` into the pane of `runId` when it is mounted and on screen;
|
||||
* false otherwise (not mounted yet, or hidden). */
|
||||
export function pasteToRun(runId: string, text: string): boolean {
|
||||
export function pasteToRun(runId: string, text: string, files: string[] = []): boolean {
|
||||
const p = panes.get(runId);
|
||||
if (!p?.visible()) return false;
|
||||
p.paste(text);
|
||||
p.paste(text, false, files);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Sends `text` as a message to the pane of `runId`: a paste, then Enter.
|
||||
* False when the pane is not mounted or not attached. */
|
||||
export function submitToRun(runId: string, text: string): boolean {
|
||||
export function submitToRun(runId: string, text: string, files: string[] = []): boolean {
|
||||
const p = panes.get(runId);
|
||||
if (!p?.visible()) return false;
|
||||
p.paste(text, true);
|
||||
p.paste(text, true, files);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -176,8 +180,9 @@ export type PaneMenu = {
|
||||
};
|
||||
|
||||
const OPTION = /^ {0,4}([❯›][ \u00a0]?)? *(\d{1,2})\. +(.*)$/;
|
||||
/** A row a menu's cursor sits on (a numbered option or Submit): a menu has one. */
|
||||
export const MENU_CURSOR_ROW = /^ *[❯›][ \u00a0]* *(?:\d{1,2}\. |Submit\s*$)/;
|
||||
/** A row only a menu shows: its cursor on a numbered option or Submit, or the
|
||||
* "Enter to confirm" footer of Claude's unnumbered menus (the trust prompt). */
|
||||
export const MENU_CURSOR_ROW = /^ *(?:[❯›][ \u00a0]* *(?:\d{1,2}\. |Submit\s*$)|Enter to confirm)/;
|
||||
const SUBMIT = /^ *([❯›])?[ \u00a0]*Submit$/;
|
||||
const RULE_ROW = /^ *[─╌]{3,} *$/;
|
||||
const CHECK = /^\[([ ✔])\] *(.*)$/;
|
||||
@@ -224,7 +229,8 @@ export function parsePaneMenu(rows: string[]): PaneMenu | null {
|
||||
}
|
||||
}
|
||||
const numbered = options.filter((o) => o.n !== null);
|
||||
if (top < 0 || cursor < 0 || numbered.length < 2 || RULE_ROW.test(r[top - 1] ?? "")) return null;
|
||||
if (top < 0 || cursor < 0 || numbered.length < 2 || RULE_ROW.test(r[top - 1] ?? ""))
|
||||
return parseBareMenu(r.slice(0, end + 1));
|
||||
if (numbered.some((o, i) => o.n !== i + 1)) return null;
|
||||
// The question: the block of text right above the first option.
|
||||
let q = top - 1;
|
||||
@@ -241,6 +247,39 @@ export function parsePaneMenu(rows: string[]): PaneMenu | null {
|
||||
};
|
||||
}
|
||||
|
||||
const BARE_CURSOR = /^( {0,4})❯[ \u00a0]+(\S.*)$/;
|
||||
|
||||
/** Claude's UNNUMBERED menu at the bottom of `r` (the folder-trust prompt:
|
||||
* `❯ No, exit` over ` Yes, I trust this folder`), or null. Its rows share the
|
||||
* cursor row's text column, and nothing under them is a rule — Claude's input
|
||||
* box draws one above and below its `❯` row, so neither the box nor a prompt
|
||||
* in the history above it reads as a menu. Picked by arrows and Enter. */
|
||||
function parseBareMenu(r: string[]): PaneMenu | null {
|
||||
let at = -1;
|
||||
for (let i = r.length - 1; i >= 0 && at < 0; i--) if (BARE_CURSOR.test(r[i] ?? "")) at = i;
|
||||
if (at < 0 || RULE_ROW.test(r[at - 1] ?? "") || r.slice(at + 1).some((l) => RULE_ROW.test(l)))
|
||||
return null;
|
||||
const m = BARE_CURSOR.exec(r[at]!)!;
|
||||
const indent = " ".repeat((m[1] ?? "").length + 2);
|
||||
const sibling = (l = "") => l.startsWith(indent) && /\S/.test(l[indent.length] ?? " ");
|
||||
let top = at;
|
||||
while (top > 0 && sibling(r[top - 1])) top--;
|
||||
let last = at;
|
||||
while (last < r.length - 1 && sibling(r[last + 1])) last++;
|
||||
if (last === top) return null;
|
||||
const options = r.slice(top, last + 1).map((l, i) => ({
|
||||
n: null,
|
||||
label: top + i === at ? (m[2] ?? "").trim() : l.trim(),
|
||||
hint: "",
|
||||
checked: null,
|
||||
}));
|
||||
// The question: the paragraphs above, up to the dialog's top rule.
|
||||
const lines: string[] = [];
|
||||
for (let q = top - 1; q >= 0 && !RULE_ROW.test(r[q]!) && lines.length < 8; q--)
|
||||
if (r[q]) lines.unshift(r[q]!.trim());
|
||||
return { question: lines.join("\n"), options, cursor: at - top, multi: false, typeAt: -1 };
|
||||
}
|
||||
|
||||
/** The "Type something" row. Text typed into it replaces its label, and it is
|
||||
* still the last numbered row above "Chat about this". */
|
||||
function typeRow(options: PaneMenuOption[]): number {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* @file sessionChange.ts
|
||||
* @description `session_created` / `session_updated` matcher for live-refresh
|
||||
* callers that care about only a few session columns. A session row is
|
||||
* re-broadcast on nearly every hook (last activity, name, tokens…), so
|
||||
* matching the bare message types made every such frame refetch; this one
|
||||
* fires on a new session, or when the chosen key of a session actually
|
||||
* changed. Each call keeps its own memory of the keys it has seen.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import type { Session, WSMessage } from "./types";
|
||||
|
||||
/** The columns that move a session between the active / waiting / archived counts. */
|
||||
export const sessionStateKeyOf = (s: Partial<Session>): string =>
|
||||
`${s.status}:${s.awaiting_input_since ? 1 : 0}:${s.archived_at ? 1 : 0}`;
|
||||
|
||||
export function sessionChangeMatcher(
|
||||
keyOf: (s: Partial<Session>) => string = sessionStateKeyOf
|
||||
): (msg: WSMessage) => boolean {
|
||||
const seen = new Map<string, string>();
|
||||
return (msg) => {
|
||||
if (msg.type !== "session_created" && msg.type !== "session_updated") return false;
|
||||
const s = msg.data as Partial<Session> | undefined;
|
||||
// A frame we cannot key is taken as a change: refetching is the safe side.
|
||||
if (!s || typeof s.id !== "string") return true;
|
||||
const key = keyOf(s);
|
||||
if (msg.type === "session_updated" && seen.get(s.id) === key) return false;
|
||||
seen.set(s.id, key);
|
||||
return true;
|
||||
};
|
||||
}
|
||||
@@ -13,6 +13,9 @@
|
||||
* the server's sandboxed `raw` route in a sandboxed iframe, so nothing a
|
||||
* shared HTML file carries runs on the dashboard's origin. Right-clicking a
|
||||
* card offers the same actions as its buttons, plus copying a page's link.
|
||||
* Preview is offered only for what a browser shows inside that sandbox (text,
|
||||
* images, HTML, audio/video); an Office file, a zip or a PDF is downloaded —
|
||||
* the sandbox blocks both a download and the PDF viewer, so it would be blank.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
@@ -63,6 +66,9 @@ function fmtBytes(n: number | null): string {
|
||||
}
|
||||
|
||||
const IMAGE = /\.(png|jpe?g|gif|webp|svg)$/i;
|
||||
// What the sandboxed preview can show: the server's typed list minus PDF.
|
||||
const PREVIEWABLE =
|
||||
/\.(html?|md|markdown|txt|log|csv|tsv|json|ya?ml|sh|py|js|ts|png|jpe?g|gif|webp|svg|mp4|webm|mp3|wav)$/i;
|
||||
|
||||
export function Artifacts() {
|
||||
const { t } = useTranslation("artifacts");
|
||||
@@ -73,6 +79,7 @@ export function Artifacts() {
|
||||
const [items, setItems] = useState<Artifact[] | null>(null);
|
||||
const [adding, setAdding] = useState<ArtifactKind | null>(null);
|
||||
const [addMenu, setAddMenu] = useState(false);
|
||||
const addMenuRef = useRef<HTMLDivElement>(null);
|
||||
const [preview, setPreview] = useState<{ item: Artifact; path: string } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -105,6 +112,23 @@ export function Artifacts() {
|
||||
[load]
|
||||
);
|
||||
|
||||
// The Add menu closes on Escape or a click anywhere outside it.
|
||||
useEffect(() => {
|
||||
if (!addMenu) return;
|
||||
const onDown = (e: MouseEvent) => {
|
||||
if (!addMenuRef.current?.contains(e.target as Node)) setAddMenu(false);
|
||||
};
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") setAddMenu(false);
|
||||
};
|
||||
document.addEventListener("mousedown", onDown);
|
||||
document.addEventListener("keydown", onKey);
|
||||
return () => {
|
||||
document.removeEventListener("mousedown", onDown);
|
||||
document.removeEventListener("keydown", onKey);
|
||||
};
|
||||
}, [addMenu]);
|
||||
|
||||
const server = !!settings?.serverMode;
|
||||
|
||||
const share = async (a: Artifact) => {
|
||||
@@ -186,11 +210,13 @@ export function Artifacts() {
|
||||
<p className="text-sm text-fg-muted">{t(server ? "subtitleServer" : "subtitle")}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="relative">
|
||||
<div className="relative" ref={addMenuRef}>
|
||||
<button
|
||||
type="button"
|
||||
className="btn-primary flex items-center gap-1.5 text-sm"
|
||||
data-testid="artifacts-add"
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={addMenu}
|
||||
onClick={() => setAddMenu((v) => !v)}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
@@ -334,7 +360,9 @@ function ArtifactCard({
|
||||
fn();
|
||||
};
|
||||
const previewPath = a.kind === "skill" ? "SKILL.md" : (a.files[0]?.path ?? "");
|
||||
const canPreview = (a.kind === "file" || a.kind === "skill") && a.files.length > 0;
|
||||
const canPreview =
|
||||
a.files.length > 0 &&
|
||||
(a.kind === "skill" || (a.kind === "file" && PREVIEWABLE.test(previewPath)));
|
||||
const btn =
|
||||
"flex items-center gap-1 rounded px-1.5 py-0.5 text-[11px] text-fg-secondary hover:bg-surface-3 hover:text-fg-primary";
|
||||
return (
|
||||
@@ -598,6 +626,7 @@ function PreviewDialog({
|
||||
path: string;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation("artifacts");
|
||||
const [current, setCurrent] = useState(path);
|
||||
const url = api.artifacts.rawUrl(item.id, current);
|
||||
return (
|
||||
@@ -624,7 +653,18 @@ function PreviewDialog({
|
||||
</ul>
|
||||
)}
|
||||
<div className="min-w-0 flex-1 rounded border border-border bg-white">
|
||||
{IMAGE.test(current) && !/\.svg$/i.test(current) ? (
|
||||
{!PREVIEWABLE.test(current) ? (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-3 bg-surface-1 p-6 text-center">
|
||||
<p className="text-sm text-fg-secondary">{t("noPreview")}</p>
|
||||
<a
|
||||
href={api.artifacts.rawUrl(item.id, current, true)}
|
||||
className="btn-primary flex items-center gap-1.5 text-sm"
|
||||
>
|
||||
<Download className="h-4 w-4" />
|
||||
{t("download")}
|
||||
</a>
|
||||
</div>
|
||||
) : IMAGE.test(current) && !/\.svg$/i.test(current) ? (
|
||||
<img src={url} alt={current} className="h-full w-full object-contain" />
|
||||
) : (
|
||||
// No allow-* tokens: a shared page renders, nothing in it runs.
|
||||
|
||||
@@ -2790,9 +2790,12 @@ function RecentActivityPanel({ sessionsById }: { sessionsById: Map<string, Sessi
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
useLiveRefresh(load, { intervalMs: 10000 });
|
||||
// New events arrive over the WebSocket (prepended below); a reload is only
|
||||
// for what the socket cannot carry: a remote source's import, a gap while it
|
||||
// was down (reconnect) or the tab hidden (shown again), and a slow safety poll.
|
||||
useLiveRefresh(load, { intervalMs: 60000, match: isRemoteDataRefreshMessage });
|
||||
|
||||
// A new event is prepended at once (no reload); the poll reconciles.
|
||||
// A new event is prepended at once (no reload); the reloads reconcile.
|
||||
useEffect(
|
||||
() =>
|
||||
eventBus.subscribe((msg: WSMessage) => {
|
||||
|
||||
@@ -1129,7 +1129,11 @@ export function SessionDetail() {
|
||||
|
||||
{visitedTabs.has("conversation") && (
|
||||
<div hidden={activeTab !== "conversation"}>
|
||||
<ConversationView sessionId={session.id} initialTranscriptId={pendingTranscriptId} />
|
||||
<ConversationView
|
||||
sessionId={session.id}
|
||||
initialTranscriptId={pendingTranscriptId}
|
||||
ended={session.status !== "active"}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* @file Settings.tsx
|
||||
* @description The install-wide settings, as three pages of the Settings nav (`SettingsHub.tsx`): `section="data"` — total cost, database overview, workspace housekeeping (dry run first, confirm before a real run), import, remote sources, push ingest (`components/settings/PushIngestSettings.tsx`), privacy (`components/settings/PrivacySettings.tsx`), the daily database backup (`components/settings/BackupSettings.tsx`), export, this browser's preferences backup, session cleanup (whole days ≥ 1, a dry-run count in its confirm) and the danger zone (typed confirmation) —, `section="about"` (the System page) — the start-at-login switch and Quit (`AutostartSettings`), then the server process (release, uptime, platform, CPU, memory, live connections), how AgentHub is installed (the update check's cached status) and the database file — and `section="notifications"` — browser notifications (per-browser, with a reset) and alerts (server-wide). Server info (`/api/settings/info`) is read only by Data and About, refreshed on activity at most every 10 s. Language, theme and the pet live on the Appearance page (`components/settings/AppearanceSettings.tsx`); per-tool settings live in that tool's page under `/settings/agents/<id>`.
|
||||
* @description The install-wide settings, as three pages of the Settings nav (`SettingsHub.tsx`): `section="data"` — total cost, database overview, workspace housekeeping (dry run first, confirm before a real run), import, remote sources, push ingest (`components/settings/PushIngestSettings.tsx`), privacy (`components/settings/PrivacySettings.tsx`), the daily database backup (`components/settings/BackupSettings.tsx`), export, this browser's preferences backup, session cleanup (whole days ≥ 1, a dry-run count in its confirm; under it the opt-in automatic cleanup and Compact, `components/settings/RetentionSettings.tsx`) and the danger zone (typed confirmation) —, `section="about"` (the System page) — the start-at-login switch and Quit (`AutostartSettings`), then the server process (release, uptime, platform, CPU, memory, live connections), how AgentHub is installed (the update check's cached status) and the database file — and `section="notifications"` — browser notifications (per-browser, with a reset) and alerts (server-wide). Server info (`/api/settings/info`) is read only by Data and About, refreshed on activity at most every 10 s. Language, theme and the pet live on the Appearance page (`components/settings/AppearanceSettings.tsx`); per-tool settings live in that tool's page under `/settings/agents/<id>`.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
/* =============================================================================
|
||||
@@ -103,6 +103,7 @@ import { RemoteSources } from "../components/RemoteSources";
|
||||
import { PushIngestSettings } from "../components/settings/PushIngestSettings";
|
||||
import { PrivacySettings } from "../components/settings/PrivacySettings";
|
||||
import { BackupSettings } from "../components/settings/BackupSettings";
|
||||
import { RetentionSettings } from "../components/settings/RetentionSettings";
|
||||
import { AutostartSettings } from "../components/settings/AutostartSettings";
|
||||
import { usePermissions } from "../components/AuthGate";
|
||||
import { Skeleton } from "../components/Skeleton";
|
||||
@@ -1054,6 +1055,8 @@ export function Settings({
|
||||
</button>
|
||||
|
||||
{actionBanner(["cleanup"])}
|
||||
|
||||
<RetentionSettings />
|
||||
</section>
|
||||
|
||||
{/* ─── THIS BROWSER'S PREFERENCES ─── */}
|
||||
|
||||
@@ -85,6 +85,9 @@ import { endRuns } from "../lib/stopSession";
|
||||
import { ContextMenu, MenuItem, useContextMenu } from "../components/ContextMenu";
|
||||
import { confirmDiscard } from "../lib/confirm";
|
||||
import { keepIfSame } from "../lib/keepIfSame";
|
||||
import { laneChangeMatcher, runKeyOf } from "../lib/laneChange";
|
||||
import { sessionChangeMatcher } from "../lib/sessionChange";
|
||||
import { useLiveRefresh } from "../hooks/useLiveRefresh";
|
||||
import { useWorkLanes } from "../hooks/useLanes";
|
||||
import { LaneConsolePane } from "../components/run/LaneConsolePane";
|
||||
import {
|
||||
@@ -1044,9 +1047,10 @@ export function Workspace() {
|
||||
.catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
// Goes through `keepIfSame`: this fires every 5 s below, and a
|
||||
// fresh-but-identical payload would otherwise re-render the lane strip, the
|
||||
// lane card and the whole console area on every tick for nothing.
|
||||
// Goes through `keepIfSame`: this re-reads on run-moving messages and a
|
||||
// fallback poll below, and a fresh-but-identical payload would otherwise
|
||||
// re-render the lane strip, the lane card and the whole console area for
|
||||
// nothing.
|
||||
const refreshList = useCallback(() => {
|
||||
api.run
|
||||
.list()
|
||||
@@ -1061,33 +1065,30 @@ export function Workspace() {
|
||||
window.dispatchEvent(new CustomEvent(LIVE_RUNS_EVENT, { detail: activeRuns.items }));
|
||||
}, [activeRuns]);
|
||||
|
||||
// Background poll so the run list and history reflect external changes
|
||||
// (server-boot reconciliation, sibling tabs, direct DB edits) even when
|
||||
// no WS event fires. Lighter than typical WS gaps; aggressive enough that
|
||||
// status flips appear within seconds without needing a manual refresh.
|
||||
// The run list follows the WebSocket instead of a blind 5 s poll: a pane
|
||||
// starting, ending or learning its session in slot 0 moves the lane's run
|
||||
// columns (`lane_update`); an agent starting in a free tab (slots 1–9)
|
||||
// shows as a new session, one ending as a session status change, and a pane
|
||||
// dying under its agent as `runs_interrupted`. This page's own starts, stops
|
||||
// and a shown terminal's exit call `refreshList` directly
|
||||
// (`onRunsChanged`). What none of those cover — a shell tab opened or closed
|
||||
// from another browser, server-boot reconciliation — is caught by the
|
||||
// 30 s fallback poll, on reconnect, and when the tab is shown or focused.
|
||||
const [laneRunChanged] = useState(() => laneChangeMatcher(runKeyOf));
|
||||
const [sessionRunChanged] = useState(() => sessionChangeMatcher((s) => `${s.status}`));
|
||||
useEffect(() => {
|
||||
refreshList();
|
||||
const tick = setInterval(() => {
|
||||
// Hidden tab: skip; the visibility handler below re-reads on show.
|
||||
if (document.visibilityState === "visible") refreshList();
|
||||
}, 5000);
|
||||
return () => clearInterval(tick);
|
||||
}, [refreshList]);
|
||||
|
||||
// Refresh whenever the tab regains focus / visibility - typical when the
|
||||
// user comes back from running `claude` in a terminal and wants to see the
|
||||
// current state of every run without waiting for the next poll.
|
||||
useLiveRefresh(refreshList, {
|
||||
intervalMs: 30_000,
|
||||
throttleMs: 1500,
|
||||
match: (msg) =>
|
||||
msg.type === "runs_interrupted" || laneRunChanged(msg) || sessionRunChanged(msg),
|
||||
});
|
||||
useEffect(() => {
|
||||
const onFocus = () => refreshList();
|
||||
const onVis = () => {
|
||||
if (document.visibilityState === "visible") refreshList();
|
||||
};
|
||||
window.addEventListener("focus", onFocus);
|
||||
document.addEventListener("visibilitychange", onVis);
|
||||
return () => {
|
||||
window.removeEventListener("focus", onFocus);
|
||||
document.removeEventListener("visibilitychange", onVis);
|
||||
};
|
||||
return () => window.removeEventListener("focus", onFocus);
|
||||
}, [refreshList]);
|
||||
|
||||
const currentLane = selectedLaneId !== null ? lanes.find((l) => l.id === selectedLaneId) : null;
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
* a plugin is picked from the list its marketplace link answers (a link the
|
||||
* server cannot read opens the by-hand form), a skill is uploaded from one
|
||||
* Markdown file under the name the user types, or written in the dialog.
|
||||
* A card's right-click menu runs the same actions (Preview, Delete).
|
||||
* A card's right-click menu runs the same actions (Preview, Delete). A file
|
||||
* the sandbox cannot show (Office, zip, PDF) offers Download only, and the
|
||||
* Add menu closes on Escape or a click outside it.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
@@ -253,4 +255,27 @@ describe("Artifacts", () => {
|
||||
"/api/artifacts/1/raw?path=report.html"
|
||||
);
|
||||
});
|
||||
|
||||
it("offers no preview for a file the sandbox cannot show, only its download", async () => {
|
||||
vi.mocked(api.artifacts.list).mockResolvedValue({
|
||||
items: [item({ title: "plan.docx", files: [{ path: "plan.docx", size: 10 }] })],
|
||||
});
|
||||
open();
|
||||
const card = await screen.findByTestId("artifact-1");
|
||||
expect(within(card).queryByRole("button", { name: "Preview" })).toBeNull();
|
||||
expect(within(card).getByRole("link", { name: "Download" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("closes the Add menu on Escape and on a click outside it", async () => {
|
||||
const user = userEvent.setup();
|
||||
open();
|
||||
await screen.findByText("deploy");
|
||||
await user.click(screen.getByTestId("artifacts-add"));
|
||||
expect(screen.getByRole("button", { name: "Skill" })).toBeInTheDocument();
|
||||
await user.keyboard("{Escape}");
|
||||
expect(screen.queryByRole("button", { name: "Skill" })).toBeNull();
|
||||
await user.click(screen.getByTestId("artifacts-add"));
|
||||
await user.click(screen.getByText("report.html"));
|
||||
expect(screen.queryByRole("button", { name: "Skill" })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -77,6 +77,18 @@ vi.mock("../../lib/api", async (importOriginal) => {
|
||||
env_owned: { dir: false, hour: false, keep: false },
|
||||
})),
|
||||
},
|
||||
retention: {
|
||||
get: vi.fn(async () => ({
|
||||
days: 0,
|
||||
max_days: 3650,
|
||||
env_owned: { days: false },
|
||||
last_run: null,
|
||||
space: null,
|
||||
db_size: 0,
|
||||
compacting: false,
|
||||
last_compact: null,
|
||||
})),
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -7022,7 +7022,7 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
class="mt-2"
|
||||
>
|
||||
<div
|
||||
class="flex justify-between gap-4 border-b border-border/60 last:border-b-0 py-3 items-center"
|
||||
class="flex justify-between gap-6 border-b border-border/60 last:border-b-0 py-3 items-center"
|
||||
>
|
||||
<div
|
||||
class="min-w-0"
|
||||
@@ -7033,7 +7033,7 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
Start AgentHub automatically
|
||||
</p>
|
||||
<p
|
||||
class="mt-0.5 text-xs text-fg-muted"
|
||||
class="mt-0.5 text-xs leading-relaxed text-fg-muted"
|
||||
>
|
||||
Run the dashboard as a systemd --user service, so it starts at boot without Claude Code being opened. Turning it off keeps the running server up.
|
||||
</p>
|
||||
@@ -7044,19 +7044,19 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
<button
|
||||
aria-checked="false"
|
||||
aria-label="Start AgentHub automatically"
|
||||
class="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-1 focus-visible:ring-offset-surface-0 disabled:cursor-not-allowed disabled:opacity-50 bg-border-light ring-1 ring-inset ring-fg-muted/80"
|
||||
class="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-1 focus-visible:ring-offset-surface-0 disabled:cursor-not-allowed disabled:opacity-40 bg-border-light ring-1 ring-inset ring-fg-muted/80 enabled:hover:ring-fg-secondary"
|
||||
role="switch"
|
||||
type="button"
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
class="inline-block h-4 w-4 rounded-full bg-white shadow transition-transform translate-x-0.5"
|
||||
class="inline-block h-4 w-4 rounded-full bg-white shadow-sm ring-1 ring-black/10 transition-transform duration-200 ease-out translate-x-0.5"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="flex justify-between gap-4 border-b border-border/60 last:border-b-0 py-3 items-center"
|
||||
class="flex justify-between gap-6 border-b border-border/60 last:border-b-0 py-3 items-center"
|
||||
>
|
||||
<div
|
||||
class="min-w-0"
|
||||
@@ -7067,7 +7067,7 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
Show AgentHub icon in the status area
|
||||
</p>
|
||||
<p
|
||||
class="mt-0.5 text-xs text-fg-muted"
|
||||
class="mt-0.5 text-xs leading-relaxed text-fg-muted"
|
||||
>
|
||||
An AgentHub icon beside the clock (top bar, menu bar or notification area) to open the dashboard, quit it, and start it again after a quit.
|
||||
</p>
|
||||
@@ -7078,19 +7078,19 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
<button
|
||||
aria-checked="true"
|
||||
aria-label="Show AgentHub icon in the status area"
|
||||
class="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-1 focus-visible:ring-offset-surface-0 disabled:cursor-not-allowed disabled:opacity-50 bg-accent-solid"
|
||||
class="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-1 focus-visible:ring-offset-surface-0 disabled:cursor-not-allowed disabled:opacity-40 bg-accent-solid enabled:hover:bg-accent-solid-hover"
|
||||
role="switch"
|
||||
type="button"
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
class="inline-block h-4 w-4 rounded-full bg-white shadow transition-transform translate-x-[18px]"
|
||||
class="inline-block h-4 w-4 rounded-full bg-white shadow-sm ring-1 ring-black/10 transition-transform duration-200 ease-out translate-x-[18px]"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="flex justify-between gap-4 border-b border-border/60 last:border-b-0 py-3 items-center"
|
||||
class="flex justify-between gap-6 border-b border-border/60 last:border-b-0 py-3 items-center"
|
||||
>
|
||||
<div
|
||||
class="min-w-0"
|
||||
@@ -7101,25 +7101,51 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
Quit AgentHub
|
||||
</p>
|
||||
<p
|
||||
class="mt-0.5 text-xs text-fg-muted"
|
||||
class="mt-0.5 text-xs leading-relaxed text-fg-muted"
|
||||
>
|
||||
Stop the dashboard so nothing runs in the background. Opening Claude Code no longer starts it; run \`agenthub start\` to bring it back.
|
||||
Stop the dashboard so nothing runs in the background. Opening Claude Code no longer starts it; run
|
||||
<code
|
||||
class="whitespace-nowrap rounded border border-border bg-surface-2 px-1 py-px font-mono text-[11px] text-fg-secondary"
|
||||
>
|
||||
agenthub start
|
||||
</code>
|
||||
to bring it back.
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
class="shrink-0"
|
||||
>
|
||||
<button
|
||||
class="btn-ghost text-xs text-status-danger disabled:opacity-40"
|
||||
aria-busy="false"
|
||||
class="btn-secondary min-w-[6.5rem] justify-center text-xs"
|
||||
data-testid="quit-agenthub"
|
||||
type="button"
|
||||
>
|
||||
<svg
|
||||
class="lucide lucide-power h-3.5 w-3.5 shrink-0"
|
||||
fill="none"
|
||||
height="24"
|
||||
stroke="currentColor"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
viewBox="0 0 24 24"
|
||||
width="24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
d="M12 2v10"
|
||||
/>
|
||||
<path
|
||||
d="M18.4 6.6a9 9 0 1 1-12.77.04"
|
||||
/>
|
||||
</svg>
|
||||
Quit
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="flex justify-between gap-4 border-b border-border/60 last:border-b-0 py-3 items-center"
|
||||
class="flex justify-between gap-6 border-b border-border/60 last:border-b-0 py-3 items-center"
|
||||
>
|
||||
<div
|
||||
class="min-w-0"
|
||||
@@ -7130,7 +7156,7 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
Uninstall AgentHub
|
||||
</p>
|
||||
<p
|
||||
class="mt-0.5 text-xs text-fg-muted"
|
||||
class="mt-0.5 text-xs leading-relaxed text-fg-muted"
|
||||
>
|
||||
Remove AgentHub from this computer: the dashboard, its database and settings, its hooks in Claude Code, Codex and Antigravity, and the plugin. Your conversations, workspace folders and repositories are kept.
|
||||
</p>
|
||||
@@ -7139,10 +7165,45 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
class="shrink-0"
|
||||
>
|
||||
<button
|
||||
class="btn-ghost text-xs text-status-danger disabled:opacity-40"
|
||||
aria-busy="false"
|
||||
class="btn-danger min-w-[6.5rem] justify-center text-xs"
|
||||
data-testid="uninstall-agenthub"
|
||||
type="button"
|
||||
>
|
||||
<svg
|
||||
class="lucide lucide-trash2 h-3.5 w-3.5 shrink-0"
|
||||
fill="none"
|
||||
height="24"
|
||||
stroke="currentColor"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
viewBox="0 0 24 24"
|
||||
width="24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
d="M3 6h18"
|
||||
/>
|
||||
<path
|
||||
d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"
|
||||
/>
|
||||
<path
|
||||
d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"
|
||||
/>
|
||||
<line
|
||||
x1="10"
|
||||
x2="10"
|
||||
y1="11"
|
||||
y2="17"
|
||||
/>
|
||||
<line
|
||||
x1="14"
|
||||
x2="14"
|
||||
y1="11"
|
||||
y2="17"
|
||||
/>
|
||||
</svg>
|
||||
Uninstall
|
||||
</button>
|
||||
</div>
|
||||
@@ -7162,7 +7223,7 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
class="mt-2"
|
||||
>
|
||||
<div
|
||||
class="flex justify-between gap-4 border-b border-border/60 last:border-b-0 py-3 items-center"
|
||||
class="flex justify-between gap-6 border-b border-border/60 last:border-b-0 py-3 items-center"
|
||||
>
|
||||
<div
|
||||
class="min-w-0"
|
||||
@@ -7173,12 +7234,12 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
Release
|
||||
</p>
|
||||
<p
|
||||
class="mt-0.5 text-xs text-fg-muted"
|
||||
class="mt-0.5 text-xs leading-relaxed text-fg-muted"
|
||||
>
|
||||
<span
|
||||
class="text-status-warning/90"
|
||||
>
|
||||
UI build v2.8.6 (rebuild client to match)
|
||||
UI build v2.8.11 (rebuild client to match)
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
@@ -7193,7 +7254,7 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="flex justify-between gap-4 border-b border-border/60 last:border-b-0 py-2 items-center"
|
||||
class="flex justify-between gap-6 border-b border-border/60 last:border-b-0 py-2 items-center"
|
||||
>
|
||||
<div
|
||||
class="min-w-0"
|
||||
@@ -7215,7 +7276,7 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="flex justify-between gap-4 border-b border-border/60 last:border-b-0 py-2 items-center"
|
||||
class="flex justify-between gap-6 border-b border-border/60 last:border-b-0 py-2 items-center"
|
||||
>
|
||||
<div
|
||||
class="min-w-0"
|
||||
@@ -7240,7 +7301,7 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="flex justify-between gap-4 border-b border-border/60 last:border-b-0 py-2 items-center"
|
||||
class="flex justify-between gap-6 border-b border-border/60 last:border-b-0 py-2 items-center"
|
||||
>
|
||||
<div
|
||||
class="min-w-0"
|
||||
@@ -7262,7 +7323,7 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="flex justify-between gap-4 border-b border-border/60 last:border-b-0 py-2 items-center"
|
||||
class="flex justify-between gap-6 border-b border-border/60 last:border-b-0 py-2 items-center"
|
||||
>
|
||||
<div
|
||||
class="min-w-0"
|
||||
@@ -7284,7 +7345,7 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="flex justify-between gap-4 border-b border-border/60 last:border-b-0 py-3 items-center"
|
||||
class="flex justify-between gap-6 border-b border-border/60 last:border-b-0 py-3 items-center"
|
||||
>
|
||||
<div
|
||||
class="min-w-0"
|
||||
@@ -7295,7 +7356,7 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
Live connections
|
||||
</p>
|
||||
<p
|
||||
class="mt-0.5 text-xs text-fg-muted"
|
||||
class="mt-0.5 text-xs leading-relaxed text-fg-muted"
|
||||
>
|
||||
Browser tabs and tools receiving live updates
|
||||
</p>
|
||||
@@ -7325,7 +7386,7 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
class="mt-2"
|
||||
>
|
||||
<div
|
||||
class="flex justify-between gap-4 border-b border-border/60 last:border-b-0 py-2 items-center"
|
||||
class="flex justify-between gap-6 border-b border-border/60 last:border-b-0 py-2 items-center"
|
||||
>
|
||||
<div
|
||||
class="min-w-0"
|
||||
@@ -7355,7 +7416,7 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
class="mt-2"
|
||||
>
|
||||
<div
|
||||
class="flex justify-between gap-4 border-b border-border/60 last:border-b-0 py-3 items-center"
|
||||
class="flex justify-between gap-6 border-b border-border/60 last:border-b-0 py-3 items-center"
|
||||
>
|
||||
<div
|
||||
class="min-w-0"
|
||||
@@ -7366,7 +7427,7 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
Database file
|
||||
</p>
|
||||
<p
|
||||
class="mt-0.5 text-xs text-fg-muted"
|
||||
class="mt-0.5 text-xs leading-relaxed text-fg-muted"
|
||||
>
|
||||
<span
|
||||
class="font-mono break-all"
|
||||
@@ -7386,7 +7447,7 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="flex justify-between gap-4 border-b border-border/60 last:border-b-0 py-2 items-center"
|
||||
class="flex justify-between gap-6 border-b border-border/60 last:border-b-0 py-2 items-center"
|
||||
>
|
||||
<div
|
||||
class="min-w-0"
|
||||
@@ -7408,7 +7469,7 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="flex justify-between gap-4 border-b border-border/60 last:border-b-0 py-2 items-center"
|
||||
class="flex justify-between gap-6 border-b border-border/60 last:border-b-0 py-2 items-center"
|
||||
>
|
||||
<div
|
||||
class="min-w-0"
|
||||
@@ -8960,7 +9021,7 @@ exit 0
|
||||
class="mt-2"
|
||||
>
|
||||
<div
|
||||
class="flex justify-between gap-4 border-b border-border/60 last:border-b-0 py-3 items-center"
|
||||
class="flex justify-between gap-6 border-b border-border/60 last:border-b-0 py-3 items-center"
|
||||
>
|
||||
<div
|
||||
class="min-w-0"
|
||||
@@ -8971,7 +9032,7 @@ exit 0
|
||||
Redact secrets before storing
|
||||
</p>
|
||||
<p
|
||||
class="mt-0.5 text-xs text-fg-muted"
|
||||
class="mt-0.5 text-xs leading-relaxed text-fg-muted"
|
||||
>
|
||||
API keys and tokens of known shapes, bearer headers, private keys and password=/TOKEN= values in event payloads and summaries become [redacted]. The transcripts on disk are the CLIs' own files and are not changed.
|
||||
</p>
|
||||
@@ -8982,13 +9043,13 @@ exit 0
|
||||
<button
|
||||
aria-checked="false"
|
||||
aria-label="Redact secrets before storing"
|
||||
class="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-1 focus-visible:ring-offset-surface-0 disabled:cursor-not-allowed disabled:opacity-50 bg-border-light ring-1 ring-inset ring-fg-muted/80"
|
||||
class="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-1 focus-visible:ring-offset-surface-0 disabled:cursor-not-allowed disabled:opacity-40 bg-border-light ring-1 ring-inset ring-fg-muted/80 enabled:hover:ring-fg-secondary"
|
||||
role="switch"
|
||||
type="button"
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
class="inline-block h-4 w-4 rounded-full bg-white shadow transition-transform translate-x-0.5"
|
||||
class="inline-block h-4 w-4 rounded-full bg-white shadow-sm ring-1 ring-black/10 transition-transform duration-200 ease-out translate-x-0.5"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
@@ -9357,6 +9418,108 @@ exit 0
|
||||
</svg>
|
||||
Run Cleanup
|
||||
</button>
|
||||
<div
|
||||
class="border-t border-border pt-4 space-y-3"
|
||||
>
|
||||
<div>
|
||||
<h4
|
||||
class="text-xs font-medium text-fg-secondary"
|
||||
>
|
||||
Automatic cleanup
|
||||
</h4>
|
||||
<p
|
||||
class="text-xs text-fg-muted"
|
||||
>
|
||||
Off by default. When on, the hourly maintenance deletes finished sessions (completed, error, abandoned) that started more than this many days ago — with their events, agents and token usage — a little at a time.
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
class="flex flex-wrap items-end gap-3"
|
||||
>
|
||||
<div
|
||||
class="bg-surface-2 rounded-lg px-4 py-3"
|
||||
>
|
||||
<label
|
||||
class="text-xs text-fg-secondary block mb-2"
|
||||
for="retention-days"
|
||||
>
|
||||
Delete sessions older than
|
||||
</label>
|
||||
<div
|
||||
class="flex items-center gap-2"
|
||||
>
|
||||
<input
|
||||
class="input w-20 text-sm text-right font-mono"
|
||||
id="retention-days"
|
||||
inputmode="numeric"
|
||||
max="3650"
|
||||
min="0"
|
||||
step="1"
|
||||
type="number"
|
||||
value="0"
|
||||
/>
|
||||
<span
|
||||
class="text-xs text-fg-muted"
|
||||
>
|
||||
days
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
class="btn-primary px-4 py-2 text-sm disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
disabled=""
|
||||
type="button"
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
</div>
|
||||
<p
|
||||
class="text-xs text-fg-secondary"
|
||||
>
|
||||
Automatic cleanup is off.
|
||||
</p>
|
||||
<div
|
||||
class="flex flex-wrap items-center gap-3"
|
||||
>
|
||||
<button
|
||||
class="text-xs px-3 py-1.5 rounded-md transition-colors disabled:opacity-50 text-fg-secondary hover:text-fg-primary hover:bg-surface-4 border border-border"
|
||||
type="button"
|
||||
>
|
||||
<svg
|
||||
class="lucide lucide-minimize2 w-3 h-3 inline mr-1"
|
||||
fill="none"
|
||||
height="24"
|
||||
stroke="currentColor"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
viewBox="0 0 24 24"
|
||||
width="24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<polyline
|
||||
points="4 14 10 14 10 20"
|
||||
/>
|
||||
<polyline
|
||||
points="20 10 14 10 14 4"
|
||||
/>
|
||||
<line
|
||||
x1="14"
|
||||
x2="21"
|
||||
y1="10"
|
||||
y2="3"
|
||||
/>
|
||||
<line
|
||||
x1="3"
|
||||
x2="10"
|
||||
y1="21"
|
||||
y2="14"
|
||||
/>
|
||||
</svg>
|
||||
Compact now
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section
|
||||
class="scroll-mt-24"
|
||||
@@ -9637,7 +9800,7 @@ exports[`screen snapshots > Settings — notifications 1`] = `
|
||||
class="min-w-0 flex-1"
|
||||
>
|
||||
<div
|
||||
class="flex justify-between gap-4 border-b border-border/60 last:border-b-0 py-2 items-center"
|
||||
class="flex justify-between gap-6 border-b border-border/60 last:border-b-0 py-2 items-center"
|
||||
>
|
||||
<div
|
||||
class="min-w-0"
|
||||
@@ -9654,13 +9817,13 @@ exports[`screen snapshots > Settings — notifications 1`] = `
|
||||
<button
|
||||
aria-checked="false"
|
||||
aria-label="Enable Browser Notifications"
|
||||
class="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-1 focus-visible:ring-offset-surface-0 disabled:cursor-not-allowed disabled:opacity-50 bg-border-light ring-1 ring-inset ring-fg-muted/80"
|
||||
class="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-1 focus-visible:ring-offset-surface-0 disabled:cursor-not-allowed disabled:opacity-40 bg-border-light ring-1 ring-inset ring-fg-muted/80 enabled:hover:ring-fg-secondary"
|
||||
role="switch"
|
||||
type="button"
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
class="inline-block h-4 w-4 rounded-full bg-white shadow transition-transform translate-x-0.5"
|
||||
class="inline-block h-4 w-4 rounded-full bg-white shadow-sm ring-1 ring-black/10 transition-transform duration-200 ease-out translate-x-0.5"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -362,6 +362,18 @@ vi.mock("../../lib/api", async (importOriginal) => {
|
||||
env_owned: { dir: false, hour: false, keep: false },
|
||||
}),
|
||||
},
|
||||
retention: {
|
||||
get: r({
|
||||
days: 0,
|
||||
max_days: 3650,
|
||||
env_owned: { days: false },
|
||||
last_run: null,
|
||||
space: null,
|
||||
db_size: 0,
|
||||
compacting: false,
|
||||
last_compact: null,
|
||||
}),
|
||||
},
|
||||
exportData: () => "/api/settings/export",
|
||||
cleanup: r({
|
||||
ok: true,
|
||||
|
||||
+17
-4
@@ -89,9 +89,9 @@ In server mode a **developer** sees only rows of the workspaces they own (`lanes
|
||||
|
||||
An admin changes accounts with `POST /api/users` (`{username, password, role}` → `201 {user}`), `GET /api/users/:id` (`{user, workspaces: [{id, title, cwd}]}`, the account with `logins` and `lastLoginAt`, for the Edit form; admin or analyst), `GET /api/users/:id/avatar` (that account's picture for the sidebar's owner groups — admin or analyst, `nosniff` + `sandbox` CSP, `404 ENOAVATAR`; a workspace in `GET /api/lanes` carries `owner_avatar_at` to version its URL), `PATCH /api/users/:id` (any of `{displayName?, email?, role?, disabled?, password?, addWorkspaces?: [laneId], removeWorkspaces?: [laneId], signOut?: true}` — every field validated before any is written; `removeWorkspaces` leaves the workspace with no owner and answers `409 ENOTOWNED` for one the user does not own; an admin's own `password`/`signOut` keeps the login it came from), `POST /api/users/:id/password` (`{password}`; that user's logins end) `POST /api/users/:id/workspaces` (`{laneId}`; the workspace's owner becomes that user) and `DELETE /api/users/:id` (delete for good: the user's logins, panes, workspaces' records, prefs and — under S3 — their Linux account and whole home, removed FIRST so a refusal (`502 EPROVISION`) leaves every row; `409 ESELF` for yourself, `409 ELASTADMIN` for the last admin; session history and the audit log stay). Every one carries `currentPassword`, the admin's own password: `403 EREAUTH` when it is wrong or missing, `429 ETOOMANY` after 10 wrong tries in 15 minutes. `409 ESELF` for an admin's own role or disable, `409 EEXISTS` for a taken name, `400 EBADUSER`/`EBADPASSWORD`/`EBADROLE`/`EBADEMAIL`/`EBADFIELD`, `404 ENOUSER`/`ENOLANE`; a developer or analyst gets `403 EADMIN`, and local mode `403 ELOCALMODE`. No answer carries a password hash; each change is written to the audit log.
|
||||
|
||||
`GET /api/accounts[?force=1]` lists the Claude account pool ([SERVER-MODE.md](SERVER-MODE.md#claude-account-pool)): `{accounts: [{name, addedAt, expiresAt, expired, livePanes, spend5h, spend7d, tokens5h, tokens7d, quota: {fiveHour, sevenDay, checkedAt, error} | null, quotaPercent, full}], codex: [{name, kind: "apikey"|"chatgpt", addedAt, livePanes, spend5h, spend7d, tokens5h, tokens7d, quota: {windows: [{label, usedPercent, resetsAt}], asOf} | null, quotaPercent, full}], blockPercent}` — `codex` is the [Codex account pool](SERVER-MODE.md#codex-account-pool). `spend*`/`tokens*` = the sessions the account's runs held, over the hours they held them (a Codex session counts whole once its run started in the window). It never includes a key or a token. `force=1` re-reads every quota first. Run rows (`/api/run/history`) carry `account`, the pool account their pane ran on (`null` = the machine's own login).
|
||||
`GET /api/accounts[?force=1]` lists the Claude account pool ([SERVER-MODE.md](SERVER-MODE.md#claude-account-pool)): `{accounts: [{name, addedAt, expiresAt, expired, livePanes, spend5h, spend7d, tokens5h, tokens7d, quota: {fiveHour, sevenDay, checkedAt, error} | null, quotaPercent, full}], codex: [{name, kind: "apikey"|"chatgpt", addedAt, livePanes, spend5h, spend7d, tokens5h, tokens7d, quota: {windows: [{label, usedPercent, resetsAt}], asOf} | null, quotaPercent, full}], pins: {claude: [{userId, username, account, pinnedAt}], codex: […]}, blockPercent}` — `pins` are the users an admin pinned to one account (empty in local mode); `codex` is the [Codex account pool](SERVER-MODE.md#codex-account-pool). `spend*`/`tokens*` = the sessions the account's runs held, over the hours they held them (a Codex session counts whole once its run started in the window). It never includes a key or a token. `force=1` re-reads every quota first. Run rows (`/api/run/history`) carry `account`, the pool account their pane ran on (`null` = the machine's own login).
|
||||
|
||||
An admin (server mode) adds an account with `POST /api/accounts` `{tool: "claude"|"codex", name, currentPassword, …}` → `201 {account}`. For Claude the body carries one of: `profile` (a saved switch-user profile, MOVED in: the profile is deleted; the one the host's CLI is logged into moves in with its live login and the host's home becomes one more placement the server refreshes — `409 EACTIVE` only for a macOS Keychain login; `name` defaults to it), `credentials` (the text of a `.credentials.json`; Anthropic is asked whose account it is, `502 EUPSTREAM` when it cannot be reached), or `token` (a `claude setup-token` token). For Codex, `token` is an OpenAI API key or the text of an `auth.json`. `GET /api/accounts/profiles` lists the saved profiles `{profiles: [{name, label, email, subscriptionType, active}]}` (no token). Claude rows in `GET /api/accounts` carry `kind` (`token`|`login`), `email` and `refreshError`; a login's `expiresAt` is null and removes one with `DELETE /api/accounts/:name` `{tool, currentPassword}` → `{ok: true}`. No answer carries the token. `403 EREAUTH` wrong password (`429 ETOOMANY` after 10), `403 EADMIN` for a non-admin, `403 ELOCALMODE` in local mode, `400 EBADTOOL`/`EBADNAME`/`EBADTOKEN`, `409 EEXISTS`, `404 ENOACCOUNT`; each change is audited by account name.
|
||||
An admin (server mode) adds an account with `POST /api/accounts` `{tool: "claude"|"codex", name, currentPassword, …}` → `201 {account}`. For Claude the body carries one of: `profile` (a saved switch-user profile, MOVED in: the profile is deleted; the one the host's CLI is logged into moves in with its live login and the host's home becomes one more placement the server refreshes — `409 EACTIVE` only for a macOS Keychain login; `name` defaults to it), `credentials` (the text of a `.credentials.json`; Anthropic is asked whose account it is, `502 EUPSTREAM` when it cannot be reached), or `token` (a `claude setup-token` token). For Codex, `token` is an OpenAI API key or the text of an `auth.json`. `GET /api/accounts/profiles` lists the saved profiles `{profiles: [{name, label, email, subscriptionType, active}]}` (no token). Claude rows in `GET /api/accounts` carry `kind` (`token`|`login`), `email` and `refreshError`; a login's `expiresAt` is null and removes one with `DELETE /api/accounts/:name` `{tool, currentPassword}` → `{ok: true}`. No answer carries the token. `403 EREAUTH` wrong password (`429 ETOOMANY` after 10), `403 EADMIN` for a non-admin, `403 ELOCALMODE` in local mode, `400 EBADTOOL`/`EBADNAME`/`EBADTOKEN`, `409 EEXISTS`, `404 ENOACCOUNT`; each change is audited by account name. `PUT /api/accounts/pins` `{tool, userId, account, currentPassword}` → `{pin: {userId, username, account}}` switches that user's sessions of `tool` to one pool account (`account: null` = automatic again; `404 ENOUSER`/`ENOACCOUNT`); `switched` says what happened now — `switched` (a Claude login was written into their home: running panes take it at their next credentials read, no restart), `kept`, `own-login` (their own login, left alone), `expired`, `next-session` (a token, Codex, or no member home), with the same password step-up and audit (the user as `owner_id`). `PUT /api/accounts/:name/users` `{tool, userIds, currentPassword}` → `{added: [{userId, username, switched}], removed: [{userId, username}]}` is the Users page's Edit of one account: exactly those users run on it afterwards (a user on another account moves here, one left out goes back to the balancer; one transaction, each change audited; `400 EBADUSER`, `404 ENOUSER`/`ENOACCOUNT`). Removing an account drops its pins; deleting a user drops theirs.
|
||||
|
||||
**The account's own preferences and first-run setup** (`server/routes/me.js`; local mode is the one account `local`, server mode one row per account in `user_prefs`):
|
||||
|
||||
@@ -1006,6 +1006,9 @@ cannot collide on `index.lock`.
|
||||
the file resolves by removing it. `merge-commit` is `409 ECONFLICTS` while
|
||||
anything is unmerged, and it and `merge-abort` are `409 ENOMERGE` with no
|
||||
merge in progress. `merge-abort` needs `confirm: true` (`400 ECONFIRM`).
|
||||
- Any action on a host with no `git` binary (or none on the dashboard's PATH)
|
||||
is `503 EGITMISSING`: a missing dependency, not a bad request; the message
|
||||
carries the install command (like `ETMUXMISSING` for tmux).
|
||||
- `push` pushes `HEAD`, never a branch name from the request, so a workspace can
|
||||
only push the branch it is on.
|
||||
- A **path** in the body is never trusted as a path: `stage`, `unstage` and
|
||||
@@ -1595,7 +1598,7 @@ What a workspace's home page edits (`server/lib/lane-sources.js`, `server/routes
|
||||
- **Memory** — read-only: the folder's `CLAUDE.md`, `.claude/CLAUDE.md`, `CLAUDE.local.md`, `AGENTS.md`, and for a Claude workspace `<CLAUDE_HOME>/projects/<encoded cwd>/memory/*.md` — `{files: [{label, path, size, mtime, truncated, content}]}`, each at most 256 KB of content.
|
||||
- Every write is same-origin only (`403 EBADORIGIN`); an unknown workspace is `404 ENOLANE`, an unknown source `404 ENOSOURCE`.
|
||||
|
||||
At spawn (`spawnRun`, both `POST /api/lanes/:id/start` and `POST /api/run`) the pane gets, from these rows: Claude — `--add-dir <folders…> [<context dir>]` first, then `--append-system-prompt-file=<data dir>/workspace-prompts/<lane id>.md`, a file rewritten at every spawn holding the workspace owner's own instructions (`PUT /api/me/instructions`) + the workspace's instructions + the context file list + the extra folders; Codex — one `--add-dir <dir>` per folder (and the context dir) and `-c developer_instructions=<same text as a TOML string>` (above 6 KB as the escaped TOML string, one line pointing at that file instead; nothing when that file could not be written). Any other tool gets none of it (`supported: false`). A folder or file that vanished is skipped.
|
||||
At spawn (`spawnRun`, both `POST /api/lanes/:id/start` and `POST /api/run`) the pane gets, from these rows: Claude — `--add-dir <folders…> [<context dir>]` first, then that workspace's instructions folder `<data dir>/workspace-prompts/<lane id>/` (a member's: `prompt-<lane id>/` in their handoff dir) as one more `--add-dir`, with `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1` in the pane's env so Claude reads the `CLAUDE.md` there as memory — never `--append-system-prompt-file`: Claude cannot carry a custom system prompt over a restart and refused `/tui` in such a pane. That `CLAUDE.md` is rewritten at every spawn and holds the workspace owner's own instructions (`PUT /api/me/instructions`) + the workspace's instructions + the context file list + the extra folders; Codex — one `--add-dir <dir>` per folder (and the context dir) and `-c developer_instructions=<same text as a TOML string>` (above 6 KB as the escaped TOML string, one line pointing at that file instead; nothing when that file could not be written). Any other tool gets none of it (`supported: false`). A folder or file that vanished is skipped.
|
||||
|
||||
#### Projects (workspaces grouped by repository)
|
||||
|
||||
@@ -2954,7 +2957,7 @@ POST /api/pets/featured/:id Download a FEATURED pet from codex-pets.ne
|
||||
DELETE /api/pets/:id Delete a pet (its folder under the data dir)
|
||||
```
|
||||
|
||||
The mascot (Sagi) can wear a pet: right-click it for **Hide pet**, **Size** (48–250 px), **Choose pet** (Sagi, the featured pets, your own — deletable), **Upload your own…**, **Import .codex-pet bundle…**, **Find more on codex-pets.net** and **Pet settings…**, which opens the pet block of **Settings → Appearance** (`/settings/appearance#pet`, `client/src/components/settings/PetSettings.tsx`; the old `/settings/pet` redirects there): show/hide, speech bubbles, size with a live preview, and the same choose / download / upload / import / delete as a grid. The menu and the page share `components/Sagi/usePets.ts`. Which pet is worn (with its display name, which the mascot goes by) and its size are viewer preferences in `localStorage` (`agenthub.pet`, `agenthub.pet.size`); a name the user types by clicking it in the mascot's panel is `agenthub.pet.names` (`{ [petId]: name }`, empty = the pet's own); the pets live on the server, one folder each under `<data dir>/pets/<id>/` with a `meta.json` AgentHub writes.
|
||||
The mascot (Sagi) can wear a pet: right-click it for **Hide pet**, **Size** (48–250 px), **Choose pet** (Sagi, the featured pets, your own — deletable), **Upload your own…**, **Import .codex-pet bundle…**, **Find more on codex-pets.net** and **Pet settings…**, which opens the pet block of **Settings → Appearance** (`/settings/appearance#pet`, `client/src/components/settings/PetSettings.tsx`; the old `/settings/pet` redirects there): show/hide, speech bubbles, size with a live preview, and the same choose / download / upload / import / delete as a grid. The menu and the page share `components/Sagi/usePets.ts`. Which pet is worn (with its display name, which the mascot goes by) and its size are viewer preferences in `localStorage` (`agenthub.pet`, `agenthub.pet.size`); a name the user types by clicking it in the mascot's chat window header is `agenthub.pet.names` (`{ [petId]: name }`, empty = the pet's own); the pets live on the server, one folder each under `<data dir>/pets/<id>/` with a `meta.json` AgentHub writes.
|
||||
|
||||
A **Codex pet** is the `.codex-pet.zip` format Codex Desktop uses (the bundles shared on codex-pets.net and in `mileson/codex-pets`): `pet.json` (`id`, `displayName`, `description`, `spritesheetPath`) and `spritesheet.webp`, a 1536×1872 atlas of 8 columns × 9 rows of 192×208 frames — idle, run right, run left, waving, jumping, failed, waiting, running, review, with 6/8/8/4/5/8/6/6/6 frames — or a v2 atlas (`spriteVersionNumber: 2`, 1536×2288, 11 rows) whose rows 9–10 add 16 gaze poses, 22.5° apart clockwise from straight up. The mascot plays the row of its mood (an agent working → running, waiting for you → waiting, an error → failed, a finished turn → jumping, a live session at rest → review, idle/asleep → idle), and on an event it plays a moment over the mood (a new session → waving, a finish or a pat → jumping, a new subagent → review, a session waiting on you → waiting, an error → failed); dragged it runs left or right with the drag (and along the glide to its edge), hovered it waves, and a v2 pet at idle turns toward the pointer (back to idle 2 s after the pointer rests). Frames play at Codex's own timings (`codex-rs/tui/src/pets/model.rs`: e.g. running 120 ms a frame, its last 220 ms); idle plays at the drawn pace (280/110/110/140/140/320 ms), a sleeping pet at Codex's 6× slower one. Waving, jumping, failed and review are moments — they play three times and settle into idle; running, waiting and the run rows loop. Only the two files are read, at the archive root or one folder deep; an entry's size is checked from the zip's directory before it is inflated; the sheet must be a WebP of exactly one of those sizes (`400 EBADPET` otherwise). An uploaded image is shown still and bobs; SVG is refused because an SVG served from the dashboard's origin runs script.
|
||||
|
||||
@@ -3057,6 +3060,16 @@ POST /api/settings/backup/run 202 — started (or already running); poll GE
|
||||
Settings → Data → **Daily backup** (`server/lib/db-backup.js`). Once a day, at `hour` (0–23, the server's local time, default 2), the database is copied to `dir` as `agenthub-YYYYMMDD-HHMMSS.db`: `VACUUM INTO` on a read-only connection in a worker thread, so the copy is a consistent snapshot (writes from another dashboard on the same database never restart it), compacted, and the event loop keeps serving while it runs (≈30 s for a 1.25 GB database). It is written as `<name>.partial` and renamed when complete. Beyond `keep` (1–365, default 7) the oldest are deleted — only regular files matching that exact name; nothing else in the folder, and no symlink, is ever touched. A day missed while the server was down runs at the next start; a failed run is retried the next day or by **Back up now**, never every minute. The three values persist to the settings file as `AGENTHUB_BACKUP_DIR` / `AGENTHUB_BACKUP_HOUR` / `AGENTHUB_BACKUP_KEEP`; one the environment set is `env_owned` (`409 EENVOWNED`). Writes are same-origin, and admin-only in server mode. `400 INVALID_PATH` for a relative, missing, non-directory or unwritable folder, `400 INVALID_INPUT` for an hour or count out of range, `400 ENOBACKUPDIR` for a run with no folder. The scheduler beat is `DASHBOARD_BACKUP_TICK_MS` (default 60000, `0` = off).
|
||||
|
||||
Restoring is manual, on purpose: `agenthub stop`, delete `dashboard.db-wal` and `dashboard.db-shm`, copy a backup over `dashboard.db` (its path is on Settings → System), `agenthub start`.
|
||||
|
||||
### Retention and Compact
|
||||
|
||||
```
|
||||
GET /api/settings/retention { days, max_days, env_owned: { days }, last_run, space: { auto_vacuum, page_size, page_count, freelist_pages, free_bytes }, db_size, compacting, last_compact }
|
||||
PUT /api/settings/retention { days } → the same state; 0 turns it off (the default)
|
||||
POST /api/settings/compact { confirm: true } → 202 — started (or already running); poll GET while `compacting`
|
||||
```
|
||||
|
||||
Settings → Data → **Session cleanup** (`server/lib/db-retention.js`). Automatic retention is OFF unless `days` (1–3650, `AGENTHUB_RETENTION_DAYS` in the settings file) is set; nothing is deleted by default. When set, the hourly maintenance (`DASHBOARD_DB_MAINTAIN_MS`) purges finished (completed/error/abandoned) sessions that started more than `days` ago — the same rule and the same deletion (`purgeSessionIds`: events, agents, token usage, the session) as `POST /api/settings/cleanup` with `purge_days` — 25 sessions per transaction with a yield between, at most 5000 per run. A new database is created with `auto_vacuum = INCREMENTAL`, an existing one up to 32 MB is converted by a VACUUM at startup; the same hourly run then returns free pages to the OS (`incremental_vacuum`, in 1024-page slices, at most 65536 pages per run) once more than 1024 are free. A larger, older database is converted only by **Compact**: a full VACUUM in a worker thread followed by a TRUNCATE checkpoint — it holds the write lock while it runs (tens of seconds on a GB-size file), so hooks wait meanwhile; it runs only on a click. In server mode both writes are an admin's (`/settings` is in `ADMIN_WRITE_PREFIXES`).
|
||||
---
|
||||
|
||||
## WebSocket API
|
||||
|
||||
+1
-1
@@ -108,7 +108,7 @@ The CLI talks to the local dashboard server — **API-backed commands require it
|
||||
| `agenthub server install-system [--dry-run\|--uninstall]` | **One Linux user per account** (S3). Run as the account that runs the dashboard, never as root: it runs `scripts/server/install-system.sh` through one `sudo`. That script creates the groups, `/srv/agenthub/users`, `/opt/agenthub`, the sudoers file, the member hooks and `hidepid`, and installs the system unit `agenthub.service`. The command then points the unit at this install, writes `AGENTHUB_USERS_ROOT`, and moves the dashboard from the `systemd --user` unit to the system one (panes stay). `--dry-run` prints the sudo command; `--uninstall` goes back to the user unit. See [SERVER-MODE.md](SERVER-MODE.md#one-linux-user-per-account) |
|
||||
| `agenthub server tools` | One Linux user per account: publish this install's scripts and every installed AI tool under `/opt/agenthub` (`tools/bin/<command>`), where every account's pane runs them. The server also does this at start and after each install or update. Prints each tool's shared copy, or why it could not be shared |
|
||||
| `agenthub server off` / `agenthub server status` | Back to local mode (accounts kept) / show the mode and account count |
|
||||
| `agenthub accounts list\|add <name>\|remove <name>` | The **Claude account pool**: new Claude sessions spread over these accounts (each a `claude setup-token` token, typed hidden or read from stdin). `list` shows live panes, $ and tokens in the last 5 h / 7 d, and quota. With `--tool codex` the same for the **Codex account pool**: `add <name> --tool codex --api-key` (key typed hidden or on stdin) or `--from <dir>` (a `codex login` home or its `auth.json`). See [SERVER-MODE.md](SERVER-MODE.md#claude-account-pool) |
|
||||
| `agenthub accounts list\|add <name>\|remove <name>` | The **Claude account pool**: new Claude sessions spread over these accounts (each a `claude setup-token` token, typed hidden or read from stdin). `list` shows live panes, $ and tokens in the last 5 h / 7 d, and quota. With `--tool codex` the same for the **Codex account pool**: `add <name> --tool codex --api-key` (key typed hidden or on stdin) or `--from <dir>` (a `codex login` home or its `auth.json`). `pin <account> <user>` / `unpin <user>` (add `--tool codex` for Codex) switches one user's sessions to that account (a Claude login goes into their home at once, running sessions follow without a restart) (server mode; `list` shows a `pinned` column). See [SERVER-MODE.md](SERVER-MODE.md#claude-account-pool) |
|
||||
| `agenthub users list\|add <name> [--role admin\|analyst\|member]\|passwd <name>\|role <name> <role>\|disable <name>\|enable <name>\|provision <name>\|--all\|assign <workspace id> <name>\|audit [--limit N]` | Server mode's accounts, written straight to the database. Once `install-system` ran, `add` first creates the Linux user `ah-<name>`; a name must then be lower case: a letter, then up to 28 letters, digits, `_` or `-`. `disable`/`enable` lock or unlock that Linux user too, and `provision` gives users made earlier their Linux user (idempotent); `assign` gives a workspace made before server mode an owner; `audit` lists admin/analyst reads of members' sessions. Inside a dashboard pane in server mode, every command acts as the workspace's owner through the pane's `AGENTHUB_PANE_TOKEN`. A password is typed hidden twice, or read from the first line of stdin |
|
||||
|
||||
### Interactive REPL
|
||||
|
||||
+2
-1
@@ -621,6 +621,7 @@ Server mode's accounts ([SERVER-MODE.md](SERVER-MODE.md), `server/lib/auth.js`).
|
||||
| --- | --- |
|
||||
| `users` | `id`, `username` (unique, case-insensitive), `role` (`admin`\|`analyst`\|`member`), `password_hash` (`scrypt$<salt>$<hash>`), `disabled`, `created_at` |
|
||||
| `auth_sessions` | `token_hash` (SHA-256 of the cookie token, PK), `user_id` → `users.id` (cascade), `created_at`, `expires_at` (30 days) |
|
||||
| `account_pins` | `user_id` → `users.id` (cascade), `tool` (`claude`\|`codex`), `account` (a pool account's name), `pinned_at`; PK (`user_id`, `tool`) — an admin's pin of a user to one pool account (`server/lib/account-pins.js`) |
|
||||
|
||||
`dashboard_runs.account` names the Claude pool account a run's pane was started on (`server/lib/claude-pool.js`; `NULL` = the machine's own login). The balancer sums each account's spend from the `token_usage_hourly` rows of those runs' sessions. The pool's tokens live in files under `<CLAUDE_HOME>/agenthub-accounts/`, never in the database.
|
||||
|
||||
@@ -915,7 +916,7 @@ worker's own writable connection. SQLite's automatic checkpoint runs inside whic
|
||||
per commit under load. A failed checkpoint switches the automatic one back on. A second
|
||||
process on the same file (another dashboard, the CLI) keeps its own setting.
|
||||
|
||||
**Upkeep.** `maintainDatabase()` (exported by `server/db.js`) runs hourly from `server/index.js` (`DASHBOARD_DB_MAINTAIN_MS`, `0` = off): a `wal_checkpoint(PASSIVE)` — it never waits on a reader, such as the other dashboard — after which the next write shrinks the WAL to `journal_size_limit`, and `PRAGMA optimize`. Nothing runs `VACUUM`: it rewrites the whole file under an exclusive lock, so space freed by a cleanup is reused for new rows instead of returned to the disk.
|
||||
**Upkeep.** `maintainDatabase()` (exported by `server/db.js`) runs hourly from `server/index.js` (`DASHBOARD_DB_MAINTAIN_MS`, `0` = off): a `wal_checkpoint(PASSIVE)` — it never waits on a reader, such as the other dashboard — after which the next write shrinks the WAL to `journal_size_limit`, and `PRAGMA optimize`. Then `runScheduledMaintenance` (`server/lib/db-retention.js`) applies the OPT-IN retention (`AGENTHUB_RETENTION_DAYS`, off by default: finished sessions older than N days, purged 25 per transaction like the manual cleanup) and, when the database is in `auto_vacuum = INCREMENTAL` and more than 1024 pages are free, a bounded `incremental_vacuum` (1024-page slices, ≤ 65536 pages per run) that returns them to the disk. A new database is created INCREMENTAL; an existing one up to 32 MB is converted by one `VACUUM` at startup (`convertAutoVacuum`), a larger one only by Settings → Data → **Compact** (`POST /api/settings/compact`: a full `VACUUM` in a worker thread, write lock held while it runs). No automatic path runs a full `VACUUM` on a large file. See docs/API.md § Retention and Compact.
|
||||
|
||||
**Growth.** `events.data` is the hook payload TRIMMED by `trim_event_data(?)` (`server/lib/event-payload.js`, a SQL function registered on the connection in `server/db.js`, used by every event `INSERT` and by the duplicate guard): Edit/MultiEdit/NotebookEdit/Write drop `tool_response.originalFile`/`oldString`/`newString` (Write also `content`), Read drops `tool_response.file.content`/`base64`, and any string inside `tool_input`/`tool_response` over 8 KB keeps its first 6 KB and last 2 KB; `structuredPatch` and every field outside those two are kept, and `_trimmed` lists what was dropped. The full text stays in the session transcript and AgentHub's snapshot of it under `<data dir>/transcripts/`, which the Conversation tab reads. Rows stored before this are trimmed once in the background (`sweepEventPayloads`, 200 rows per transaction, `user_version` 4 after marker 3); measured on a 1.2 GB install it took `events.data` from 913 MB to ~400 MB. Freed pages are reused, not returned to the disk (no `VACUUM`). No ROW is pruned automatically. The only deletions are the user's: Settings → clear data / cleanup, a workspace's purge, `scripts/clear-data.js`. Clear data runs in ONE transaction (foreign keys off around it, so workflows are deleted explicitly), cleanup deletes in 500-id chunks inside one transaction. `GET /api/settings/export` streams `events` in keyset pages of 500 instead of loading the table.
|
||||
|
||||
|
||||
+2
-2
@@ -256,9 +256,9 @@ DASHBOARD_DB_PATH=/var/lib/agenthub/dashboard.db
|
||||
DASHBOARD_WORKFLOW_POLL_MS=12000 # Workflow-tool run journals
|
||||
DASHBOARD_CODEX_POLL_MS=15000 # Codex rollout journals → codex lane running/idle + Codex sessions/tokens
|
||||
CODEX_HOME= # where Codex keeps sessions/ (default ~/.codex)
|
||||
DASHBOARD_ANTIGRAVITY_POLL_MS=15000 # agy conversation files → Antigravity sessions/tokens
|
||||
DASHBOARD_ANTIGRAVITY_POLL_MS=15000 # agy conversation files → Antigravity sessions/tokens (60 s while idle)
|
||||
AGENTHUB_GEMINI_DIR= # where agy keeps its data (default ~/.gemini)
|
||||
DASHBOARD_CURSOR_POLL_MS=15000 # Cursor agent transcripts → Cursor sessions (no tokens)
|
||||
DASHBOARD_CURSOR_POLL_MS=15000 # Cursor agent transcripts → Cursor sessions (no tokens; 60 s while idle)
|
||||
AGENTHUB_CURSOR_DIR= # where Cursor keeps its data (default ~/.cursor)
|
||||
AGENTHUB_AGY_USAGE= # 0 never runs `agy --print /usage` for the Usage panel's Antigravity quota (default on; running agy may update it)
|
||||
|
||||
|
||||
+3
-1
@@ -491,7 +491,8 @@ graph TB
|
||||
> entry whose PID is no longer alive** and POSTs the hook payload to one
|
||||
> port per **unique SQLite data directory** (lowest port wins when two
|
||||
> instances share `~/.claude/agenthub`). The other instance re-broadcasts
|
||||
> the workspaces those hooks moved within `DASHBOARD_LANE_SYNC_MS` (2 s), so its
|
||||
> the workspaces those hooks moved within `DASHBOARD_LANE_SYNC_MS` (2 s; a server
|
||||
> alone on its data dir only looks for such a peer every 30 s), so its
|
||||
> browsers see a workspace's status without a refresh.
|
||||
> 3. If neither yields a target, the handler falls back to `4820`.
|
||||
>
|
||||
@@ -589,6 +590,7 @@ Claude Code waits only for the handler process: Node start-up, reading stdin, se
|
||||
|
||||
- **Fire-and-forget POST** — no wait for the dashboard's reply.
|
||||
- **Incremental transcript reads** — `TranscriptCache` reads only the bytes appended since the last hook.
|
||||
- **Only new transcript entries are written** — a per-transcript mark (`transcriptMarks` in `server/routes/hooks.js`, set once the hook's transaction commits) skips the token, compaction, API-error and turn-duration writes when the transcript did not change, and walks only the entries after the last one handled when it grew.
|
||||
- **One POST per database, not per server** — servers sharing a database get each event once (`resolveHookIngestPorts`).
|
||||
- **Heavy reads off the event loop** — aggregates run in a worker (`server/lib/read-pool.js`), so a slow page never delays ingest.
|
||||
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
+1
-1
@@ -115,7 +115,7 @@ Internal build — all rights reserved.
|
||||
|
||||
| Need | Version | Required for |
|
||||
|---|---|---|
|
||||
| **Node.js** | >= 20 (>= 22.5 for a plugin install) | Everything. Both suites are verified green on **24** and **26** |
|
||||
| **Node.js** | >= 22.5 (`node:sqlite`; Node 20 is end-of-life) | Everything. Both suites are verified green on **24** and **26** |
|
||||
| **npm** | 9+ | Ships with Node |
|
||||
| **git** | any | Cloning, and every workspace operation (worktrees, branch/status reads) |
|
||||
| **tmux** | 3.x | The browser run console, `agenthub workspace shell`, typing `/reload-plugins` into a live pane |
|
||||
|
||||
+1
-1
@@ -81,7 +81,7 @@ Internal build — all rights reserved.
|
||||
|
||||
| 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** |
|
||||
| **Node.js** | >= 22.5 (`node:sqlite`; Node 20 đã hết hạn hỗ trợ) | 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 workspace (worktree, đọc branch/status) |
|
||||
| **tmux** | 3.x | Run console trên trình duyệt, `agenthub workspace shell`, gõ `/reload-plugins` vào pane đang sống |
|
||||
|
||||
+21
-10
@@ -61,13 +61,13 @@ claude --plugin-dir plugins/agenthub-analytics
|
||||
## Prerequisites
|
||||
|
||||
- [Claude Code](https://docs.anthropic.com/en/docs/claude-code) installed and authenticated
|
||||
- Node **>= 22.5** when installing via the `agenthub` plugin. A plugin install has no
|
||||
native `better-sqlite3`, so the server stores data through `node:sqlite`, which
|
||||
landed in 22.5. The bootstrap refuses with one line on anything older instead
|
||||
of letting the server crash. (A checkout install still works on Node >= 20.)
|
||||
- Node **>= 22.5**. A plugin install has no native `better-sqlite3`, so the
|
||||
server stores data through `node:sqlite`, which landed in 22.5. The bootstrap
|
||||
refuses on anything older instead of letting the server crash, and says so in
|
||||
the session (below). A checkout needs the same (`engines` in `package.json`).
|
||||
- The Agent Monitor dashboard reachable at `http://localhost:4820` — the `agenthub`
|
||||
plugin starts it for you; a checkout starts it with `npm start` (see
|
||||
[SETUP.md](../SETUP.md))
|
||||
[INSTALL.md](../INSTALL.md))
|
||||
|
||||
Skills and commands are invoked as `/agenthub-<plugin>:<name>`. Agents are dispatched automatically by Claude Code (or named explicitly).
|
||||
|
||||
@@ -124,12 +124,12 @@ waits on an install:
|
||||
|
||||
1. **Fast path** — recorded state matches this plugin build and a server is live → exit. "Live" means a discovery entry whose pid answers AND whose `startedAt` is after this boot (60 s margin): an entry left over from before a reboot names a pid the OS may have handed to an unrelated process, and without systemd (macOS) nothing else clears it.
|
||||
2. **Superseded check** — if Claude Code records a DIFFERENT build of this plugin as installed, this one logs a line and does nothing else (see [A retired build never acts](#a-retired-build-never-acts)).
|
||||
3. **Node gate** — refuse below 22.5 with one line (see Prerequisites).
|
||||
3. **Node gate** — refuse below 22.5 with one line (see Prerequisites). Also checked by the foreground pass itself (it costs nothing), which then spawns no worker and tells the session at once.
|
||||
4. **Lock** — atomic `mkdir` lock holding the PID; reclaimed when the owner is dead or the lock is older than 10 minutes, so two sessions cannot race the install or spawn two servers.
|
||||
5. **Install** — `npm install --omit=dev --ignore-scripts` into the runtime dir, run as the npm bundled with the node running the bootstrap (`npmCommand`: its `npm-cli.js` beside `process.execPath`, no shell, that node's directory first on PATH; `npm` on PATH only when that node ships none) — the update chain runs with the dashboard server's environment, whose PATH need not reach `npm.cmd` on Windows. The UI build below and the doctor's npm row use the same npm (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. **Install** — only when the dependencies changed (`depsHash` covers what npm installs — the dependency lists and the lockfile's package tree — never the release's own `version`, so a plain version bump reinstalls nothing): `npm install --omit=dev --ignore-scripts` into the runtime dir, output in `runtime/npm-install.log`, run as the npm bundled with the node running the bootstrap (`npmCommand`: its `npm-cli.js` beside `process.execPath`, no shell, that node's directory first on PATH; `npm` on PATH only when that node ships none) — the update chain runs with the dashboard server's environment, whose PATH need not reach `npm.cmd` on Windows. The UI build below and the doctor's npm row use the same npm (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.
|
||||
6. **Legacy hook cleanup** — see above.
|
||||
7. **CLI** — write the `~/.local/bin/agenthub` launcher, never clobbering a `agenthub` the bootstrap did not write. It pins the node that ran the bootstrap and falls back to `node` on `PATH` when that binary is gone (a Homebrew Cellar or nvm path deleted by an upgrade).
|
||||
8. **UI build** — `client/` is copied into the runtime dir and built there (`npm ci --include=dev --ignore-scripts`, falling back to `npm install` with the same flags, then `tsc -b` and `vite build` run by the bootstrap's own `node` — the client's `build` script without `npm run`), landing in `runtime/client-dist` — the same directory the server serves from. Nothing in it looks `node` up on PATH: on Windows an install script or a `.bin/*.cmd` shim runs through cmd.exe, and the server's PATH may have no `node` (esbuild's postinstall failed there with "'node' is not recognized" and the update kept the old UI); esbuild, the only dependency with an install script, finds its binary without it. `--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. **UI build** — `client/` is copied into the runtime dir and built there (`npm ci --include=dev --ignore-scripts`, falling back to `npm install` with the same flags — skipped while `client/package.json` and its lockfile are unchanged, because the installed tree in `runtime/client-src/node_modules` is kept with a `.agenthub-deps` stamp; a failed build drops the stamp so the next one installs from clean — then `vite build` run by the bootstrap's own `node`: the vite half of the client's `build` script without `npm run`. The `tsc -b` half is the release's job, not every user's: it emits nothing the bundle needs and cost ~25 s and ~900 MB per update), landing in `runtime/client-dist` — the same directory the server serves from. Nothing in it looks `node` up on PATH: on Windows an install script or a `.bin/*.cmd` shim runs through cmd.exe, and the server's PATH may have no `node` (esbuild's postinstall failed there with "'node' is not recognized" and the update kept the old UI); esbuild, the only dependency with an install script, finds its binary without it. `--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 (`clientBuild` in `state.json`, recorded only after a build that did not fail, so the next session retries a failed one); 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.
|
||||
9. **Server** — when the user has turned **Start AgentHub automatically** on
|
||||
(Settings → System; OFF by default), install/refresh the
|
||||
`agenthub.service` unit on Linux — on macOS with a GUI login, the
|
||||
@@ -149,10 +149,21 @@ waits on an install:
|
||||
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)
|
||||
work the moment `claude` starts, with no manual `/agenthub-open` step. Progress
|
||||
goes to `~/.claude/agenthub/runtime/bootstrap.log`; the UI build's own
|
||||
output goes to `client-build.log` next to it; the server's own output goes to
|
||||
goes to `~/.claude/agenthub/runtime/bootstrap.log`; npm's own output goes to
|
||||
`npm-install.log` and the UI build's to `client-build.log` next to it; the server's own output goes to
|
||||
`server.log`.
|
||||
|
||||
**A failure is reported once, in the session.** The worker's output is
|
||||
discarded, so a Node that is too old, a failed npm install or a failed UI build
|
||||
is recorded in `runtime/last-failure.json` (kind, message, log file). The NEXT
|
||||
foreground pass — its stdout is what Claude Code reads — prints it as a
|
||||
SessionStart `{"systemMessage": "AgentHub: … — details in <log>. Run
|
||||
/agenthub-doctor …"}` and marks it reported, so the same failure is not repeated
|
||||
every session; a different failure is reported again, and a bootstrap that
|
||||
succeeds removes the file. The steady state prints nothing, and the report is a
|
||||
single small read (plus one write, only when there is something to show) — the
|
||||
fast path still spawns nothing.
|
||||
|
||||
### A retired build never acts
|
||||
|
||||
`claude plugin update` unpacks the new version into a **new** cache directory
|
||||
|
||||
+6
-7
@@ -9,8 +9,7 @@ Comprehensive documentation for the Agent Dashboard project.
|
||||
- [Architecture Overview](../ARCHITECTURE.md) - System design and technical reference
|
||||
- [I18N Architecture](./I18N.md) - Internationalization architecture and usage guide
|
||||
- [CLI Reference](./CLI.md) - The `agenthub` terminal CLI: every command, discovery, safety model
|
||||
- [Setup Guide](../SETUP.md) - Installation and configuration
|
||||
- [Installation](../INSTALL.md) - Detailed installation instructions
|
||||
- [Installation & setup](../INSTALL.md) - Installation, configuration and troubleshooting
|
||||
|
||||
---
|
||||
|
||||
@@ -20,7 +19,7 @@ Comprehensive documentation for the Agent Dashboard project.
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
Start[Start Here] --> Setup[SETUP.md<br/>Installation & Config]
|
||||
Start[Start Here] --> Setup[INSTALL.md<br/>Installation & Config]
|
||||
Start --> Architecture[ARCHITECTURE.md<br/>System Design]
|
||||
|
||||
Setup --> Client[Client README<br/>React UI docs]
|
||||
@@ -62,7 +61,7 @@ graph TB
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[New to Project] --> B[Read SETUP.md]
|
||||
A[New to Project] --> B[Read INSTALL.md]
|
||||
B --> C[Install Dependencies]
|
||||
C --> D[Run npm run dev]
|
||||
D --> E[Open localhost:5173]
|
||||
@@ -75,7 +74,7 @@ graph LR
|
||||
|
||||
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)
|
||||
2. Read the rest of [INSTALL.md](../INSTALL.md)
|
||||
3. Run `npm run setup`
|
||||
4. Run `npm run dev`
|
||||
5. Open browser to `http://localhost:5173`
|
||||
@@ -287,7 +286,7 @@ graph LR
|
||||
**Documentation:**
|
||||
- [Hook System Guide](./HOOKS.md)
|
||||
- [Hook Processing](../server/README.md#hook-processing)
|
||||
- [Installation](../SETUP.md#install-hooks)
|
||||
- [Installation](../INSTALL.md#hook-auto-installation)
|
||||
|
||||
---
|
||||
|
||||
@@ -441,4 +440,4 @@ This documentation covers:
|
||||
- ✅ **Internationalization** - Language resources, switching flow, locale formatting, rollout checklist
|
||||
- ✅ **Development guides** - Setup, testing, contributing
|
||||
|
||||
**Start with:** [SETUP.md](../SETUP.md) for installation, then explore specific areas based on your role.
|
||||
**Start with:** [INSTALL.md](../INSTALL.md) for installation, then explore specific areas based on your role.
|
||||
|
||||
+25
-1
@@ -355,6 +355,7 @@ claude setup-token
|
||||
agenthub accounts add team-1
|
||||
agenthub accounts list # live panes, $ and tokens in the last 5 h / 7 d, quota, state
|
||||
agenthub accounts remove team-1
|
||||
agenthub accounts pin team-1 mia # switch mia to team-1 (unpin mia = automatic again)
|
||||
```
|
||||
|
||||
In server mode an admin can do the same on the **Users** page, in the
|
||||
@@ -423,6 +424,28 @@ How a new session picks its account (`server/lib/claude-pool.js`):
|
||||
pane still needs that member's own `/login`.
|
||||
- A token more than a year old is skipped.
|
||||
- A resumed session picks an account again, like a new one.
|
||||
- **Switching a user to one account.** An admin can take one user off the
|
||||
ranking: the pencil (**Edit**) on that account's row in the Account pool
|
||||
card — tick the users who run on it, untick to send one back to automatic (or
|
||||
`agenthub accounts pin <account> <user> [--tool codex]`, `unpin <user>`; their
|
||||
own password again, each change audited). A user ticked on one account
|
||||
moves off any other. Every session in a
|
||||
workspace that user OWNS then runs on that account, even when it is full;
|
||||
other users are not affected, and the account is not reserved for them.
|
||||
- **A Claude login switches at once, without a restart.** The server first
|
||||
copies every home's newer pair back into the pool (so the login leaving
|
||||
the home keeps its only live refresh token), then writes the new login
|
||||
into the user's `~/.claude/.credentials.json` as them. New sessions start
|
||||
on it; sessions already running keep their process and move to it the
|
||||
next time Claude Code re-reads its credentials (it does so before it
|
||||
refreshes its access token, so at the latest when that token expires).
|
||||
A login the user made themselves (`/login`) is never written over — the
|
||||
card says so. Their sessions are booked to the account they started on.
|
||||
- A setup-token, a Codex account, or a host pane gets the account at its
|
||||
next spawn; running ones keep theirs.
|
||||
- An expired account falls back to the ranking. Removing the account drops
|
||||
the switch; deleting the user drops theirs. Server mode only
|
||||
(`server/lib/account-pins.js`).
|
||||
- Quota is read with each account's own token, in the background, at most every
|
||||
5 minutes. If the usage endpoint refuses a setup-token, the state column shows
|
||||
`no quota (…)` and ranking uses spend alone.
|
||||
@@ -447,6 +470,7 @@ CODEX_HOME=$(mktemp -d) codex login
|
||||
agenthub accounts add team-chatgpt --tool codex --from /tmp/tmp.XXXX
|
||||
agenthub accounts list --tool codex
|
||||
agenthub accounts remove team-key --tool codex
|
||||
agenthub accounts pin team-key mia --tool codex # pins work as for Claude
|
||||
```
|
||||
|
||||
- **API key**: any number of panes at once. The pane gets the key through
|
||||
@@ -586,7 +610,7 @@ What runs as the member, and how:
|
||||
- In a member's folder, git and `gh` run as `sudo -n -u ah-<name> git …`, so git's own ownership check passes and every file stays the member's.
|
||||
- The editor and `.gitignore` saves go through `/opt/agenthub/libexec/write-as`.
|
||||
- A file uploaded in the Files tab (`POST /api/lanes/:id/git/upload`) is written the same way, AS the member through `write-as` (content on stdin), and only as a NEW file in an existing folder of the workspace — never over an existing name, never into `.git`, never a home dot folder, at most 25 MB. With **Download** on a file (`GET /api/lanes/:id/git/download`, read like any member file below, up to 512 MB) this is how a member with no SSH or `scp` to the host moves files in and out of their own folder; both work in a folder that is not a git repo.
|
||||
- AgentHub's stored git logins are never handed to a member's git, and a password typed in the git bar goes into the member's OWN store (below) for that one call — through `write-as`'s stdin, never sudo's argv or env — and out again unless "remember" was ticked; a store that cannot be read is never rewritten (`409 ESTOREUNREADABLE`). The member keeps their OWN identity in Settings → Git → **Your git identity** (`/api/me/git`): a commit author (`user.name`/`user.email` in their `~/.gitconfig` — commits fail without one; a new member has none), SSH keys AgentHub makes for them (an ED25519 and/or an RSA one — AWS CodeCommit takes only RSA) and HTTPS logins, both under `~/.config/agenthub/` in their home, written as them by `write-as` (0600). Add workspace → **Clone** (`POST /api/lanes/clone`) clones as them with it and writes it into the clone's own config (`core.sshCommand` / `credential.helper=store --file=…`), so the git bar and their agents' pushes in that repo use it too. A plain `git` they type themselves in a pane reads none of that, so making the key also sets `core.sshCommand` in their `~/.gitconfig` (the key first, then `~/.ssh/id_*`; a switch under the key, issue #82) — unless they already set their own, which is left alone. The SSH keys are shown one section per kind of host, each with only its own steps: **GitHub · GitLab · Gitea · Bitbucket** (ED25519) and **AWS CodeCommit** (RSA: copy → upload in IAM → paste the SSH key ID `APKA…` and pick the region), plus a collapsed **Other SSH hosts (advanced)**. The key ID (or another host's user) is saved as `url."ssh://<user>@<host>/".insteadOf "ssh://<host>/"` in the same `~/.gitconfig`, so the plain `git clone ssh://git-codecommit.<region>.amazonaws.com/v1/repos/<repo>` works in a pane and in Clone. A login typed in the Clone dialog goes to their store through `write-as`'s stdin, never sudo's argv or env, and is removed again after the clone unless "remember" was ticked.
|
||||
- AgentHub's stored git logins are never handed to a member's git, and a password typed in the git bar goes into the member's OWN store (below) for that one call — through `write-as`'s stdin, never sudo's argv or env — and out again unless "remember" was ticked; a store that cannot be read is never rewritten (`409 ESTOREUNREADABLE`). The member keeps their OWN identity in Settings → Git → **Your git identity** (`/api/me/git`): a commit author (`user.name`/`user.email` in their `~/.gitconfig` — commits fail without one; a new member has none), SSH keys AgentHub makes for them (an ED25519 and/or an RSA one — AWS CodeCommit takes only RSA) and HTTPS logins, both under `~/.config/agenthub/` in their home, written as them by `write-as` (0600). Add workspace → **Clone** (`POST /api/lanes/clone`) clones as them with it and writes it into the clone's own config (`core.sshCommand` / `credential.helper=store --file=…`), so the git bar and their agents' pushes in that repo use it too. A plain `git` they type themselves in a pane reads none of that, so making the key also sets `core.sshCommand` in their `~/.gitconfig` (the key first, then `~/.ssh/id_*`; a switch under the key, issue #82) — unless they already set their own, which is left alone. The SSH keys are shown one TAB per kind of host, each with only its own steps: **GitHub · GitLab** (ED25519, for Gitea and Bitbucket too) and **AWS CodeCommit** (RSA: copy → upload in IAM → paste the SSH key ID `APKA…` and pick the region), then **More keys** (named keys for extra accounts) and **Other hosts** (advanced); it opens on the AWS tab when only an RSA key exists. The terminal switch sits under the tabs. The key ID (or another host's user) is saved as `url."ssh://<user>@<host>/".insteadOf "ssh://<host>/"` in the same `~/.gitconfig`, so the plain `git clone ssh://git-codecommit.<region>.amazonaws.com/v1/repos/<repo>` works in a pane and in Clone. A login typed in the Clone dialog goes to their store through `write-as`'s stdin, never sudo's argv or env, and is removed again after the clone unless "remember" was ticked.
|
||||
- **Files a pane reads.** These are written into `~/.agenthub/handoff/` AS the member (`write-as`). The dashboard never writes, changes or deletes anything in a member's home itself: the member could have swapped the name for a link. The files are:
|
||||
- the workspace prompt and its context files;
|
||||
- the AI Proxy settings: no key, only that pane's own token for the gateway;
|
||||
|
||||
@@ -19,7 +19,7 @@ One place to keep what agents PRODUCE, and (in server mode) to share it:
|
||||
## Rules (binding, same spirit as CLAUDE.md)
|
||||
|
||||
- **What is shared is a SNAPSHOT, never the owner's live file.** Sharing a `file`/`skill` copies it (size-capped, regular files only, no symlinks followed) into `<data dir>/artifacts/<id>/`, written once like `session_snapshots`. Viewers read only that copy, so no route ever reads another user's home for them. Re-sharing makes a new snapshot.
|
||||
- **Nothing shared runs on the dashboard's origin.** HTML/SVG previews are served under the `/git/raw` headers (`sandbox` CSP + `nosniff`) and shown in a sandboxed iframe; a `page` is only a link out, accepted only as `https://claude.ai/…`.
|
||||
- **Nothing shared runs on the dashboard's origin.** HTML/SVG previews are served under the `/git/raw` headers (`sandbox` CSP + `nosniff`) and shown in a sandboxed iframe; a type that sandbox cannot show (Office files, zip, PDF — the sandbox blocks both a download and the PDF viewer) gets Download only, never a blank Preview. A `page` is only a link out, accepted only as `https://claude.ai/…`.
|
||||
- **Installing is the viewer's explicit click, into the viewer's own account only.** For a skill, the hub writes the snapshot's files into `~/.claude/skills/<name>/` of the VIEWER (S3: as their member, through `write-as`). It never overwrites an existing skill without `conflict: replace`, and the old one goes to the trash first. For a plugin, the hub runs `claude plugin marketplace add <source>` + `claude plugin install <name>@<market> --scope user` as the viewer (the `applyPluginBaseline` path). The marketplace source passes an allowlist (`owner/repo` or a `validateRemoteUrl` URL), and no argv comes from the request beyond those two validated values.
|
||||
- **Before installing, the dialog lists every file of the skill** (a skill may carry scripts that the viewer's agent will run). Every share, unshare and install is written to `audit_log`.
|
||||
- **Visibility follows ownership:** a developer sees their own artifacts plus shared ones; admin/analyst see per `scope.js`, like sessions. Unshare removes an artifact from the Hub but does not uninstall copies others already installed.
|
||||
|
||||
+318
-1
@@ -3,7 +3,7 @@
|
||||
openapi: 3.0.3
|
||||
info:
|
||||
title: Agent Dashboard for Claude Code API
|
||||
version: 2.8.5
|
||||
version: 2.8.11
|
||||
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ĩ
|
||||
@@ -4785,6 +4785,22 @@ components:
|
||||
description: Events attributed to this run's inner agents, ordered by created_at then id. Capped at 5000 rows.
|
||||
items:
|
||||
$ref: '#/components/schemas/DashboardEvent'
|
||||
AccountPin:
|
||||
type: object
|
||||
required:
|
||||
- userId
|
||||
- username
|
||||
- account
|
||||
properties:
|
||||
userId:
|
||||
type: integer
|
||||
username:
|
||||
type: string
|
||||
account:
|
||||
type: string
|
||||
description: The pool account's name
|
||||
pinnedAt:
|
||||
type: string
|
||||
UserPrefs:
|
||||
type: object
|
||||
required:
|
||||
@@ -13328,6 +13344,178 @@ paths:
|
||||
description: 'ENOBACKUPDIR: no backup folder is set'
|
||||
'403':
|
||||
description: 'EBADORIGIN: another site asked'
|
||||
/api/settings/retention:
|
||||
get:
|
||||
tags:
|
||||
- Settings
|
||||
summary: Automatic retention and database space
|
||||
operationId: getRetention
|
||||
responses:
|
||||
'200':
|
||||
description: Automatic retention setting, database space and the last Compact
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required:
|
||||
- days
|
||||
- max_days
|
||||
- env_owned
|
||||
- compacting
|
||||
properties:
|
||||
days:
|
||||
type: integer
|
||||
minimum: 0
|
||||
maximum: 3650
|
||||
description: Finished sessions older than this many days are purged by the hourly maintenance; 0 = off (the default)
|
||||
max_days:
|
||||
type: integer
|
||||
env_owned:
|
||||
type: object
|
||||
properties:
|
||||
days:
|
||||
type: boolean
|
||||
last_run:
|
||||
type: object
|
||||
nullable: true
|
||||
description: 'This process''s last hourly maintenance: {at, retention?: {purged_sessions, purged_events, purged_agents, error?}, reclaim: {reclaimed_pages, error?}, ms}'
|
||||
space:
|
||||
type: object
|
||||
nullable: true
|
||||
properties:
|
||||
auto_vacuum:
|
||||
type: string
|
||||
enum:
|
||||
- none
|
||||
- full
|
||||
- incremental
|
||||
page_size:
|
||||
type: integer
|
||||
page_count:
|
||||
type: integer
|
||||
freelist_pages:
|
||||
type: integer
|
||||
free_bytes:
|
||||
type: integer
|
||||
db_size:
|
||||
type: integer
|
||||
description: Database file size in bytes
|
||||
compacting:
|
||||
type: boolean
|
||||
last_compact:
|
||||
type: object
|
||||
nullable: true
|
||||
description: 'This process''s last Compact: {at, ok, size_before?, size_after?, ms?, error?}'
|
||||
put:
|
||||
tags:
|
||||
- Settings
|
||||
summary: Set the automatic retention
|
||||
description: Persisted to the settings file as AGENTHUB_RETENTION_DAYS. 0 turns it off. Same-origin only; in server mode an admin's.
|
||||
operationId: setRetention
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required:
|
||||
- days
|
||||
properties:
|
||||
days:
|
||||
type: integer
|
||||
minimum: 0
|
||||
maximum: 3650
|
||||
responses:
|
||||
'200':
|
||||
description: The new state
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required:
|
||||
- days
|
||||
- max_days
|
||||
- env_owned
|
||||
- compacting
|
||||
properties:
|
||||
days:
|
||||
type: integer
|
||||
minimum: 0
|
||||
maximum: 3650
|
||||
description: Finished sessions older than this many days are purged by the hourly maintenance; 0 = off (the default)
|
||||
max_days:
|
||||
type: integer
|
||||
env_owned:
|
||||
type: object
|
||||
properties:
|
||||
days:
|
||||
type: boolean
|
||||
last_run:
|
||||
type: object
|
||||
nullable: true
|
||||
description: 'This process''s last hourly maintenance: {at, retention?: {purged_sessions, purged_events, purged_agents, error?}, reclaim: {reclaimed_pages, error?}, ms}'
|
||||
space:
|
||||
type: object
|
||||
nullable: true
|
||||
properties:
|
||||
auto_vacuum:
|
||||
type: string
|
||||
enum:
|
||||
- none
|
||||
- full
|
||||
- incremental
|
||||
page_size:
|
||||
type: integer
|
||||
page_count:
|
||||
type: integer
|
||||
freelist_pages:
|
||||
type: integer
|
||||
free_bytes:
|
||||
type: integer
|
||||
db_size:
|
||||
type: integer
|
||||
description: Database file size in bytes
|
||||
compacting:
|
||||
type: boolean
|
||||
last_compact:
|
||||
type: object
|
||||
nullable: true
|
||||
description: 'This process''s last Compact: {at, ok, size_before?, size_after?, ms?, error?}'
|
||||
'400':
|
||||
description: 'INVALID_INPUT: days is not a whole number from 0 to 3650'
|
||||
'403':
|
||||
description: 'EBADORIGIN: another site asked'
|
||||
'409':
|
||||
description: 'EENVOWNED: the environment set AGENTHUB_RETENTION_DAYS'
|
||||
'500':
|
||||
description: 'ESAVE: the settings file could not be written'
|
||||
/api/settings/compact:
|
||||
post:
|
||||
tags:
|
||||
- Settings
|
||||
summary: Compact the database now (full VACUUM)
|
||||
description: Rewrites the database in a worker thread, switching it to incremental auto_vacuum, then truncates the WAL. Hook writes wait while it runs. Answers at once; poll GET /api/settings/retention while `compacting`. Same-origin only; in server mode an admin's.
|
||||
operationId: compactDatabase
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required:
|
||||
- confirm
|
||||
properties:
|
||||
confirm:
|
||||
type: boolean
|
||||
enum:
|
||||
- true
|
||||
responses:
|
||||
'202':
|
||||
description: Started (or already running); the retention state
|
||||
'400':
|
||||
description: 'ECONFIRM: confirm: true is missing'
|
||||
'403':
|
||||
description: 'EBADORIGIN: another site asked'
|
||||
/api/settings/codex-hooks:
|
||||
get:
|
||||
tags:
|
||||
@@ -14969,6 +15157,18 @@ paths:
|
||||
nullable: true
|
||||
full:
|
||||
type: boolean
|
||||
pins:
|
||||
type: object
|
||||
description: Per tool, the users an admin pinned to one account (empty in local mode)
|
||||
properties:
|
||||
claude:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/AccountPin'
|
||||
codex:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/AccountPin'
|
||||
codex:
|
||||
type: array
|
||||
description: The Codex account pool (server/lib/codex-pool.js), same fields plus `kind`; no expiry
|
||||
@@ -15069,6 +15269,62 @@ paths:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
/api/accounts/pins:
|
||||
put:
|
||||
tags:
|
||||
- Auth
|
||||
operationId: pinPoolAccount
|
||||
summary: 'Admin: switch one user''s sessions of a tool to one pool account (`account: null` = automatic), with their own password again. A Claude login is written into their home at once; running panes take it without a restart'
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required:
|
||||
- tool
|
||||
- userId
|
||||
- currentPassword
|
||||
properties:
|
||||
tool:
|
||||
type: string
|
||||
enum:
|
||||
- claude
|
||||
- codex
|
||||
userId:
|
||||
type: integer
|
||||
account:
|
||||
type: string
|
||||
nullable: true
|
||||
currentPassword:
|
||||
type: string
|
||||
responses:
|
||||
'200':
|
||||
description: '`{pin: {userId, username, account}, switched}` — `account` null when unpinned; `switched`: switched | kept | own-login | expired | next-session | null'
|
||||
'400':
|
||||
description: EBADTOOL
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
'403':
|
||||
description: EREAUTH — wrong password; EADMIN — not an admin; ELOCALMODE
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
'404':
|
||||
description: ENOUSER, ENOACCOUNT
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
'429':
|
||||
description: ETOOMANY — too many wrong passwords
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
/api/accounts/profiles:
|
||||
get:
|
||||
tags:
|
||||
@@ -15078,6 +15334,67 @@ paths:
|
||||
responses:
|
||||
'200':
|
||||
description: '`{profiles: [{name, label, email, subscriptionType, active}]}`'
|
||||
/api/accounts/{name}/users:
|
||||
put:
|
||||
tags:
|
||||
- Auth
|
||||
operationId: setPoolAccountUsers
|
||||
summary: 'Admin: exactly these users run on this pool account (a user on another account moves here; one left out goes back to the balancer), with their own password again. A Claude login is written into each added user''s home at once'
|
||||
parameters:
|
||||
- name: name
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required:
|
||||
- tool
|
||||
- userIds
|
||||
- currentPassword
|
||||
properties:
|
||||
tool:
|
||||
type: string
|
||||
enum:
|
||||
- claude
|
||||
- codex
|
||||
userIds:
|
||||
type: array
|
||||
items:
|
||||
type: integer
|
||||
currentPassword:
|
||||
type: string
|
||||
responses:
|
||||
'200':
|
||||
description: '`{added: [{userId, username, switched}], removed: [{userId, username}]}` — `switched`: switched | kept | own-login | expired | next-session'
|
||||
'400':
|
||||
description: EBADTOOL, EBADUSER
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
'403':
|
||||
description: EREAUTH — wrong password; EADMIN — not an admin; ELOCALMODE
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
'404':
|
||||
description: ENOUSER, ENOACCOUNT
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
'429':
|
||||
description: ETOOMANY — too many wrong passwords
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
/api/accounts/{name}:
|
||||
delete:
|
||||
tags:
|
||||
|
||||
Generated
+20
-984
File diff suppressed because it is too large
Load Diff
+3
-4
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "agenthub",
|
||||
"version": "2.8.6",
|
||||
"version": "2.8.11",
|
||||
"bin": {
|
||||
"agenthub": "bin/agenthub.js"
|
||||
},
|
||||
@@ -75,8 +75,8 @@
|
||||
"adm-zip": "^0.6.1",
|
||||
"cors": "^2.8.5",
|
||||
"express": "^4.21.2",
|
||||
"js-yaml": "^4.1.0",
|
||||
"multer": "^2.0.0",
|
||||
"redoc": "^2.5.3",
|
||||
"swagger-ui-express": "^5.0.1",
|
||||
"systray2": "^2.1.4",
|
||||
"tar": "^7.4.3",
|
||||
@@ -89,10 +89,9 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"concurrently": "^9.1.2",
|
||||
"js-yaml": "^4.1.0",
|
||||
"prettier": "^3.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
"node": ">=22.5.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1937,6 +1937,47 @@ async function ingestWorkflowsForBatch(dbModule, sessions) {
|
||||
}
|
||||
}
|
||||
|
||||
// Session sync: a session counts as fed LIVE by hooks while it is active, its
|
||||
// newest event came from a hook (not this importer), and a hook touched it
|
||||
// within this window. Such a transcript is left to the hooks until it goes
|
||||
// quiet. DASHBOARD_SYNC_LIVE_HOOK_MS=0 turns the deferral off.
|
||||
const LIVE_HOOK_MS = (() => {
|
||||
const n = Number(process.env.DASHBOARD_SYNC_LIVE_HOOK_MS ?? 5 * 60_000);
|
||||
return Number.isFinite(n) && n >= 0 ? n : 5 * 60_000;
|
||||
})();
|
||||
// mtimeCache value for a deferred file: present (so the fs watcher ignores its
|
||||
// appends) yet never equal to a real mtime (so every sweep re-checks it).
|
||||
const DEFERRED_MTIME = -1;
|
||||
const IMPORTED_DATA_RE = /"imported"\s*:\s*true/;
|
||||
const latestEventStmts = new WeakMap();
|
||||
|
||||
function rowIsImported(row) {
|
||||
try {
|
||||
return !!(row.metadata && JSON.parse(row.metadata).imported);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isHookLive(dbModule, row) {
|
||||
if (!(LIVE_HOOK_MS > 0) || row.status !== "active") return false;
|
||||
const touched = Date.parse(row.updated_at);
|
||||
if (!Number.isFinite(touched) || Date.now() - touched > LIVE_HOOK_MS) return false;
|
||||
try {
|
||||
let stmt = latestEventStmts.get(dbModule.db);
|
||||
if (!stmt) {
|
||||
stmt = dbModule.db.prepare(
|
||||
"SELECT data FROM events WHERE session_id = ? ORDER BY id DESC LIMIT 1"
|
||||
);
|
||||
latestEventStmts.set(dbModule.db, stmt);
|
||||
}
|
||||
const ev = stmt.get(row.id);
|
||||
return !!ev && !IMPORTED_DATA_RE.test(ev.data || "");
|
||||
} catch {
|
||||
return false; // when in doubt, sync as before
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Incremental, change-driven sync of the default `~/.claude/projects` directory.
|
||||
*
|
||||
@@ -2024,6 +2065,25 @@ async function syncDefaultProjects(dbModule, options = {}) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// A session hooks are feeding RIGHT NOW: its transcript keeps growing
|
||||
// between hooks, so `mtime > updated_at` on nearly every sweep, and a
|
||||
// full re-parse + snapshot copy here bought nothing the hooks do not
|
||||
// already record. Leave it until it goes quiet (or ends): the sentinel
|
||||
// keeps the watcher ignoring its appends, and never equals a real
|
||||
// mtime, so the first sweep after the hooks stop catches it up.
|
||||
if (existingRow && isHookLive(dbModule, existingRow)) {
|
||||
mtimeCache.set(sourcePath, DEFERRED_MTIME);
|
||||
continue;
|
||||
}
|
||||
// A session a hook created (no `imported` flag): importSession() skips
|
||||
// it outright, so parsing the whole transcript + subagents was pure
|
||||
// waste — only the durable snapshot copy still matters.
|
||||
if (existingRow && !rowIsImported(existingRow)) {
|
||||
mtimeCache.set(sourcePath, mtime);
|
||||
if (require("../server/lib/run-as").sameOwner(sourcePath, existingRow.cwd))
|
||||
await snapshotTranscript(sourcePath, sessionId);
|
||||
continue;
|
||||
}
|
||||
const existed = !!existingRow;
|
||||
const session = await parseSessionForImport(projPath, sourcePath);
|
||||
// Record the mtime even when the file yields no session, so we don't
|
||||
|
||||
+171
-25
@@ -138,14 +138,38 @@ function serverIsLive() {
|
||||
return livePids().length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* What npm installs from a manifest: its dependency lists, or the lockfile's
|
||||
* package tree — never the release's own `version`, which both files carry.
|
||||
* Hashing the whole files reinstalled every dependency on each update (minutes
|
||||
* on a slow link) when the bump changed nothing npm would fetch.
|
||||
*/
|
||||
function installedPart(file, text) {
|
||||
const json = JSON.parse(text);
|
||||
if (file === "package.json") {
|
||||
const { dependencies, optionalDependencies, overrides } = json;
|
||||
return JSON.stringify({ dependencies, optionalDependencies, overrides });
|
||||
}
|
||||
const { "": own, ...packages } = json.packages || {};
|
||||
const { version: _version, ...rest } = own || {};
|
||||
return JSON.stringify({ own: rest, packages });
|
||||
}
|
||||
|
||||
/** Hash of the dependency manifest — changes mean the runtime tree must be reinstalled. */
|
||||
function depsHash(root = PLUGIN_ROOT) {
|
||||
const h = crypto.createHash("sha256");
|
||||
for (const f of ["package.json", "package-lock.json"]) {
|
||||
let text;
|
||||
try {
|
||||
h.update(fs.readFileSync(path.join(root, f)));
|
||||
text = fs.readFileSync(path.join(root, f), "utf8");
|
||||
} catch {
|
||||
h.update(f); // absent counts as its own state
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
h.update(installedPart(f, text));
|
||||
} catch {
|
||||
h.update(text); // not JSON npm could read either: the bytes decide
|
||||
}
|
||||
}
|
||||
return h.digest("hex").slice(0, 16);
|
||||
@@ -196,6 +220,81 @@ function nodeVersionOk(version = process.versions.node) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- last failure report */
|
||||
|
||||
/**
|
||||
* The worker runs detached with its output discarded, so a failed install, a
|
||||
* Node that is too old or a failed UI build used to live only in a log nobody
|
||||
* opens — and every session silently retried. The last failure is kept in one
|
||||
* small file; the NEXT foreground pass (which Claude Code reads) prints it once
|
||||
* as a SessionStart `systemMessage`, and a bootstrap that succeeds removes it.
|
||||
*/
|
||||
function failurePath(rt = runtimeDir()) {
|
||||
return path.join(rt, "last-failure.json");
|
||||
}
|
||||
|
||||
function readFailure(rt = runtimeDir()) {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(failurePath(rt), "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Record a failure; the same kind again keeps its `reported` flag (once per failure). */
|
||||
function recordFailure(rt, kind, message, logFile) {
|
||||
const prev = readFailure(rt);
|
||||
const same = prev && prev.kind === kind && prev.message === message;
|
||||
const rec = {
|
||||
kind,
|
||||
message,
|
||||
log: logFile,
|
||||
at: new Date().toISOString(),
|
||||
reported: Boolean(same && prev.reported),
|
||||
};
|
||||
try {
|
||||
fs.mkdirSync(rt, { recursive: true });
|
||||
fs.writeFileSync(failurePath(rt), JSON.stringify(rec, null, 2) + "\n", "utf8");
|
||||
} catch {
|
||||
/* best effort */
|
||||
}
|
||||
}
|
||||
|
||||
function clearFailure(rt = runtimeDir()) {
|
||||
try {
|
||||
fs.rmSync(failurePath(rt), { force: true });
|
||||
} catch {
|
||||
/* best effort */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The SessionStart output for an unreported failure, or null. Marks it
|
||||
* reported, so a failure is shown once — not on every session until fixed.
|
||||
*/
|
||||
function takeFailureReport(rt = runtimeDir()) {
|
||||
const rec = readFailure(rt);
|
||||
if (!rec || rec.reported) return null;
|
||||
try {
|
||||
fs.writeFileSync(failurePath(rt), JSON.stringify({ ...rec, reported: true }, null, 2) + "\n");
|
||||
} catch {
|
||||
return null; // could not mark it: stay quiet rather than repeat forever
|
||||
}
|
||||
return {
|
||||
systemMessage:
|
||||
`AgentHub: ${rec.message}` +
|
||||
(rec.log ? ` — details in ${rec.log}` : "") +
|
||||
". Run /agenthub-doctor for a diagnosis.",
|
||||
};
|
||||
}
|
||||
|
||||
function nodeTooOldMessage(version = process.versions.node) {
|
||||
return (
|
||||
`Node ${version} is too old — AgentHub needs Node >= ${MIN_NODE.join(".")} ` +
|
||||
`(the server stores data through node:sqlite). Upgrade Node, then start a new session`
|
||||
);
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------- lock */
|
||||
|
||||
function lockPath(rt = runtimeDir()) {
|
||||
@@ -422,13 +521,22 @@ function installDeps(rt = runtimeDir(), root = PLUGIN_ROOT) {
|
||||
if (fs.existsSync(src)) fs.copyFileSync(src, path.join(rt, f));
|
||||
}
|
||||
const npm = npmCommand(["install", "--omit=dev", "--ignore-scripts", "--no-audit", "--no-fund"]);
|
||||
const res = spawnSync(npm.file, npm.args, {
|
||||
cwd: rt,
|
||||
stdio: "inherit",
|
||||
env: npm.env,
|
||||
shell: npm.shell,
|
||||
});
|
||||
return res.status === 0;
|
||||
// npm's output goes to a log: the worker's own stdout is discarded, so
|
||||
// inheriting it threw away the one explanation of a failed install.
|
||||
const logPath = path.join(rt, "npm-install.log");
|
||||
require("./log-rotate").rotateIfLarge(logPath);
|
||||
const logFd = fs.openSync(logPath, "a");
|
||||
try {
|
||||
const res = spawnSync(npm.file, npm.args, {
|
||||
cwd: rt,
|
||||
stdio: ["ignore", logFd, logFd],
|
||||
env: npm.env,
|
||||
shell: npm.shell,
|
||||
});
|
||||
return res.status === 0;
|
||||
} finally {
|
||||
fs.closeSync(logFd);
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ server */
|
||||
@@ -671,11 +779,8 @@ function bootstrap(rt = runtimeDir(), { force = false } = {}) {
|
||||
}
|
||||
|
||||
if (!nodeVersionOk()) {
|
||||
log(
|
||||
rt,
|
||||
`Node ${process.versions.node} is too old — AgentHub needs Node >= ${MIN_NODE.join(".")} ` +
|
||||
`(the server stores data through node:sqlite). Upgrade Node, then start a new session.`
|
||||
);
|
||||
log(rt, nodeTooOldMessage());
|
||||
recordFailure(rt, "node-too-old", nodeTooOldMessage(), path.join(rt, "bootstrap.log"));
|
||||
return "node-too-old";
|
||||
}
|
||||
|
||||
@@ -695,7 +800,16 @@ function bootstrap(rt = runtimeDir(), { force = false } = {}) {
|
||||
if (force || state.depsHash !== wantDeps || !fs.existsSync(path.join(rt, "node_modules"))) {
|
||||
log(rt, "installing runtime dependencies (first run takes a few minutes)");
|
||||
if (!installDeps(rt)) {
|
||||
log(rt, "npm install failed — see the output above; run /agenthub-doctor after fixing it");
|
||||
log(
|
||||
rt,
|
||||
`npm install failed — see ${path.join(rt, "npm-install.log")}; run /agenthub-doctor after fixing it`
|
||||
);
|
||||
recordFailure(
|
||||
rt,
|
||||
"install-failed",
|
||||
"installing the dashboard's runtime dependencies failed",
|
||||
path.join(rt, "npm-install.log")
|
||||
);
|
||||
return "install-failed";
|
||||
}
|
||||
}
|
||||
@@ -713,17 +827,24 @@ function bootstrap(rt = runtimeDir(), { force = false } = {}) {
|
||||
|
||||
// Built eagerly (not lazily behind /agenthub-open) so the dashboard, including
|
||||
// client-only routes like /run, works the instant `claude` is started —
|
||||
// same trigger as the dependency install above: missing, or this plugin
|
||||
// version has not built one yet.
|
||||
// when missing, or when this plugin version has not built one yet
|
||||
// (`clientBuild` is recorded only after a build that did not fail, so the
|
||||
// next session retries a failed one instead of keeping the old UI for good).
|
||||
const { buildClient } = require("./plugin-open");
|
||||
const uiResult = buildClient({
|
||||
rt,
|
||||
root: PLUGIN_ROOT,
|
||||
force: force || state.depsHash !== wantDeps,
|
||||
force: force || state.clientBuild !== pluginVersion(),
|
||||
logPath: path.join(rt, "client-build.log"),
|
||||
});
|
||||
if (uiResult === "failed") {
|
||||
log(rt, "dashboard UI build failed — the API still works; run /agenthub-open to retry");
|
||||
recordFailure(
|
||||
rt,
|
||||
"ui-build-failed",
|
||||
"the dashboard UI build failed (the API still works; /agenthub-open retries it)",
|
||||
path.join(rt, "client-build.log")
|
||||
);
|
||||
} else if (uiResult === "built") {
|
||||
log(rt, "built the dashboard UI bundle");
|
||||
}
|
||||
@@ -829,6 +950,7 @@ function bootstrap(rt = runtimeDir(), { force = false } = {}) {
|
||||
{
|
||||
pluginVersion: pluginVersion(),
|
||||
depsHash: wantDeps,
|
||||
clientBuild: uiResult === "failed" ? state.clientBuild : pluginVersion(),
|
||||
pluginRoot: PLUGIN_ROOT,
|
||||
claudeHome: getClaudeHome(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
@@ -836,6 +958,8 @@ function bootstrap(rt = runtimeDir(), { force = false } = {}) {
|
||||
rt
|
||||
);
|
||||
|
||||
if (uiResult !== "failed") clearFailure(rt);
|
||||
|
||||
// After the state is durable, so a prune that goes wrong cannot also cost
|
||||
// us the record of a bootstrap that went right.
|
||||
pruneRetiredPluginRoots(rt);
|
||||
@@ -868,13 +992,26 @@ function bootstrap(rt = runtimeDir(), { force = false } = {}) {
|
||||
* milliseconds in the steady state, and otherwise hands off to a detached
|
||||
* worker so the session never waits on an install.
|
||||
*/
|
||||
function main() {
|
||||
if (notTheHost() || fastPathOk()) return;
|
||||
const child = spawn(process.execPath, [__filename, "--worker"], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
});
|
||||
child.unref();
|
||||
function main(rt = runtimeDir()) {
|
||||
if (notTheHost()) return null;
|
||||
// Checked here too, not only in the worker: it costs nothing, the worker
|
||||
// could only log it, and this pass can tell the user right now. A retired
|
||||
// build stays silent — its worker would do nothing either.
|
||||
if (!nodeVersionOk()) {
|
||||
if (supersededBy()) return null;
|
||||
recordFailure(rt, "node-too-old", nodeTooOldMessage(), null);
|
||||
return takeFailureReport(rt);
|
||||
}
|
||||
if (!fastPathOk(rt)) {
|
||||
const child = spawn(process.execPath, [__filename, "--worker"], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
});
|
||||
child.unref();
|
||||
}
|
||||
// A failure the previous worker recorded (it ran after that session's
|
||||
// foreground pass had already returned). Pure fs; writes only to mark it shown.
|
||||
return takeFailureReport(rt);
|
||||
}
|
||||
|
||||
// Exported before the entry block below, not after it: `bootstrap()` requires
|
||||
@@ -897,6 +1034,12 @@ module.exports = {
|
||||
depsHash,
|
||||
fastPathOk,
|
||||
nodeVersionOk,
|
||||
failurePath,
|
||||
readFailure,
|
||||
recordFailure,
|
||||
clearFailure,
|
||||
takeFailureReport,
|
||||
main,
|
||||
lockPath,
|
||||
lockIsStale,
|
||||
acquireLock,
|
||||
@@ -934,7 +1077,10 @@ if (require.main === module) {
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
main();
|
||||
const report = main();
|
||||
// SessionStart reads a JSON object on stdout; `systemMessage` is shown
|
||||
// to the user. Nothing at all is printed in the steady state.
|
||||
if (report) process.stdout.write(JSON.stringify(report) + "\n");
|
||||
} catch {
|
||||
// A bootstrap failure must never break a Claude Code session.
|
||||
}
|
||||
|
||||
+46
-12
@@ -68,7 +68,19 @@ function buildClient({
|
||||
const stdio = logFd === null ? "inherit" : ["ignore", logFd, logFd];
|
||||
try {
|
||||
const src = path.join(rt, "client-src");
|
||||
fs.rmSync(src, { recursive: true, force: true });
|
||||
// The installed tree is kept across updates while the client's manifests
|
||||
// are unchanged (`stamp`, written after a successful install): a release
|
||||
// rarely touches them, and the clean `npm ci` below fetched all of the
|
||||
// ~200 MB toolchain again on every update.
|
||||
const stamp = path.join(src, "node_modules", ".agenthub-deps");
|
||||
const want = clientDepsHash(root);
|
||||
const reuse = readText(stamp) === want;
|
||||
if (reuse) {
|
||||
for (const e of fs.readdirSync(src))
|
||||
if (e !== "node_modules") fs.rmSync(path.join(src, e), { recursive: true, force: true });
|
||||
} else {
|
||||
fs.rmSync(src, { recursive: true, force: true });
|
||||
}
|
||||
fs.cpSync(path.join(root, "client"), src, {
|
||||
recursive: true,
|
||||
filter: (p) => !/[\\/](node_modules|dist)$/.test(p),
|
||||
@@ -101,19 +113,25 @@ function buildClient({
|
||||
// esbuild is the only dependency with an install script, and it finds its
|
||||
// platform binary without it.
|
||||
const npmFlags = ["--no-audit", "--no-fund", "--include=dev", "--ignore-scripts"];
|
||||
if (
|
||||
!exec(NPM, ["ci", ...npmFlags], src, stdio) &&
|
||||
!exec(NPM, ["install", ...npmFlags], src, stdio)
|
||||
) {
|
||||
return "failed";
|
||||
if (!reuse) {
|
||||
if (
|
||||
!exec(NPM, ["ci", ...npmFlags], src, stdio) &&
|
||||
!exec(NPM, ["install", ...npmFlags], src, stdio)
|
||||
) {
|
||||
return "failed";
|
||||
}
|
||||
fs.mkdirSync(path.dirname(stamp), { recursive: true });
|
||||
fs.writeFileSync(stamp, want);
|
||||
}
|
||||
// = client/package.json's "build" script (`tsc -b && vite build`); a test
|
||||
// keeps the two in step.
|
||||
// client/package.json's "build" script is `tsc -b && vite build`; only the
|
||||
// vite half runs here. The type check emits nothing the bundle needs, and on
|
||||
// a user's machine it cost ~25 s and ~900 MB of memory per update — and a
|
||||
// type error in a release then kept the old UI everywhere (v2.7.0). The
|
||||
// release itself still runs `tsc -b`. A test keeps the two in step.
|
||||
const bin = (...p) => path.join(src, "node_modules", ...p);
|
||||
if (
|
||||
!exec(NODE, [bin("typescript", "bin", "tsc"), "-b"], src, stdio) ||
|
||||
!exec(NODE, [bin("vite", "bin", "vite.js"), "build"], src, stdio)
|
||||
) {
|
||||
if (!exec(NODE, [bin("vite", "bin", "vite.js"), "build"], src, stdio)) {
|
||||
// Maybe a damaged kept tree: the next build starts from a clean install.
|
||||
fs.rmSync(stamp, { force: true });
|
||||
return "failed";
|
||||
}
|
||||
|
||||
@@ -125,6 +143,22 @@ function buildClient({
|
||||
}
|
||||
}
|
||||
|
||||
function readText(file) {
|
||||
try {
|
||||
return fs.readFileSync(file, "utf8");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The client's manifests, which decide whether its installed tree still fits. */
|
||||
function clientDepsHash(root) {
|
||||
const h = require("crypto").createHash("sha256");
|
||||
for (const f of ["package.json", "package-lock.json"])
|
||||
h.update(readText(path.join(root, "client", f)) ?? `no ${f}`);
|
||||
return h.digest("hex").slice(0, 16);
|
||||
}
|
||||
|
||||
function dashboardUrl() {
|
||||
try {
|
||||
return `http://localhost:${resolveDashboardPort()}`;
|
||||
|
||||
@@ -3,14 +3,20 @@
|
||||
* @file Detached helper spawned by `server/lib/self-restart.js`. Polls the
|
||||
* old dashboard PID until it exits (server/index.js's own SIGTERM handler
|
||||
* has a 5s force-exit backstop, so this never waits forever), then starts a
|
||||
* fresh server from the same entry point and exits itself.
|
||||
* fresh server from the same entry point and exits itself. The new server's
|
||||
* stdout/stderr are appended to the log file it is given (the checkout's
|
||||
* `data/agenthub-server.log`, the one `agenthub start` writes), so a crash
|
||||
* after an update still leaves Node's stack trace behind.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
require("../server/lib/windows-hide").install(); // before child_process is read
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { spawn } = require("child_process");
|
||||
const { rotateIfLarge } = require("./log-rotate");
|
||||
|
||||
const [, , pidArg, entry] = process.argv;
|
||||
const [, , pidArg, entry, logArg] = process.argv;
|
||||
const pid = parseInt(pidArg, 10);
|
||||
|
||||
// ponytail: fixed poll cadence/cap, not configurable — this script has one caller.
|
||||
@@ -26,10 +32,25 @@ function isAlive(p) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Append fd for the new server's output, or "ignore" when there is none. */
|
||||
function openLog(file) {
|
||||
if (!file) return "ignore";
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
rotateIfLarge(file);
|
||||
const fd = fs.openSync(file, "a");
|
||||
fs.writeSync(fd, `[${new Date().toISOString()}] restart-helper: old server ${pid} gone, starting ${entry}\n`);
|
||||
return fd;
|
||||
} catch {
|
||||
return "ignore"; // a log must never stop the restart
|
||||
}
|
||||
}
|
||||
|
||||
function restart() {
|
||||
const out = openLog(logArg);
|
||||
const child = spawn(process.execPath, [entry], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
stdio: ["ignore", out, out],
|
||||
env: process.env,
|
||||
});
|
||||
child.unref();
|
||||
|
||||
+3
-2
@@ -439,7 +439,7 @@ All endpoints return JSON unless noted. Error responses use:
|
||||
| `GET` | `/api/openapi.json` | Raw OpenAPI 3.0.3 spec |
|
||||
| `GET` | `/api/docs` | Interactive **Swagger UI** (try-it-out request execution) |
|
||||
| `GET` | `/api/redoc` | **ReDoc** reference — clean, read-optimized three-panel rendering of the same spec |
|
||||
| `GET` | `/api/redoc/redoc.standalone.js` | Self-hosted ReDoc bundle (via the `redoc` dependency, never a CDN — works offline) |
|
||||
| `GET` | `/api/redoc/redoc.standalone.js` | Self-hosted ReDoc bundle (vendored in `server/vendor/redoc/`, never a CDN — works offline) |
|
||||
|
||||
The OpenAPI spec is generated from `server/openapi.js` (`createOpenApiSpec()`), merged with supplementary fragments under `server/openapi-extra/`, and is the source of truth for request/response contracts. It now documents every backend route (75 path entries). Both Swagger UI and ReDoc (`server/lib/redoc.js`) render the same spec; the ReDoc bundle is served locally so the reference works offline / air-gapped. A committed `openapi.yaml` at the repo root mirrors the live spec — regenerate it after API changes with `npm run openapi:yaml` (never hand-edit it).
|
||||
|
||||
@@ -1600,10 +1600,11 @@ DASHBOARD_DB_PATH=./data/dashboard.db # SQLite database path
|
||||
DASHBOARD_AI_TOOLS_DIR= # Extra AI Tools catalog JSON files; an id here replaces the built-in one
|
||||
AGENTHUB_SHELL_PATH=1 # 0 = never run the login shell to read its PATH (startup + Refresh)
|
||||
AGENTHUB_AI_TOOLS_SYNC=1 # 0 = never copy the newest release's AI Tools catalog (server/lib/ai-tools-sync.js, daily)
|
||||
DASHBOARD_LANE_SYNC_MS=2000 # re-broadcast lanes another dashboard on the same DB changed (PRAGMA data_version); 0 = off
|
||||
DASHBOARD_LANE_SYNC_MS=2000 # re-broadcast lanes another dashboard on the same DB changed (PRAGMA data_version), only while one runs (checked every 30 s); 0 = off
|
||||
|
||||
# Background services
|
||||
DASHBOARD_SESSION_SYNC_MS=30000 # Continuous project-sync poll interval (ms); 0 disables the poll (watcher stays)
|
||||
DASHBOARD_SYNC_LIVE_HOOK_MS=300000 # project sync leaves a transcript alone while hooks fed its session within this window; 0 = never defer
|
||||
DASHBOARD_LIVENESS_PROBE=1 # 0 disables the dead-session liveness reap (use when hooks arrive from another machine)
|
||||
DASHBOARD_LIVENESS_IDLE_SECONDS=60 # Idle gate before the liveness reap may complete a process-less session
|
||||
DASHBOARD_REPORTS_MS=60000 # Scheduled-reports beat (ms); 0 disables the scheduler
|
||||
|
||||
@@ -213,6 +213,13 @@ describe("OpenAPI / Swagger", () => {
|
||||
const res = await fetch("/api/redoc/redoc.standalone.js");
|
||||
assert.equal(res.status, 200);
|
||||
assert.match(res.headers["content-type"], /javascript/);
|
||||
// The vendored file (server/vendor/redoc/), licence banner intact — the
|
||||
// `redoc` npm package is no longer a dependency.
|
||||
assert.match(
|
||||
res.body,
|
||||
/For license information please see redoc\.standalone\.js\.LICENSE\.txt/
|
||||
);
|
||||
assert.doesNotThrow(() => require("fs").statSync(require("../lib/redoc").redocBundlePath()));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -42,19 +42,21 @@ function request(method, p, body, headers = {}) {
|
||||
method,
|
||||
headers: { "Content-Type": "application/json", ...headers },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
}).then(async (r) => ({
|
||||
status: r.status,
|
||||
headers: r.headers,
|
||||
text: await r.text(),
|
||||
})).then((r) => {
|
||||
let json = null;
|
||||
try {
|
||||
json = JSON.parse(r.text);
|
||||
} catch {
|
||||
/* not JSON */
|
||||
}
|
||||
return { ...r, body: json };
|
||||
});
|
||||
})
|
||||
.then(async (r) => ({
|
||||
status: r.status,
|
||||
headers: r.headers,
|
||||
text: await r.text(),
|
||||
}))
|
||||
.then((r) => {
|
||||
let json = null;
|
||||
try {
|
||||
json = JSON.parse(r.text);
|
||||
} catch {
|
||||
/* not JSON */
|
||||
}
|
||||
return { ...r, body: json };
|
||||
});
|
||||
}
|
||||
|
||||
before(async () => {
|
||||
@@ -63,18 +65,23 @@ before(async () => {
|
||||
fs.writeFileSync(path.join(ws, "main.js"), "code");
|
||||
const skill = path.join(ws, ".claude", "skills", "deploy");
|
||||
fs.mkdirSync(path.join(skill, "scripts"), { recursive: true });
|
||||
fs.writeFileSync(path.join(skill, "SKILL.md"), "---\nname: deploy\ndescription: Ship it\n---\nDo it.\n");
|
||||
fs.writeFileSync(
|
||||
path.join(skill, "SKILL.md"),
|
||||
"---\nname: deploy\ndescription: Ship it\n---\nDo it.\n"
|
||||
);
|
||||
fs.writeFileSync(path.join(skill, "scripts", "run.sh"), "echo hi\n");
|
||||
fs.mkdirSync(process.env.CLAUDE_HOME, { recursive: true });
|
||||
lane = lanesLib.createLane({ cwd: ws, title: "ws" });
|
||||
db.prepare("INSERT INTO sessions (id, name, status, cwd, lane_id) VALUES ('s1', 's1', 'active', ?, ?)").run(
|
||||
ws,
|
||||
lane.id
|
||||
);
|
||||
db.prepare(
|
||||
"INSERT INTO sessions (id, name, status, cwd, lane_id) VALUES ('s1', 's1', 'active', ?, ?)"
|
||||
).run(ws, lane.id);
|
||||
const ev = db.prepare(
|
||||
"INSERT INTO events (session_id, event_type, tool_name, data) VALUES ('s1', 'PostToolUse', ?, ?)"
|
||||
);
|
||||
ev.run("Write", JSON.stringify({ tool_input: { file_path: path.join(ws, "out", "report.html") } }));
|
||||
ev.run(
|
||||
"Write",
|
||||
JSON.stringify({ tool_input: { file_path: path.join(ws, "out", "report.html") } })
|
||||
);
|
||||
ev.run("Edit", JSON.stringify({ tool_input: { file_path: path.join(ws, "main.js") } }));
|
||||
ev.run("Write", JSON.stringify({ tool_input: { file_path: "/etc/passwd.md" } }));
|
||||
server = http.createServer(createApp());
|
||||
@@ -125,7 +132,10 @@ describe("files", () => {
|
||||
});
|
||||
|
||||
it("pins a snapshot and serves it sandboxed, never a path outside it", async () => {
|
||||
const r = await request("POST", "/api/artifacts/file", { laneId: lane.id, path: "out/report.html" });
|
||||
const r = await request("POST", "/api/artifacts/file", {
|
||||
laneId: lane.id,
|
||||
path: "out/report.html",
|
||||
});
|
||||
assert.equal(r.status, 201, r.text);
|
||||
const id = r.body.item.id;
|
||||
// The live file changes; the artifact does not.
|
||||
@@ -138,7 +148,10 @@ describe("files", () => {
|
||||
const other = await request("GET", `/api/artifacts/${id}/raw?path=../../t.db`);
|
||||
assert.equal(other.status, 404);
|
||||
|
||||
const escape = await request("POST", "/api/artifacts/file", { laneId: lane.id, path: "../t.db" });
|
||||
const escape = await request("POST", "/api/artifacts/file", {
|
||||
laneId: lane.id,
|
||||
path: "../t.db",
|
||||
});
|
||||
assert.equal(escape.status, 400);
|
||||
|
||||
const del = await request("DELETE", `/api/artifacts/${id}`);
|
||||
@@ -154,10 +167,7 @@ describe("skills", () => {
|
||||
const r = await request("POST", "/api/artifacts/skill", { laneId: lane.id, name: "deploy" });
|
||||
assert.equal(r.status, 201, r.text);
|
||||
assert.equal(r.body.item.description, "Ship it");
|
||||
assert.deepEqual(
|
||||
r.body.item.files.map((f) => f.path).sort(),
|
||||
["SKILL.md", "scripts/run.sh"]
|
||||
);
|
||||
assert.deepEqual(r.body.item.files.map((f) => f.path).sort(), ["SKILL.md", "scripts/run.sh"]);
|
||||
const id = r.body.item.id;
|
||||
|
||||
const first = await request("POST", `/api/artifacts/${id}/install`, {});
|
||||
@@ -240,7 +250,12 @@ function upload(p, files, fields = {}) {
|
||||
|
||||
const snapText = (item, file = "SKILL.md") =>
|
||||
fs.readFileSync(
|
||||
path.join(process.env.DASHBOARD_DATA_DIR, "artifacts", db.prepare("SELECT snapshot FROM artifacts WHERE id = ?").get(item.id).snapshot, file),
|
||||
path.join(
|
||||
process.env.DASHBOARD_DATA_DIR,
|
||||
"artifacts",
|
||||
db.prepare("SELECT snapshot FROM artifacts WHERE id = ?").get(item.id).snapshot,
|
||||
file
|
||||
),
|
||||
"utf8"
|
||||
);
|
||||
|
||||
@@ -263,7 +278,10 @@ describe("plugins from a marketplace link", () => {
|
||||
n("https://git.example.vn/Org/skills/src/branch/main/"),
|
||||
"https://git.example.vn/Org/skills"
|
||||
);
|
||||
assert.equal(n("https://git.example.vn/Org/skills.git"), "https://git.example.vn/Org/skills.git");
|
||||
assert.equal(
|
||||
n("https://git.example.vn/Org/skills.git"),
|
||||
"https://git.example.vn/Org/skills.git"
|
||||
);
|
||||
assert.throws(() => n("file:///etc"), { code: "EBADMARKET" });
|
||||
assert.throws(() => n("http://x/y.git"), { code: "EBADMARKET" });
|
||||
});
|
||||
@@ -281,7 +299,10 @@ describe("plugins from a marketplace link", () => {
|
||||
assert.equal(r.status, 200, r.text);
|
||||
assert.equal(asked, "https://git.example.vn/Org/skills.git");
|
||||
assert.equal(r.body.name, "sg");
|
||||
assert.deepEqual(r.body.plugins.map((p) => p.key), ["sg-dev@sg", "sg-common@sg"]);
|
||||
assert.deepEqual(
|
||||
r.body.plugins.map((p) => p.key),
|
||||
["sg-dev@sg", "sg-common@sg"]
|
||||
);
|
||||
|
||||
const add = (title) =>
|
||||
request("POST", "/api/artifacts/plugin", { key: "sg-dev@sg", market: r.body.market, title });
|
||||
@@ -312,14 +333,21 @@ describe("plugins from a marketplace link", () => {
|
||||
|
||||
describe("skills from files or written", () => {
|
||||
it("makes one Markdown file the SKILL.md, named by the user, with a frontmatter", async () => {
|
||||
const r = await upload("/api/artifacts/skill/upload", [["Notes cho đội.md", "# Do this\nStep 1\n"]], {
|
||||
name: "Hướng dẫn deploy",
|
||||
description: "Use when deploying",
|
||||
});
|
||||
const r = await upload(
|
||||
"/api/artifacts/skill/upload",
|
||||
[["Notes cho đội.md", "# Do this\nStep 1\n"]],
|
||||
{
|
||||
name: "Hướng dẫn deploy",
|
||||
description: "Use when deploying",
|
||||
}
|
||||
);
|
||||
assert.equal(r.status, 201, JSON.stringify(r.body));
|
||||
const [item] = r.body.items;
|
||||
assert.equal(item.source, "Huong-dan-deploy");
|
||||
assert.deepEqual(item.files.map((f) => f.path), ["SKILL.md"]);
|
||||
assert.deepEqual(
|
||||
item.files.map((f) => f.path),
|
||||
["SKILL.md"]
|
||||
);
|
||||
const text = snapText(item);
|
||||
assert.match(text, /^---\nname: Huong-dan-deploy\ndescription: Use when deploying\n---\n/);
|
||||
assert.match(text, /# Do this/);
|
||||
@@ -364,15 +392,23 @@ describe("skills from files or written", () => {
|
||||
["b/SKILL.md", "no frontmatter"],
|
||||
]);
|
||||
assert.equal(r.body.error.code, "ENODESCRIPTION");
|
||||
assert.equal(db.prepare("SELECT COUNT(*) AS n FROM artifacts WHERE kind = 'skill'").get().n, before);
|
||||
const secret = await upload(
|
||||
"/api/artifacts/skill/upload",
|
||||
[["s/SKILL.md", "---\ndescription: S\n---\n"], ["s/.env", "K=1"]]
|
||||
assert.equal(
|
||||
db.prepare("SELECT COUNT(*) AS n FROM artifacts WHERE kind = 'skill'").get().n,
|
||||
before
|
||||
);
|
||||
const secret = await upload("/api/artifacts/skill/upload", [
|
||||
["s/SKILL.md", "---\ndescription: S\n---\n"],
|
||||
["s/.env", "K=1"],
|
||||
]);
|
||||
assert.equal(secret.body.error.code, "ESECRET");
|
||||
const out = await upload("/api/artifacts/skill/upload", [["../SKILL.md", "x"]], { description: "d" });
|
||||
const out = await upload("/api/artifacts/skill/upload", [["../SKILL.md", "x"]], {
|
||||
description: "d",
|
||||
});
|
||||
assert.equal(out.body.error.code, "EBADPATH");
|
||||
const none = await upload("/api/artifacts/skill/upload", [["a.png", "x"], ["b.png", "y"]]);
|
||||
const none = await upload("/api/artifacts/skill/upload", [
|
||||
["a.png", "x"],
|
||||
["b.png", "y"],
|
||||
]);
|
||||
assert.equal(none.body.error.code, "ENOSKILLMD");
|
||||
});
|
||||
|
||||
@@ -383,13 +419,22 @@ describe("skills from files or written", () => {
|
||||
content: "Summarise.",
|
||||
});
|
||||
assert.equal(r.status, 201, r.text);
|
||||
assert.match(snapText(r.body.item), /^---\nname: standup\ndescription: "Use for the daily standup: summarise yesterday"\n---\n\nSummarise\./);
|
||||
const bad = await request("POST", "/api/artifacts/skill/new", { name: "!!!", description: "d", content: "c" });
|
||||
assert.match(
|
||||
snapText(r.body.item),
|
||||
/^---\nname: standup\ndescription: "Use for the daily standup: summarise yesterday"\n---\n\nSummarise\./
|
||||
);
|
||||
const bad = await request("POST", "/api/artifacts/skill/new", {
|
||||
name: "!!!",
|
||||
description: "d",
|
||||
content: "c",
|
||||
});
|
||||
assert.equal(bad.body.error.code, "EBADNAME");
|
||||
});
|
||||
|
||||
it("keeps an uploaded file as a snapshot, by its own base name", async () => {
|
||||
const r = await upload("/api/artifacts/file/upload", [["report.html", "<h1>x</h1>"]], { title: "Report" });
|
||||
const r = await upload("/api/artifacts/file/upload", [["report.html", "<h1>x</h1>"]], {
|
||||
title: "Report",
|
||||
});
|
||||
assert.equal(r.status, 201, JSON.stringify(r.body));
|
||||
assert.equal(r.body.item.kind, "file");
|
||||
assert.equal(r.body.item.title, "Report");
|
||||
@@ -408,13 +453,25 @@ describe("sharing and visibility", () => {
|
||||
});
|
||||
|
||||
it("shows a server-mode developer their own rows and shared ones only", () => {
|
||||
db.prepare("INSERT INTO artifacts (kind, title, owner_id, url) VALUES ('page', 'a', 7, 'https://claude.ai/a')").run();
|
||||
db.prepare("INSERT INTO artifacts (kind, title, owner_id, url, shared) VALUES ('page', 'b', 8, 'https://claude.ai/b', 1)").run();
|
||||
db.prepare("INSERT INTO artifacts (kind, title, owner_id, url) VALUES ('page', 'c', 8, 'https://claude.ai/c')").run();
|
||||
db.prepare(
|
||||
"INSERT INTO artifacts (kind, title, owner_id, url) VALUES ('page', 'a', 7, 'https://claude.ai/a')"
|
||||
).run();
|
||||
db.prepare(
|
||||
"INSERT INTO artifacts (kind, title, owner_id, url, shared) VALUES ('page', 'b', 8, 'https://claude.ai/b', 1)"
|
||||
).run();
|
||||
db.prepare(
|
||||
"INSERT INTO artifacts (kind, title, owner_id, url) VALUES ('page', 'c', 8, 'https://claude.ai/c')"
|
||||
).run();
|
||||
const dev = { method: "GET", user: { id: 7, role: "developer", username: "d" } };
|
||||
const titles = artifacts.list(dev).map((i) => i.title).sort();
|
||||
const titles = artifacts
|
||||
.list(dev)
|
||||
.map((i) => i.title)
|
||||
.sort();
|
||||
assert.deepEqual(titles, ["a", "b"]);
|
||||
assert.deepEqual(artifacts.list(dev, { scope: "hub" }).map((i) => i.title), ["b"]);
|
||||
assert.deepEqual(
|
||||
artifacts.list(dev, { scope: "hub" }).map((i) => i.title),
|
||||
["b"]
|
||||
);
|
||||
const hidden = db.prepare("SELECT id FROM artifacts WHERE title = 'c'").get().id;
|
||||
assert.equal(artifacts.canSeeId(dev, hidden), false);
|
||||
const shared = db.prepare("SELECT id FROM artifacts WHERE title = 'b'").get().id;
|
||||
@@ -431,3 +488,67 @@ describe("sharing and visibility", () => {
|
||||
assert.equal(r.status, 403);
|
||||
});
|
||||
});
|
||||
|
||||
describe("search, frontmatter and marketplace limits", () => {
|
||||
it("finds a title holding `_` or `%` literally, and only that one", () => {
|
||||
db.prepare(
|
||||
"INSERT INTO artifacts (kind, title, url) VALUES ('page', 'my_skill', 'https://claude.ai/u1')"
|
||||
).run();
|
||||
db.prepare(
|
||||
"INSERT INTO artifacts (kind, title, url) VALUES ('page', 'myXskill', 'https://claude.ai/u2')"
|
||||
).run();
|
||||
db.prepare(
|
||||
"INSERT INTO artifacts (kind, title, url) VALUES ('page', '100% done', 'https://claude.ai/u3')"
|
||||
).run();
|
||||
assert.deepEqual(
|
||||
artifacts.list(null, { q: "my_skill" }).map((i) => i.title),
|
||||
["my_skill"]
|
||||
);
|
||||
assert.deepEqual(
|
||||
artifacts.list(null, { q: "100%" }).map((i) => i.title),
|
||||
["100% done"]
|
||||
);
|
||||
});
|
||||
|
||||
it("replaces a multi-line description whole, and quotes one YAML would misread", () => {
|
||||
const src =
|
||||
"---\nname: x\ndescription: >\n old line one\n old line two\nallowed-tools: Read\n---\nbody\n";
|
||||
assert.equal(
|
||||
artifacts.withFrontmatter(src, "x", "new desc"),
|
||||
"---\nname: x\ndescription: new desc\nallowed-tools: Read\n---\nbody\n"
|
||||
);
|
||||
assert.match(
|
||||
artifacts.withFrontmatter("body", "x", "- Use for reports"),
|
||||
/^description: "- Use for reports"$/m
|
||||
);
|
||||
assert.match(
|
||||
artifacts.withFrontmatter("body", "x", "Use for reports"),
|
||||
/^description: Use for reports$/m
|
||||
);
|
||||
});
|
||||
|
||||
it("stops reading a marketplace.json link past 1 MB", async () => {
|
||||
const real = globalThis.fetch;
|
||||
let pulled = 0;
|
||||
globalThis.fetch = async () => {
|
||||
const body = new ReadableStream({
|
||||
pull(c) {
|
||||
pulled += 1;
|
||||
if (pulled > 100) return c.close();
|
||||
c.enqueue(new Uint8Array(64 * 1024));
|
||||
},
|
||||
});
|
||||
const res = new Response(body);
|
||||
Object.defineProperty(res, "url", { value: "https://x.example/m.json" });
|
||||
return res;
|
||||
};
|
||||
try {
|
||||
await assert.rejects(artifacts.inspectMarket("https://x.example/m.json"), {
|
||||
code: "ETOOBIG",
|
||||
});
|
||||
} finally {
|
||||
globalThis.fetch = real;
|
||||
}
|
||||
assert.ok(pulled < 30, `read ${pulled} chunks`);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* @file Tests server/lib/backoff-poll.js — the poll that runs at its base pace
|
||||
* while passes find work (or fail) and slows to its idle pace after a pass
|
||||
* that resolved `false`, returning to the base pace once work shows up again.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const { describe, it } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { startBackoffPoll, idleDefault } = require("../lib/backoff-poll");
|
||||
|
||||
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
describe("startBackoffPoll", () => {
|
||||
it("slows down after idle passes and speeds up again on work", async () => {
|
||||
const answers = [true, false, false, true, "x"];
|
||||
const at = [];
|
||||
const t0 = Date.now();
|
||||
const poll = startBackoffPoll(
|
||||
() => {
|
||||
at.push(Date.now() - t0);
|
||||
const a = answers.shift();
|
||||
if (a === "x") throw new Error("boom");
|
||||
return a;
|
||||
},
|
||||
{ baseMs: 10, idleMs: 80 }
|
||||
);
|
||||
await wait(260);
|
||||
poll.stop();
|
||||
assert.ok(at.length >= 5, `ran ${at.length} times`);
|
||||
const gaps = at.slice(1).map((t, i) => t - at[i]);
|
||||
assert.ok(gaps[0] < 60, "work → base pace");
|
||||
assert.ok(gaps[1] >= 75, "idle → idle pace");
|
||||
assert.ok(gaps[2] >= 75, "still idle");
|
||||
assert.ok(gaps[3] < 60, "work again → base pace");
|
||||
});
|
||||
|
||||
it("idles at a minute by default, never faster than the base pace", () => {
|
||||
assert.equal(idleDefault(15_000), 60_000);
|
||||
assert.equal(idleDefault(120_000), 120_000);
|
||||
});
|
||||
});
|
||||
@@ -9,7 +9,9 @@
|
||||
* same account; removing the account takes it out of those homes; and the
|
||||
* Users-page route moves a saved switch-user profile in — the one this
|
||||
* machine's own Claude Code is logged into with its LIVE login, the host's
|
||||
* home then being one more placement the server refreshes.
|
||||
* home then being one more placement the server refreshes. A pin of the
|
||||
* owner to another login waits while a live pane holds the first, until the
|
||||
* admin's switch writes it into the home (never over the member's own login).
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
@@ -188,6 +190,51 @@ describe("a pool login", () => {
|
||||
assert.equal(pool.__read("team"), null);
|
||||
});
|
||||
|
||||
it("follows the owner's pin, and an admin's switch moves the home's login now", async () => {
|
||||
const { db } = require("../db");
|
||||
const pins = require("../lib/account-pins");
|
||||
const miaId = db.prepare("SELECT id FROM users WHERE username = 'mia'").get().id;
|
||||
pool.addLoginAccount("alpha", { oauth: oauth("a"), account: ACCOUNT });
|
||||
pool.addLoginAccount("beta", {
|
||||
oauth: oauth("b"),
|
||||
account: { accountUuid: "uuid-beta", emailAddress: "beta@example.com" },
|
||||
});
|
||||
assert.equal(pool.forSpawn(acct, miaId).name, "alpha", "unpinned: the balancer's pick");
|
||||
pins.setPin(miaId, "claude", "beta");
|
||||
assert.equal(pool.forSpawn(acct, miaId).name, "beta");
|
||||
assert.equal(pool.forSpawn(acct, null).name, "alpha", "another owner is not pinned");
|
||||
// A pane of mia's runs on alpha: beta waits until it ends.
|
||||
pool.forSpawn(acct).place();
|
||||
fs.mkdirSync(path.join(HOME, "proj"), { recursive: true });
|
||||
const lane = db
|
||||
.prepare("INSERT INTO lanes (cwd, owner_id) VALUES (?, ?)")
|
||||
.run(path.join(HOME, "proj"), miaId).lastInsertRowid;
|
||||
db.prepare(
|
||||
`INSERT INTO dashboard_runs (id, mode, cwd, status, started_at, account, lane_id, tool)
|
||||
VALUES ('pin-run', 'interactive', ?, 'running', ?, 'alpha', ?, 'claude')`
|
||||
).run(path.join(HOME, "proj"), new Date().toISOString(), lane);
|
||||
assert.equal(pool.forSpawn(acct, miaId).name, "alpha", "a bare pin waits for the pane");
|
||||
// The admin's switch writes beta into the home now; the pane is not touched.
|
||||
assert.equal(await pins.applyPin(miaId, "claude"), "switched");
|
||||
assert.equal(diskCreds().refreshToken, oauth("b").refreshToken);
|
||||
assert.equal(pool.__read("alpha").placed.mia, undefined, "alpha no longer holds mia's home");
|
||||
assert.equal(pool.forSpawn(acct, miaId).name, "beta");
|
||||
assert.equal(await pins.applyPin(miaId, "claude"), "kept");
|
||||
// Unpinned with the pane still live: the home's login stays, no flip back.
|
||||
pins.setPin(miaId, "claude", null);
|
||||
assert.equal(pool.forSpawn(acct, miaId).name, "beta");
|
||||
// A login the member made themselves is never written over.
|
||||
fs.writeFileSync(CREDS, JSON.stringify({ claudeAiOauth: oauth("own") }));
|
||||
pins.setPin(miaId, "claude", "alpha");
|
||||
assert.equal(await pins.applyPin(miaId, "claude"), "own-login");
|
||||
assert.equal(diskCreds().refreshToken, oauth("own").refreshToken);
|
||||
pins.setPin(miaId, "claude", "beta");
|
||||
pool.removeAccount("beta");
|
||||
assert.equal(pins.pinFor(miaId, "claude"), null, "a removed account drops its pins");
|
||||
db.prepare("DELETE FROM dashboard_runs WHERE id = 'pin-run'").run();
|
||||
db.prepare("DELETE FROM lanes WHERE id = ?").run(lane);
|
||||
});
|
||||
|
||||
it("refuses a second copy of one Claude account", () => {
|
||||
pool.addLoginAccount("team", { oauth: oauth("a"), account: ACCOUNT });
|
||||
assert.throws(() => pool.addLoginAccount("team-2", { oauth: oauth("b"), account: ACCOUNT }), {
|
||||
|
||||
@@ -179,7 +179,9 @@ describe("ingestCodexUsage", () => {
|
||||
});
|
||||
|
||||
it("settles an active session to completed once its journals go quiet", async () => {
|
||||
const now = Date.now();
|
||||
// A whole second: utimes rounds through a float, and a millisecond `now`
|
||||
// came back from stat 1 ms early about half the time.
|
||||
const now = Math.floor(Date.now() / 1000) * 1000;
|
||||
writeRollout(
|
||||
"s1",
|
||||
[meta("s1"), ctx("gpt-a"), tc([1, 0, 1], [1, 0, 1])],
|
||||
@@ -536,3 +538,78 @@ describe("service tier", () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ingestCodexUsage — recent pass", () => {
|
||||
const NOW = Date.parse("2026-09-29T03:00:00Z");
|
||||
function writeAt(day, id, lines, mtime) {
|
||||
const dir = path.join(process.env.CODEX_HOME, "sessions", ...day.split("/"));
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const file = path.join(dir, `rollout-${day.replace(/\//g, "-")}T01-00-00-${id}.jsonl`);
|
||||
fs.writeFileSync(file, jsonl(lines));
|
||||
fs.utimesSync(file, mtime, mtime);
|
||||
return file;
|
||||
}
|
||||
|
||||
it("stats only the newest day folders and the journals still growing", async () => {
|
||||
const quiet = writeAt(
|
||||
"2026/09/01",
|
||||
"old1",
|
||||
[meta("old1"), ctx("gpt-a"), tc([10, 0, 1], [10, 0, 1])],
|
||||
new Date(NOW - 20 * 86_400_000)
|
||||
);
|
||||
const live = writeAt(
|
||||
"2026/09/02",
|
||||
"old2",
|
||||
[meta("old2"), ctx("gpt-a"), tc([10, 0, 1], [10, 0, 1])],
|
||||
new Date(NOW - 60_000)
|
||||
);
|
||||
writeAt("2026/09/27", "a", [meta("a"), ctx("gpt-a")], new Date(NOW - 86_400_000));
|
||||
writeAt("2026/09/28", "b", [meta("b"), ctx("gpt-a")], new Date(NOW - 86_400_000));
|
||||
await ingestCodexUsage({ now: NOW }); // the full first pass
|
||||
|
||||
// Both old journals grow; only the one written within the hour is looked at.
|
||||
fs.appendFileSync(quiet, jsonl([tc([30, 0, 3], [20, 0, 2])]));
|
||||
fs.appendFileSync(live, jsonl([tc([30, 0, 3], [20, 0, 2])]));
|
||||
fs.utimesSync(quiet, new Date(NOW - 1000), new Date(NOW - 1000));
|
||||
fs.utimesSync(live, new Date(NOW - 1000), new Date(NOW - 1000));
|
||||
// A new journal in today's folder is found too.
|
||||
writeAt(
|
||||
"2026/09/29",
|
||||
"new1",
|
||||
[meta("new1"), ctx("gpt-a"), tc([5, 0, 1], [5, 0, 1])],
|
||||
new Date(NOW - 1000)
|
||||
);
|
||||
await ingestCodexUsage({ now: NOW, recent: true });
|
||||
assert.deepEqual(usage("old2"), [{ model: "gpt-a", i: 30, r: 0, o: 3 }]);
|
||||
assert.deepEqual(usage("old1"), [{ model: "gpt-a", i: 10, r: 0, o: 1 }], "left to a full pass");
|
||||
assert.deepEqual(usage("new1"), [{ model: "gpt-a", i: 5, r: 0, o: 1 }]);
|
||||
|
||||
await ingestCodexUsage({ now: NOW }); // the next full pass catches it up
|
||||
assert.deepEqual(usage("old1"), [{ model: "gpt-a", i: 30, r: 0, o: 3 }]);
|
||||
});
|
||||
|
||||
it("finds a fork's parent in an older folder on a recent pass", async () => {
|
||||
const parent = [
|
||||
meta("p9"),
|
||||
ctx("gpt-a"),
|
||||
tc([100, 0, 10], [100, 0, 10]),
|
||||
tc([300, 0, 30], [200, 0, 20]),
|
||||
];
|
||||
writeAt("2026/08/01", "p9", parent, new Date(NOW - 50 * 86_400_000));
|
||||
writeAt("2026/09/28", "x", [meta("x")], new Date(NOW - 86_400_000));
|
||||
await ingestCodexUsage({ now: NOW });
|
||||
writeAt(
|
||||
"2026/09/29",
|
||||
"f9",
|
||||
[
|
||||
meta("f9", { forked_from_id: "p9" }),
|
||||
meta("p9"),
|
||||
...parent.slice(1),
|
||||
tc([350, 0, 35], [50, 0, 5]),
|
||||
],
|
||||
new Date(NOW - 1000)
|
||||
);
|
||||
await ingestCodexUsage({ now: NOW, recent: true });
|
||||
assert.deepEqual(usage("f9"), [{ model: "gpt-a", i: 50, r: 0, o: 5 }]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* @file Tests server/lib/db-retention.js and its Settings routes — a new
|
||||
* database is INCREMENTAL auto_vacuum, retention is off by default and purges
|
||||
* nothing then, when on it removes only finished sessions older than the
|
||||
* cutoff (with their events, agents and token rows) in bounded batches, the
|
||||
* free-page reclaim shrinks the freelist, GET/PUT /api/settings/retention
|
||||
* validate and persist the setting, and POST /api/settings/compact needs
|
||||
* confirm and runs a VACUUM in a worker. The database and settings file are
|
||||
* temp paths.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const os = require("node:os");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const { describe, it, before, after } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
|
||||
const ROOT = fs.mkdtempSync(path.join(os.tmpdir(), "agenthub-db-retention-"));
|
||||
process.env.DASHBOARD_DB_PATH = path.join(ROOT, "dashboard.db");
|
||||
process.env.AGENTHUB_SETTINGS_FILE = path.join(ROOT, "settings.env");
|
||||
process.env.DASHBOARD_LIVENESS_PROBE = "0";
|
||||
delete process.env.AGENTHUB_RETENTION_DAYS;
|
||||
|
||||
const { createApp, startServer } = require("../index");
|
||||
const { db } = require("../db");
|
||||
const retention = require("../lib/db-retention");
|
||||
|
||||
let server;
|
||||
let BASE;
|
||||
before(async () => {
|
||||
server = await startServer(createApp(), 0);
|
||||
BASE = `http://127.0.0.1:${server.address().port}`;
|
||||
});
|
||||
after(() => {
|
||||
server?.close();
|
||||
delete process.env.AGENTHUB_RETENTION_DAYS;
|
||||
fs.rmSync(ROOT, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function call(method, urlPath, body) {
|
||||
const res = await fetch(BASE + urlPath, {
|
||||
method,
|
||||
headers: body ? { "content-type": "application/json" } : {},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
return { status: res.status, body: await res.json() };
|
||||
}
|
||||
|
||||
const daysAgo = (n) => new Date(Date.now() - n * 86400 * 1000).toISOString();
|
||||
|
||||
function seed(id, status, startedAt, events = 3) {
|
||||
db.prepare(
|
||||
"INSERT INTO sessions (id, name, status, cwd, started_at, updated_at) VALUES (?, ?, ?, '/tmp', ?, ?)"
|
||||
).run(id, id, status, startedAt, startedAt);
|
||||
const ins = db.prepare(
|
||||
"INSERT INTO events (session_id, event_type, summary, data, created_at) VALUES (?, 'PostToolUse', 's', ?, ?)"
|
||||
);
|
||||
for (let i = 0; i < events; i++)
|
||||
ins.run(id, JSON.stringify({ pad: "x".repeat(2000) }), startedAt);
|
||||
}
|
||||
const exists = (id) => !!db.prepare("SELECT 1 FROM sessions WHERE id = ?").get(id);
|
||||
const eventCount = (id) =>
|
||||
db.prepare("SELECT COUNT(*) AS n FROM events WHERE session_id = ?").get(id).n;
|
||||
|
||||
describe("auto_vacuum", () => {
|
||||
it("a new database is INCREMENTAL", () => {
|
||||
assert.equal(db.pragma("auto_vacuum", { simple: true }), 2);
|
||||
assert.equal(retention.spaceInfo(db).auto_vacuum, "incremental");
|
||||
});
|
||||
});
|
||||
|
||||
describe("retentionConfig", () => {
|
||||
it("is off by default and for anything out of range", () => {
|
||||
assert.equal(retention.retentionConfig({}).days, 0);
|
||||
for (const v of ["", "0", "-3", "1.5", "abc", "99999"]) {
|
||||
assert.equal(retention.retentionConfig({ AGENTHUB_RETENTION_DAYS: v }).days, 0, v);
|
||||
}
|
||||
assert.equal(retention.retentionConfig({ AGENTHUB_RETENTION_DAYS: "30" }).days, 30);
|
||||
});
|
||||
});
|
||||
|
||||
describe("scheduled maintenance", () => {
|
||||
it("purges nothing while retention is off", async () => {
|
||||
seed("ret-off-old", "completed", daysAgo(400));
|
||||
const out = await retention.runScheduledMaintenance({ db });
|
||||
assert.equal(out.retention, undefined);
|
||||
assert.ok(exists("ret-off-old"));
|
||||
db.prepare("DELETE FROM sessions WHERE id = 'ret-off-old'").run();
|
||||
});
|
||||
|
||||
it("purges only finished sessions older than the cutoff, with their rows", async () => {
|
||||
seed("ret-old-done", "completed", daysAgo(100));
|
||||
seed("ret-old-err", "error", daysAgo(100));
|
||||
seed("ret-old-active", "active", daysAgo(100));
|
||||
seed("ret-new-done", "completed", daysAgo(5));
|
||||
db.prepare(
|
||||
"INSERT INTO token_usage (session_id, model, input_tokens) VALUES ('ret-old-done', 'm', 1)"
|
||||
).run();
|
||||
process.env.AGENTHUB_RETENTION_DAYS = "30";
|
||||
try {
|
||||
const out = await retention.runScheduledMaintenance({ db });
|
||||
assert.equal(out.retention.purged_sessions, 2);
|
||||
assert.equal(out.retention.purged_events, 6);
|
||||
} finally {
|
||||
delete process.env.AGENTHUB_RETENTION_DAYS;
|
||||
}
|
||||
assert.ok(!exists("ret-old-done"));
|
||||
assert.ok(!exists("ret-old-err"));
|
||||
assert.equal(eventCount("ret-old-done"), 0);
|
||||
assert.equal(
|
||||
db.prepare("SELECT COUNT(*) AS n FROM token_usage WHERE session_id = 'ret-old-done'").get().n,
|
||||
0
|
||||
);
|
||||
assert.ok(exists("ret-old-active"), "an active session is never purged");
|
||||
assert.ok(exists("ret-new-done"), "a recent session is kept");
|
||||
assert.equal(eventCount("ret-new-done"), 3);
|
||||
});
|
||||
|
||||
it("works in bounded batches and stops at the per-run cap", async () => {
|
||||
for (let i = 0; i < 7; i++) seed(`ret-batch-${i}`, "abandoned", daysAgo(50), 1);
|
||||
const first = await retention.applyRetention({ db, days: 10, batch: 2, maxSessions: 5 });
|
||||
assert.equal(first.purged_sessions, 5);
|
||||
const second = await retention.applyRetention({ db, days: 10, batch: 2, maxSessions: 5 });
|
||||
assert.equal(second.purged_sessions, 2);
|
||||
const third = await retention.applyRetention({ db, days: 10 });
|
||||
assert.equal(third.purged_sessions, 0);
|
||||
});
|
||||
|
||||
it("returns free pages to the OS", async () => {
|
||||
for (let i = 0; i < 40; i++) seed(`ret-big-${i}`, "completed", daysAgo(60), 20);
|
||||
await retention.applyRetention({ db, days: 30 });
|
||||
const before = db.pragma("freelist_count", { simple: true });
|
||||
assert.ok(before > 50, `expected free pages, got ${before}`);
|
||||
const out = await retention.reclaimFreePages({ db, minPages: 10, slice: 16 });
|
||||
assert.ok(out.reclaimed_pages > 0);
|
||||
assert.ok(db.pragma("freelist_count", { simple: true }) < before);
|
||||
});
|
||||
});
|
||||
|
||||
describe("routes", () => {
|
||||
it("GET reports retention off by default", async () => {
|
||||
const r = await call("GET", "/api/settings/retention");
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(r.body.days, 0);
|
||||
assert.equal(r.body.compacting, false);
|
||||
assert.equal(r.body.space.auto_vacuum, "incremental");
|
||||
});
|
||||
|
||||
it("PUT validates and persists, 0 turns it off", async () => {
|
||||
for (const bad of [-1, 1.5, "7", 99999, null]) {
|
||||
const r = await call("PUT", "/api/settings/retention", { days: bad });
|
||||
assert.equal(r.status, 400, String(bad));
|
||||
}
|
||||
let r = await call("PUT", "/api/settings/retention", { days: 90 });
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(r.body.days, 90);
|
||||
assert.match(fs.readFileSync(process.env.AGENTHUB_SETTINGS_FILE, "utf8"), /RETENTION_DAYS=90/);
|
||||
r = await call("PUT", "/api/settings/retention", { days: 0 });
|
||||
assert.equal(r.body.days, 0);
|
||||
});
|
||||
|
||||
it("POST /compact needs confirm and then vacuums", async () => {
|
||||
let r = await call("POST", "/api/settings/compact", {});
|
||||
assert.equal(r.status, 400);
|
||||
r = await call("POST", "/api/settings/compact", { confirm: true });
|
||||
assert.equal(r.status, 202);
|
||||
for (let i = 0; i < 200 && retention.isCompacting(); i++) {
|
||||
await new Promise((res) => setTimeout(res, 50));
|
||||
}
|
||||
const last = retention.lastCompactResult();
|
||||
assert.equal(last?.ok, true, last?.error);
|
||||
assert.equal(db.pragma("auto_vacuum", { simple: true }), 2);
|
||||
});
|
||||
});
|
||||
@@ -181,12 +181,16 @@ describe("lane-sources instructions and launch", () => {
|
||||
assert.equal(lanesLib.getLane(lane.id).instructions, "- always answer in Vietnamese");
|
||||
});
|
||||
|
||||
it("starts a claude pane with --add-dir first and the instructions from a file", () => {
|
||||
it("starts a claude pane with --add-dir first and the instructions as a CLAUDE.md there", () => {
|
||||
let argv = null;
|
||||
let newSession = null;
|
||||
tmux.__setExecImpl((args) => {
|
||||
if (args[0] === "has-session") throw Object.assign(new Error("gone"), { status: 1 });
|
||||
// The CLI rides behind `sh -c <cd; wait for a client> sh <cwd>` (pty-run.js).
|
||||
if (args[0] === "new-session") argv = args.slice(args.indexOf("--") + 6);
|
||||
if (args[0] === "new-session") {
|
||||
newSession = args;
|
||||
argv = args.slice(args.indexOf("--") + 6);
|
||||
}
|
||||
return "";
|
||||
});
|
||||
pty.spawnRun({ laneId: lane.id, cwd: ws, initialPrompt: "-c fix it" });
|
||||
@@ -194,11 +198,15 @@ describe("lane-sources instructions and launch", () => {
|
||||
assert.equal(argv[0], "claude");
|
||||
assert.equal(argv[1], "--add-dir");
|
||||
assert.deepEqual(argv.slice(2, 4), [extra, src.contextDir(lane.id)]);
|
||||
assert.equal(argv[4], "--permission-mode");
|
||||
const flag = argv.find((a) => a.startsWith("--append-system-prompt-file="));
|
||||
const file = flag.slice("--append-system-prompt-file=".length);
|
||||
assert.ok(file.startsWith(process.env.DASHBOARD_DATA_DIR));
|
||||
const text = fs.readFileSync(file, "utf8");
|
||||
// The instructions' own folder, read as memory: a custom system prompt
|
||||
// (`--append-system-prompt-file`) made Claude refuse `/tui` in the pane.
|
||||
const dir = argv[4];
|
||||
assert.ok(dir.startsWith(process.env.DASHBOARD_DATA_DIR));
|
||||
assert.equal(argv[5], "--permission-mode");
|
||||
assert.ok(!argv.some((a) => a.startsWith("--append-system-prompt")));
|
||||
assert.ok(newSession.includes("CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1"));
|
||||
assert.deepEqual(fs.readdirSync(dir), ["CLAUDE.md"]);
|
||||
const text = fs.readFileSync(path.join(dir, "CLAUDE.md"), "utf8");
|
||||
assert.match(text, /^- always answer in Vietnamese/);
|
||||
assert.match(text, /pass wd\.md/);
|
||||
// A prompt that looks like flags stays one positional, never `claude -c`.
|
||||
|
||||
@@ -91,6 +91,69 @@ describe("node version gate", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("last failure report (SessionStart systemMessage)", () => {
|
||||
beforeEach(resetRuntime);
|
||||
|
||||
it("reports a recorded failure once, naming the log and /agenthub-doctor", () => {
|
||||
boot.recordFailure(RT, "install-failed", "npm broke", path.join(RT, "npm-install.log"));
|
||||
const first = boot.takeFailureReport(RT);
|
||||
assert.match(first.systemMessage, /npm broke/);
|
||||
assert.match(first.systemMessage, /npm-install\.log/);
|
||||
assert.match(first.systemMessage, /\/agenthub-doctor/);
|
||||
assert.equal(boot.takeFailureReport(RT), null);
|
||||
});
|
||||
|
||||
it("does not re-report the same failure recorded again by a later retry", () => {
|
||||
boot.recordFailure(RT, "install-failed", "npm broke", "x.log");
|
||||
boot.takeFailureReport(RT);
|
||||
boot.recordFailure(RT, "install-failed", "npm broke", "x.log");
|
||||
assert.equal(boot.takeFailureReport(RT), null);
|
||||
});
|
||||
|
||||
it("reports a different failure, and nothing once cleared", () => {
|
||||
boot.recordFailure(RT, "install-failed", "npm broke", "x.log");
|
||||
boot.takeFailureReport(RT);
|
||||
boot.recordFailure(RT, "ui-build-failed", "vite broke", "y.log");
|
||||
assert.match(boot.takeFailureReport(RT).systemMessage, /vite broke/);
|
||||
boot.recordFailure(RT, "ui-build-failed", "vite broke", "y.log");
|
||||
boot.clearFailure(RT);
|
||||
assert.equal(boot.readFailure(RT), null);
|
||||
assert.equal(boot.takeFailureReport(RT), null);
|
||||
});
|
||||
|
||||
it("prints nothing with no failure on record", () => {
|
||||
assert.equal(boot.takeFailureReport(RT), null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("depsHash — only what npm installs", () => {
|
||||
function root(pkg, lock) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "agenthub-deps-"));
|
||||
fs.writeFileSync(path.join(dir, "package.json"), JSON.stringify(pkg));
|
||||
fs.writeFileSync(path.join(dir, "package-lock.json"), JSON.stringify(lock));
|
||||
return dir;
|
||||
}
|
||||
const pkg = (version, deps) => ({ name: "agenthub", version, dependencies: deps });
|
||||
const lock = (version, deps) => ({
|
||||
name: "agenthub",
|
||||
version,
|
||||
packages: { "": { name: "agenthub", version, dependencies: deps }, "node_modules/a": {} },
|
||||
});
|
||||
|
||||
it("ignores a release's version bump", () => {
|
||||
// Every update reinstalled all runtime dependencies when only the version moved.
|
||||
const a = root(pkg("1.0.0", { a: "^1" }), lock("1.0.0", { a: "^1" }));
|
||||
const b = root(pkg("1.0.1", { a: "^1" }), lock("1.0.1", { a: "^1" }));
|
||||
assert.equal(boot.depsHash(a), boot.depsHash(b));
|
||||
});
|
||||
|
||||
it("changes when a dependency does", () => {
|
||||
const a = root(pkg("1.0.0", { a: "^1" }), lock("1.0.0", { a: "^1" }));
|
||||
const b = root(pkg("1.0.0", { a: "^2" }), lock("1.0.0", { a: "^2" }));
|
||||
assert.notEqual(boot.depsHash(a), boot.depsHash(b));
|
||||
});
|
||||
});
|
||||
|
||||
describe("fast path", () => {
|
||||
beforeEach(resetRuntime);
|
||||
|
||||
@@ -527,7 +590,6 @@ describe("buildClient dependency install", () => {
|
||||
assert.deepEqual(calls, [
|
||||
"ci --no-audit --no-fund --include=dev --ignore-scripts",
|
||||
"install --no-audit --no-fund --include=dev --ignore-scripts",
|
||||
"node tsc -b",
|
||||
"node vite.js build",
|
||||
]);
|
||||
});
|
||||
@@ -567,8 +629,9 @@ describe("buildClient dependency install", () => {
|
||||
it("builds with the running node, no lifecycle script and no PATH lookup (Windows)", () => {
|
||||
// On Windows a script or a .bin shim runs through cmd.exe and needs `node`
|
||||
// on PATH; the server's PATH lacked it, so esbuild's postinstall failed and
|
||||
// every update kept the previous UI. The build here must equal the
|
||||
// client's own "build" script, run without npm.
|
||||
// every update kept the previous UI. The build here is the vite half of
|
||||
// the client's own "build" script, run without npm; the type check is the
|
||||
// release's job, not every user's.
|
||||
assert.equal(
|
||||
JSON.parse(fs.readFileSync(path.join(__dirname, "..", "..", "client", "package.json")))
|
||||
.scripts.build,
|
||||
@@ -577,8 +640,35 @@ describe("buildClient dependency install", () => {
|
||||
resetRuntime();
|
||||
const calls = [];
|
||||
buildClient({ rt: RT, root: fakeRoot(), exec: fakeExec(calls) });
|
||||
assert.deepEqual(calls.slice(-2), ["node tsc -b", "node vite.js build"]);
|
||||
assert.ok(calls.every((c) => !c.startsWith("run")));
|
||||
assert.deepEqual(calls.slice(-1), ["node vite.js build"]);
|
||||
assert.ok(calls.every((c) => !c.startsWith("run") && !c.includes("tsc")));
|
||||
});
|
||||
|
||||
it("keeps the installed tree while the client's manifests are unchanged", () => {
|
||||
resetRuntime();
|
||||
const root = fakeRoot();
|
||||
const first = [];
|
||||
buildClient({ rt: RT, root, exec: fakeExec(first) });
|
||||
assert.ok(first[0].startsWith("ci"));
|
||||
const again = [];
|
||||
assert.equal(buildClient({ rt: RT, root, force: true, exec: fakeExec(again) }), "built");
|
||||
assert.deepEqual(again, ["node vite.js build"]);
|
||||
|
||||
fs.writeFileSync(path.join(root, "client", "package.json"), '{"dependencies":{"x":"1"}}');
|
||||
const changed = [];
|
||||
buildClient({ rt: RT, root, force: true, exec: fakeExec(changed) });
|
||||
assert.ok(changed[0].startsWith("ci"), "a changed manifest installs from clean");
|
||||
});
|
||||
|
||||
it("installs from clean again after a build on the kept tree failed", () => {
|
||||
resetRuntime();
|
||||
const root = fakeRoot();
|
||||
buildClient({ rt: RT, root, exec: fakeExec([]) });
|
||||
const failing = (cmd, args, cwd) => (cmd === "node" ? false : fakeExec([])(cmd, args, cwd));
|
||||
assert.equal(buildClient({ rt: RT, root, force: true, exec: failing }), "failed");
|
||||
const next = [];
|
||||
buildClient({ rt: RT, root, force: true, exec: fakeExec(next) });
|
||||
assert.ok(next[0].startsWith("ci"));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -204,6 +204,45 @@ describe("pty-attach", () => {
|
||||
assert.deepEqual(JSON.parse(a.__sent.at(-1).data), { type: "lead" });
|
||||
});
|
||||
|
||||
it("survives a stopped pane: pipe errors, typing and resizes after the attach exited", () => {
|
||||
// Windows node-pty re-throws a read-pipe error nobody listens for, and its
|
||||
// write pipe has no listener at all: Stop (kill-session) ended the attach
|
||||
// with EPIPE and the uncaught error killed the whole dashboard.
|
||||
const ptys = [];
|
||||
ptyAttach.__setSpawnImpl(() => {
|
||||
const p = makeFakePty();
|
||||
p.on = (evt, fn) => p.__emitter.on(evt, fn);
|
||||
p._agent = { inSocket: new EventEmitter() };
|
||||
p.resize = () => {
|
||||
if (p.__gone) throw new Error("Cannot resize a pty that has already exited");
|
||||
};
|
||||
p.write = () => {
|
||||
if (p.__gone) throw new Error("write EPIPE");
|
||||
};
|
||||
ptys.push(p);
|
||||
return p;
|
||||
});
|
||||
const a = makeFakeWs();
|
||||
const b = makeFakeWs();
|
||||
a.close = b.close = () => {};
|
||||
ptyAttach.attach(a, "agenthub-lane-1", { cols: 80, rows: 24 });
|
||||
ptyAttach.attach(b, "agenthub-lane-1", { cols: 80, rows: 24 });
|
||||
|
||||
const epipe = Object.assign(new Error("read EPIPE"), { code: "EPIPE" });
|
||||
assert.doesNotThrow(() => ptys[0].__emitter.emit("error", epipe));
|
||||
assert.doesNotThrow(() => ptys[0]._agent.inSocket.emit("error", epipe));
|
||||
|
||||
ptys[0].__gone = true;
|
||||
ptys[0].__emitter.emit("exit", { exitCode: 1 }); // a's close event not yet in
|
||||
const msg = (ws, data, binary) => ws.__emitter.emit("message", Buffer.from(data), { binary });
|
||||
assert.doesNotThrow(() =>
|
||||
msg(b, JSON.stringify({ type: "resize", cols: 90, rows: 30, drive: true }), false)
|
||||
);
|
||||
assert.doesNotThrow(() => msg(a, "x", true));
|
||||
ptys[1].__gone = true; // exited, onExit still queued
|
||||
assert.doesNotThrow(() => msg(b, "y", true));
|
||||
});
|
||||
|
||||
it("kills the PTY attach process when the WS connection closes", () => {
|
||||
const ws = makeFakeWs();
|
||||
ptyAttach.attach(ws, "agenthub-lane-1", { cols: 80, rows: 24 });
|
||||
|
||||
@@ -50,6 +50,8 @@ function trackedFiles() {
|
||||
// Generated from server/openapi-extra/* (which IS linted): the drift test
|
||||
// below covers it, so linting both would only double-report one fix.
|
||||
.filter((f) => f !== "openapi.yaml" && !f.endsWith("package-lock.json"))
|
||||
// Third-party files copied unchanged (server/vendor/redoc): their links are upstream's.
|
||||
.filter((f) => !f.includes("/vendor/"))
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* @file runtime-deps.test.js
|
||||
* @description Every package the server code requires is a runtime dependency.
|
||||
* A plugin install runs `npm install --omit=dev`, so a package listed only in
|
||||
* devDependencies — or one that arrived only as some other package's
|
||||
* dependency — is missing there. v2.8.9 crashed at start on every plugin
|
||||
* install: `js-yaml` (server/lib/lane-detect.js) was a devDependency that
|
||||
* `redoc` used to pull in, and dropping `redoc` took it away. Machines with
|
||||
* Debian's global /usr/share/nodejs never saw it, so this checks the manifest
|
||||
* instead of trusting a local `require` to fail.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const { describe, it } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const { builtinModules } = require("node:module");
|
||||
|
||||
const ROOT = path.join(__dirname, "..", "..");
|
||||
const pkg = require(path.join(ROOT, "package.json"));
|
||||
|
||||
// Required only behind a runtime check, never on a plain Node server.
|
||||
const GUARDED = new Set(["electron"]);
|
||||
|
||||
function sourceFiles(dir) {
|
||||
const out = [];
|
||||
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = path.join(dir, e.name);
|
||||
if (e.isDirectory()) {
|
||||
if (!["node_modules", "__tests__", "vendor"].includes(e.name)) out.push(...sourceFiles(p));
|
||||
} else if (/\.(c?js|mjs)$/.test(e.name)) out.push(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Bare package names `file` requires, comments left out. */
|
||||
function requiredPackages(file) {
|
||||
const code = fs
|
||||
.readFileSync(file, "utf8")
|
||||
.replace(/\/\*[\s\S]*?\*\//g, "")
|
||||
.replace(/(^|[^:"'`\\])\/\/.*$/gm, "$1");
|
||||
const names = new Set();
|
||||
for (const m of code.matchAll(/\brequire\(\s*["']([^"'./][^"']*)["']\s*\)/g)) {
|
||||
const spec = m[1];
|
||||
if (spec.startsWith("node:")) continue;
|
||||
const name = spec.startsWith("@") ? spec.split("/").slice(0, 2).join("/") : spec.split("/")[0];
|
||||
if (!builtinModules.includes(name)) names.add(name);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
describe("runtime dependencies", () => {
|
||||
it("every package server/ requires is in dependencies or optionalDependencies", () => {
|
||||
const runtime = new Set([
|
||||
...Object.keys(pkg.dependencies || {}),
|
||||
...Object.keys(pkg.optionalDependencies || {}),
|
||||
]);
|
||||
const missing = [];
|
||||
for (const file of sourceFiles(path.join(ROOT, "server"))) {
|
||||
for (const name of requiredPackages(file)) {
|
||||
if (!runtime.has(name) && !GUARDED.has(name))
|
||||
missing.push(`${path.relative(ROOT, file)}: ${name}`);
|
||||
}
|
||||
}
|
||||
assert.deepEqual(missing, []);
|
||||
});
|
||||
});
|
||||
@@ -3,12 +3,17 @@
|
||||
* @description After an update, a server our service unit runs is restarted
|
||||
* by the unit, never by a detached replacement: v2.7.2 on the S3 system unit
|
||||
* left the replacement holding the port while `Restart=always` started the
|
||||
* unit every 3 s, each start exiting "already running".
|
||||
* unit every 3 s, each start exiting "already running". Without a unit, the
|
||||
* detached helper's replacement server logs to `data/agenthub-server.log`.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const { describe, it } = 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 { execFileSync } = require("node:child_process");
|
||||
const { scheduleRestart, owningUnit } = require("../lib/self-restart");
|
||||
|
||||
function deps(unit, restartAnswer = "restarted") {
|
||||
@@ -23,8 +28,9 @@ function deps(unit, restartAnswer = "restarted") {
|
||||
},
|
||||
}),
|
||||
kill: () => calls.kill++,
|
||||
spawnHelper: () => {
|
||||
spawnHelper: (_exe, args) => {
|
||||
calls.spawn++;
|
||||
calls.helperArgs = args;
|
||||
return { unref() {} };
|
||||
},
|
||||
};
|
||||
@@ -84,5 +90,27 @@ describe("self-restart", () => {
|
||||
assert.equal(scheduleRestart("/r", d), "helper");
|
||||
assert.equal(d.calls.spawn, 1);
|
||||
assert.equal(d.calls.kill, 1);
|
||||
// The new server logs where `agenthub start` does — never into nothing.
|
||||
assert.equal(d.calls.helperArgs.at(-1), path.join("/r", "data", "agenthub-server.log"));
|
||||
});
|
||||
|
||||
it("restart-helper appends the new server's stdout and stderr to the log", async () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "restart-helper-"));
|
||||
const entry = path.join(dir, "entry.js");
|
||||
const log = path.join(dir, "data", "agenthub-server.log");
|
||||
fs.writeFileSync(entry, 'console.log("up"); throw new Error("boom");\n');
|
||||
const helper = path.join(__dirname, "..", "..", "scripts", "restart-helper.js");
|
||||
// pid 0x7fffffff is never alive, so the helper restarts at once.
|
||||
execFileSync(process.execPath, [helper, "2147483647", entry, log]);
|
||||
const deadline = Date.now() + 5000;
|
||||
let text = "";
|
||||
while (Date.now() < deadline && !/boom/.test(text)) {
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
text = fs.existsSync(log) ? fs.readFileSync(log, "utf8") : "";
|
||||
}
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
assert.match(text, /restart-helper: old server 2147483647 gone/);
|
||||
assert.match(text, /^up$/m);
|
||||
assert.match(text, /Error: boom/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
* admin may add or remove an account, each change needs the admin's OWN
|
||||
* password again (EREAUTH), the token only goes in — no answer (the add, the
|
||||
* list) ever carries it — the audit log names the account, not its secret, and
|
||||
* in local mode the routes refuse.
|
||||
* in local mode the routes refuse. An admin pins a user to one account
|
||||
* (`PUT /api/accounts/pins`): that user's new panes skip the balancer.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
@@ -144,3 +145,112 @@ describe("the account pool from the Users page", () => {
|
||||
assert.ok(claudePool.pickAccount(), "team-1 is still there");
|
||||
});
|
||||
});
|
||||
|
||||
describe("pinning a user to one account", () => {
|
||||
const pins = require("../lib/account-pins");
|
||||
const pin = (cookie, body) =>
|
||||
call("PUT", "/api/accounts/pins", {
|
||||
cookie,
|
||||
body: { tool: "claude", currentPassword: BOSS_PASS, ...body },
|
||||
});
|
||||
|
||||
it("lets an admin pin and unpin, audited, and new panes follow the pin", async () => {
|
||||
const boss = await login("boss", BOSS_PASS);
|
||||
const miaId = db.prepare("SELECT id FROM users WHERE username = 'mia'").get().id;
|
||||
claudePool.addAccount("team-z", `sk-ant-oat01-${"z".repeat(40)}`);
|
||||
assert.equal(claudePool.pickAccount(null, miaId).name, "team-1", "the balancer's pick");
|
||||
const r = await pin(boss, { userId: miaId, account: "team-z" });
|
||||
assert.equal(r.status, 200);
|
||||
assert.deepEqual(r.body.pin, { userId: miaId, username: "mia", account: "team-z" });
|
||||
assert.equal(r.body.switched, "next-session", "a setup-token goes in at the next spawn");
|
||||
assert.equal(claudePool.pickAccount(null, miaId).name, "team-z");
|
||||
assert.equal(claudePool.pickAccount(null, null).name, "team-1", "nobody else moves");
|
||||
const audit = db.prepare("SELECT owner_id, path FROM audit_log ORDER BY id DESC LIMIT 1").get();
|
||||
assert.equal(audit.owner_id, miaId);
|
||||
assert.match(audit.path, /pin mia to claude account team-z/);
|
||||
const list = await call("GET", "/api/accounts", { cookie: boss });
|
||||
assert.deepEqual(
|
||||
list.body.pins.claude.map((p) => [p.username, p.account]),
|
||||
[["mia", "team-z"]]
|
||||
);
|
||||
assert.deepEqual(list.body.pins.codex, []);
|
||||
const off = await pin(boss, { userId: miaId, account: null });
|
||||
assert.equal(off.body.pin.account, null);
|
||||
assert.equal(claudePool.pickAccount(null, miaId).name, "team-1");
|
||||
claudePool.removeAccount("team-z");
|
||||
});
|
||||
|
||||
it("refuses an unknown account or user, a wrong password, and a non-admin", async () => {
|
||||
const boss = await login("boss", BOSS_PASS);
|
||||
const miaId = db.prepare("SELECT id FROM users WHERE username = 'mia'").get().id;
|
||||
assert.equal(
|
||||
(await pin(boss, { userId: miaId, account: "nope" })).body.error.code,
|
||||
"ENOACCOUNT"
|
||||
);
|
||||
assert.equal((await pin(boss, { userId: 9999, account: "team-1" })).body.error.code, "ENOUSER");
|
||||
assert.equal(
|
||||
(await pin(boss, { userId: miaId, account: "team-1", currentPassword: "x" })).body.error.code,
|
||||
"EREAUTH"
|
||||
);
|
||||
const ana = await login("ana", "analyst-pass-1");
|
||||
const w = await call("PUT", "/api/accounts/pins", {
|
||||
cookie: ana,
|
||||
body: { tool: "claude", userId: miaId, account: "team-1", currentPassword: "analyst-pass-1" },
|
||||
});
|
||||
assert.equal(w.status, 403);
|
||||
assert.equal(pins.pinFor(miaId, "claude"), null);
|
||||
});
|
||||
|
||||
it("sets exactly who runs on one account from its Edit", async () => {
|
||||
const boss = await login("boss", BOSS_PASS);
|
||||
const id = (name) => db.prepare("SELECT id FROM users WHERE username = ?").get(name).id;
|
||||
claudePool.addAccount("team-y", `sk-ant-oat01-${"y".repeat(40)}`);
|
||||
pins.setPin(id("ana"), "claude", "team-1");
|
||||
const edit = (account, userIds, extra = {}) =>
|
||||
call("PUT", `/api/accounts/${account}/users`, {
|
||||
cookie: boss,
|
||||
body: { tool: "claude", userIds, currentPassword: BOSS_PASS, ...extra },
|
||||
});
|
||||
const r = await edit("team-y", [id("mia"), id("ana")]);
|
||||
assert.equal(r.status, 200);
|
||||
assert.deepEqual(r.body.added.map((u) => [u.username, u.switched]).sort(), [
|
||||
["ana", "next-session"],
|
||||
["mia", "next-session"],
|
||||
]);
|
||||
assert.equal(pins.pinFor(id("ana"), "claude"), "team-y", "moved off team-1");
|
||||
const again = await edit("team-y", [id("mia")]);
|
||||
assert.deepEqual(again.body.added, []);
|
||||
assert.deepEqual(
|
||||
again.body.removed.map((u) => u.username),
|
||||
["ana"]
|
||||
);
|
||||
assert.equal(pins.pinFor(id("ana"), "claude"), null);
|
||||
assert.equal(pins.pinFor(id("mia"), "claude"), "team-y");
|
||||
const audit = db.prepare("SELECT path FROM audit_log ORDER BY id DESC LIMIT 1").get();
|
||||
assert.match(audit.path, /unpin ana from claude/);
|
||||
assert.equal((await edit("team-y", [9999])).body.error.code, "ENOUSER");
|
||||
assert.equal((await edit("team-y", "x")).body.error.code, "EBADUSER");
|
||||
assert.equal((await edit("nope", [])).body.error.code, "ENOACCOUNT");
|
||||
assert.equal((await edit("team-y", [], { currentPassword: "x" })).body.error.code, "EREAUTH");
|
||||
assert.equal(pins.pinFor(id("mia"), "claude"), "team-y", "a refused edit changes nothing");
|
||||
await edit("team-y", []);
|
||||
claudePool.removeAccount("team-y");
|
||||
});
|
||||
|
||||
it("is ignored in local mode and dropped with its user", async () => {
|
||||
const miaId = db.prepare("SELECT id FROM users WHERE username = 'mia'").get().id;
|
||||
pins.setPin(miaId, "claude", "team-1");
|
||||
delete process.env.AGENTHUB_MODE;
|
||||
try {
|
||||
assert.equal(pins.pinFor(miaId, "claude"), null);
|
||||
} finally {
|
||||
process.env.AGENTHUB_MODE = "server";
|
||||
}
|
||||
assert.equal(pins.pinFor(miaId, "claude"), "team-1");
|
||||
db.prepare("DELETE FROM users WHERE id = ?").run(miaId);
|
||||
assert.equal(
|
||||
db.prepare("SELECT COUNT(*) AS n FROM account_pins WHERE user_id = ?").get(miaId).n,
|
||||
0
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -114,7 +114,7 @@ describe("a member pane's files live in the member's handoff dir", () => {
|
||||
assert.deepEqual(x.addDirs, [ctx]);
|
||||
assert.equal(fs.readFileSync(path.join(ctx, "spec.md"), "utf8"), "# spec\n");
|
||||
assert.equal(mode(path.join(ctx, "spec.md")), 0o644);
|
||||
assert.equal(x.systemPromptFile, path.join(HANDOFF, `prompt-${laneId}.md`));
|
||||
assert.equal(x.systemPromptFile, path.join(HANDOFF, `prompt-${laneId}`, "CLAUDE.md"));
|
||||
assert.equal(mode(x.systemPromptFile), 0o644);
|
||||
const text = fs.readFileSync(x.systemPromptFile, "utf8");
|
||||
assert.match(text, /Be brief\./);
|
||||
|
||||
@@ -150,3 +150,85 @@ describe("syncDefaultProjects", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("syncDefaultProjects — sessions hooks are feeding", () => {
|
||||
const SNAP_DIR = path.join(process.env.DASHBOARD_DATA_DIR, "transcripts");
|
||||
const more = (sessionId, cwd, ts) => ({
|
||||
type: "assistant",
|
||||
cwd,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
message: {
|
||||
model: "claude-opus-4-8",
|
||||
content: [{ type: "text", text: "later" }],
|
||||
usage: { input_tokens: 3, output_tokens: 2 },
|
||||
},
|
||||
});
|
||||
const bumpMtime = (file) => {
|
||||
const future = Date.now() / 1000 + 120;
|
||||
fs.utimesSync(file, future, future);
|
||||
};
|
||||
const ageSession = (id) =>
|
||||
dbModule.db
|
||||
.prepare("UPDATE sessions SET updated_at = ? WHERE id = ?")
|
||||
.run(new Date(Date.now() - 10 * 60_000).toISOString(), id);
|
||||
|
||||
it("defers a live hook-fed imported session, then catches it up once quiet", async () => {
|
||||
const ID = "33333333-cccc-4ccc-8ccc-333333333333";
|
||||
const cache = new Map();
|
||||
const file = writeSession("-live", ID, fixtureLines(ID, "/live"));
|
||||
await syncDefaultProjects(dbModule, { mtimeCache: cache });
|
||||
assert.ok(dbModule.stmts.getSession.get(ID), "imported first");
|
||||
|
||||
// A hook arrives: its event is the newest, and it touches the session.
|
||||
dbModule.stmts.insertEvent.run(ID, `${ID}-main`, "PreToolUse", "Bash", "hook", "{}");
|
||||
dbModule.stmts.touchSession.run(ID);
|
||||
writeSession(
|
||||
"-live",
|
||||
ID,
|
||||
fixtureLines(ID, "/live", [more(ID, "/live", "2026-04-18T12:09:00.000Z")])
|
||||
);
|
||||
bumpMtime(file);
|
||||
|
||||
const live = await syncDefaultProjects(dbModule, { mtimeCache: cache });
|
||||
assert.equal(
|
||||
live.changed.find((c) => c.sessionId === ID),
|
||||
undefined,
|
||||
"deferred while live"
|
||||
);
|
||||
assert.equal(cache.get(file), -1, "kept in the cache so the watcher ignores its appends");
|
||||
|
||||
ageSession(ID); // the hooks went quiet
|
||||
const quiet = await syncDefaultProjects(dbModule, { mtimeCache: cache });
|
||||
assert.ok(
|
||||
quiet.changed.find((c) => c.sessionId === ID && !c.isNew),
|
||||
"caught up once quiet"
|
||||
);
|
||||
assert.notEqual(cache.get(file), -1);
|
||||
});
|
||||
|
||||
it("never re-parses a hook-created session, only refreshes its snapshot once quiet", async () => {
|
||||
const ID = "44444444-dddd-4ddd-8ddd-444444444444";
|
||||
dbModule.stmts.insertSession.run(ID, "hooked", "active", "/hooked", null, null);
|
||||
dbModule.stmts.insertEvent.run(ID, null, "SessionStart", null, "hook", "{}");
|
||||
const file = writeSession("-hooked", ID, fixtureLines(ID, "/hooked"));
|
||||
bumpMtime(file);
|
||||
const snap = path.join(SNAP_DIR, `${ID}.jsonl`);
|
||||
const cache = new Map();
|
||||
|
||||
await syncDefaultProjects(dbModule, { mtimeCache: cache });
|
||||
assert.equal(fs.existsSync(snap), false, "no snapshot copy while hooks are live");
|
||||
|
||||
ageSession(ID);
|
||||
const before = dbModule.db.prepare("SELECT COUNT(*) AS n FROM events WHERE session_id = ?");
|
||||
const n0 = before.get(ID).n;
|
||||
const r = await syncDefaultProjects(dbModule, { mtimeCache: cache });
|
||||
assert.equal(
|
||||
r.changed.find((c) => c.sessionId === ID),
|
||||
undefined,
|
||||
"nothing imported"
|
||||
);
|
||||
assert.equal(before.get(ID).n, n0, "no events written for a hook-created session");
|
||||
assert.equal(fs.existsSync(snap), true, "snapshot taken once quiet");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* @file Tests for the hook writer's per-transcript "already handled" marks
|
||||
* (`transcriptMarks` in server/routes/hooks.js): a hook whose transcript is
|
||||
* unchanged skips the token / compaction / API-error / turn-duration writes,
|
||||
* a grown transcript is walked only from the last entry handled, and the rows
|
||||
* left behind are exactly the ones a full re-walk would have written.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const { describe, it, before, after } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const path = require("path");
|
||||
const fs = require("fs");
|
||||
const os = require("os");
|
||||
const http = require("http");
|
||||
|
||||
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), "agenthub-marks-"));
|
||||
process.env.DASHBOARD_DB_PATH = path.join(TMP, "dashboard.db");
|
||||
process.env.CLAUDE_HOME = path.join(TMP, "home");
|
||||
process.env.DASHBOARD_DATA_DIR = path.join(TMP, "data");
|
||||
|
||||
const { createApp, startServer } = require("../index");
|
||||
const { db } = require("../db");
|
||||
const hooksRouter = require("../routes/hooks");
|
||||
|
||||
let server;
|
||||
let BASE;
|
||||
|
||||
function post(body) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const url = new URL("/api/hooks/event", BASE);
|
||||
const payload = JSON.stringify(body);
|
||||
const r = http.request(
|
||||
{
|
||||
hostname: url.hostname,
|
||||
port: url.port,
|
||||
path: url.pathname,
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.byteLength(payload),
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
res.resume();
|
||||
res.on("end", () => resolve(res.statusCode));
|
||||
}
|
||||
);
|
||||
r.on("error", reject);
|
||||
r.write(payload);
|
||||
r.end();
|
||||
});
|
||||
}
|
||||
|
||||
const line = (o) => JSON.stringify(o) + "\n";
|
||||
const assistant = (id, inTok) => ({
|
||||
type: "assistant",
|
||||
timestamp: "2026-09-18T01:00:00.000Z",
|
||||
message: {
|
||||
id,
|
||||
model: "claude-sonnet-5",
|
||||
content: [{ type: "text", text: "ok" }],
|
||||
usage: { input_tokens: inTok, output_tokens: 1 },
|
||||
},
|
||||
});
|
||||
const turn = (ms, ts) => ({
|
||||
type: "system",
|
||||
subtype: "turn_duration",
|
||||
durationMs: ms,
|
||||
timestamp: ts,
|
||||
});
|
||||
const apiError = (text, ts) => ({
|
||||
type: "assistant",
|
||||
isApiErrorMessage: true,
|
||||
error: "rate_limit",
|
||||
timestamp: ts,
|
||||
message: { content: [{ type: "text", text }] },
|
||||
});
|
||||
const compact = (uuid, ts) => ({ type: "user", isCompactSummary: true, uuid, timestamp: ts });
|
||||
|
||||
function rows(sid) {
|
||||
const ev = db
|
||||
.prepare(
|
||||
"SELECT event_type, summary, created_at FROM events WHERE session_id = ? AND event_type IN ('TurnDuration','APIError','Compaction') ORDER BY event_type, created_at, summary"
|
||||
)
|
||||
.all(sid)
|
||||
.map((r) =>
|
||||
r.event_type === "APIError"
|
||||
? `${r.event_type}|${r.summary}`
|
||||
: `${r.event_type}|${r.created_at}|${r.summary}`
|
||||
);
|
||||
const tokens = db
|
||||
.prepare("SELECT model, input_tokens, baseline_input FROM token_usage WHERE session_id = ?")
|
||||
.all(sid);
|
||||
return { ev, tokens };
|
||||
}
|
||||
|
||||
before(async () => {
|
||||
server = await startServer(createApp(), 0);
|
||||
BASE = `http://127.0.0.1:${server.address().port}`;
|
||||
});
|
||||
|
||||
after(() => {
|
||||
server?.close();
|
||||
fs.rmSync(TMP, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("transcript marks", () => {
|
||||
it("skips an unchanged transcript and walks only the new tail of a grown one", async () => {
|
||||
const sid = "abababab-1111-4111-8111-abababababab";
|
||||
const cwd = path.join(TMP, "work");
|
||||
fs.mkdirSync(cwd, { recursive: true });
|
||||
const tpath = path.join(TMP, `${sid}.jsonl`);
|
||||
fs.writeFileSync(
|
||||
tpath,
|
||||
line(assistant("m1", 5)) +
|
||||
line(turn(1000, "2026-09-18T01:00:01.000Z")) +
|
||||
line(apiError("slow down", "2026-09-18T01:00:02.000Z")) +
|
||||
line(compact("c-1", "2026-09-18T01:00:03.000Z")) +
|
||||
line(assistant("m2", 7)) +
|
||||
line(turn(2000, "2026-09-18T01:00:04.000Z"))
|
||||
);
|
||||
const data = { session_id: sid, cwd, transcript_path: tpath };
|
||||
|
||||
assert.equal(await post({ hook_type: "PostToolUse", data }), 200);
|
||||
const first = rows(sid);
|
||||
assert.equal(first.ev.filter((e) => e.startsWith("TurnDuration")).length, 2);
|
||||
assert.equal(first.ev.filter((e) => e.startsWith("APIError")).length, 1);
|
||||
assert.equal(first.ev.filter((e) => e.startsWith("Compaction")).length, 1);
|
||||
assert.ok(hooksRouter.transcriptMarks.size >= 1, "a mark is kept after commit");
|
||||
|
||||
// Proof of the skip: a row removed behind the writer's back is NOT put
|
||||
// back by a hook whose transcript did not change (before, every hook
|
||||
// re-walked the whole history and re-inserted it).
|
||||
db.prepare(
|
||||
"DELETE FROM events WHERE session_id = ? AND event_type = 'TurnDuration' AND created_at = '2026-09-18T01:00:01.000Z'"
|
||||
).run(sid);
|
||||
assert.equal(await post({ hook_type: "PostToolUse", data: { ...data, tool_name: "x" } }), 200);
|
||||
assert.equal(rows(sid).ev.filter((e) => e.startsWith("TurnDuration")).length, 1);
|
||||
db.prepare("DELETE FROM events WHERE session_id = ? AND event_type = 'TurnDuration'").run(sid);
|
||||
hooksRouter.transcriptMarks.clear();
|
||||
assert.equal(await post({ hook_type: "PostToolUse", data: { ...data, tool_name: "y" } }), 200);
|
||||
assert.deepEqual(rows(sid), first, "a cleared mark re-walks the whole history, as before");
|
||||
|
||||
// Grow it: one turn, one new error, a repeat of the old error, a compaction.
|
||||
fs.appendFileSync(
|
||||
tpath,
|
||||
line(assistant("m3", 11)) +
|
||||
line(turn(3000, "2026-09-18T01:00:05.000Z")) +
|
||||
line(apiError("slow down", "2026-09-18T01:00:06.000Z")) +
|
||||
line(apiError("overloaded", "2026-09-18T01:00:07.000Z")) +
|
||||
line(compact("c-2", "2026-09-18T01:00:08.000Z"))
|
||||
);
|
||||
assert.equal(await post({ hook_type: "Stop", data }), 200);
|
||||
const grown = rows(sid);
|
||||
|
||||
// The same transcript walked from scratch must produce the same rows.
|
||||
hooksRouter.transcriptMarks.clear();
|
||||
assert.equal(await post({ hook_type: "Stop", data: { ...data, stop_hook_active: true } }), 200);
|
||||
assert.deepEqual(rows(sid), grown, "the delta wrote exactly what a full walk writes");
|
||||
assert.equal(grown.ev.filter((e) => e.startsWith("TurnDuration")).length, 3);
|
||||
assert.equal(grown.ev.filter((e) => e.startsWith("APIError")).length, 2, "repeat deduped");
|
||||
assert.equal(grown.ev.filter((e) => e.startsWith("Compaction")).length, 2);
|
||||
assert.equal(grown.tokens.length, 1);
|
||||
assert.equal(grown.tokens[0].input_tokens + grown.tokens[0].baseline_input, 23);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* @file Tests server/update-scheduler.js — the default interval is an hour
|
||||
* (the env override and its 60 s floor still apply), a scheduled tick with no
|
||||
* browser connected runs no check, and a browser connecting after that gets
|
||||
* one catch-up check (only when the last check is stale). The check, the
|
||||
* connection count and the connection event are injected; nothing touches git
|
||||
* or the network.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const { describe, it, afterEach } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
|
||||
delete process.env.DASHBOARD_UPDATE_CHECK;
|
||||
const { startUpdateScheduler, intervalMs } = require("../update-scheduler");
|
||||
|
||||
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
let handle = null;
|
||||
afterEach(() => {
|
||||
handle?.stop();
|
||||
handle = null;
|
||||
delete process.env.DASHBOARD_UPDATE_CHECK_INTERVAL_MS;
|
||||
});
|
||||
|
||||
function harness(clients) {
|
||||
const h = { checks: 0, clients, listeners: [] };
|
||||
handle = startUpdateScheduler({
|
||||
broadcast: () => {},
|
||||
getConnectionCount: () => h.clients,
|
||||
onConnection: (fn) => {
|
||||
h.listeners.push(fn);
|
||||
return () => {};
|
||||
},
|
||||
getStatus: async () => {
|
||||
h.checks++;
|
||||
return { update_available: false };
|
||||
},
|
||||
initialDelayMs: 10,
|
||||
});
|
||||
h.connect = () => h.listeners.forEach((fn) => fn());
|
||||
return h;
|
||||
}
|
||||
|
||||
describe("intervalMs", () => {
|
||||
it("defaults to one hour and keeps the override with its floor", () => {
|
||||
delete process.env.DASHBOARD_UPDATE_CHECK_INTERVAL_MS;
|
||||
assert.equal(intervalMs(), 60 * 60 * 1000);
|
||||
process.env.DASHBOARD_UPDATE_CHECK_INTERVAL_MS = "120000";
|
||||
assert.equal(intervalMs(), 120000);
|
||||
process.env.DASHBOARD_UPDATE_CHECK_INTERVAL_MS = "1000";
|
||||
assert.equal(intervalMs(), 60 * 60 * 1000);
|
||||
});
|
||||
});
|
||||
|
||||
describe("startUpdateScheduler", () => {
|
||||
it("checks on the first tick when a browser is connected", async () => {
|
||||
const h = harness(1);
|
||||
await wait(40);
|
||||
assert.equal(h.checks, 1);
|
||||
});
|
||||
|
||||
it("skips the tick with no browser, then checks once when one connects", async () => {
|
||||
const h = harness(0);
|
||||
await wait(40);
|
||||
assert.equal(h.checks, 0);
|
||||
h.clients = 1;
|
||||
h.connect();
|
||||
h.connect(); // a second tab in the same window: still one check
|
||||
await wait(3_300);
|
||||
assert.equal(h.checks, 1);
|
||||
h.connect(); // fresh check: no catch-up
|
||||
await wait(3_300);
|
||||
assert.equal(h.checks, 1);
|
||||
});
|
||||
});
|
||||
@@ -465,3 +465,23 @@ describe("listBranches", () => {
|
||||
assert.deepEqual(branches, []);
|
||||
});
|
||||
});
|
||||
|
||||
describe("git missing from PATH", () => {
|
||||
it("answers EGITMISSING with the fix, not a bare ENOENT, when the folder exists", async () => {
|
||||
const saved = process.env.PATH;
|
||||
process.env.PATH = path.join(ROOT, "no-such-bin");
|
||||
try {
|
||||
await assert.rejects(
|
||||
() => wt.git(ROOT, ["status"]),
|
||||
(err) => err.code === "EGITMISSING" && /install/i.test(err.message)
|
||||
);
|
||||
// A missing FOLDER is the other ENOENT, and stays one.
|
||||
await assert.rejects(
|
||||
() => wt.git(path.join(ROOT, "gone"), ["status"]),
|
||||
(err) => err.code === "ENOENT"
|
||||
);
|
||||
} finally {
|
||||
process.env.PATH = saved;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
+47
-1
@@ -141,6 +141,14 @@ migrateLegacyDatabase(DB_PATH);
|
||||
|
||||
const db = new Database(DB_PATH);
|
||||
|
||||
// Freed pages go back to the OS only with auto_vacuum. On a NEW database this
|
||||
// takes effect at once — it must come before `journal_mode = WAL`, which
|
||||
// writes the header; an existing one is converted further down, by a VACUUM,
|
||||
// only while it is small (`convertAutoVacuum`), else by Settings → Data →
|
||||
// Compact. `maintainDatabase` then runs a bounded `incremental_vacuum`.
|
||||
if (db.pragma("auto_vacuum", { simple: true }) === 0) {
|
||||
db.pragma("auto_vacuum = INCREMENTAL");
|
||||
}
|
||||
db.pragma("journal_mode = WAL");
|
||||
db.pragma("foreign_keys = ON");
|
||||
db.pragma("busy_timeout = 5000");
|
||||
@@ -1865,6 +1873,40 @@ for (const col of ["display_name", "email", "avatar_at"]) {
|
||||
db.prepare(`ALTER TABLE users ADD COLUMN ${col} TEXT`).run();
|
||||
}
|
||||
}
|
||||
// An admin's pin of one server-mode user to one pool account per tool
|
||||
// (server/lib/account-pins.js): that user's new sessions skip the balancer.
|
||||
// The account is named, not referenced — the pool lives in files.
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS account_pins (
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
tool TEXT NOT NULL CHECK(tool IN ('claude','codex')),
|
||||
account TEXT NOT NULL,
|
||||
pinned_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
|
||||
PRIMARY KEY (user_id, tool)
|
||||
);
|
||||
`);
|
||||
|
||||
// An existing database made before auto_vacuum: the setting is stored only by
|
||||
// a VACUUM, which rewrites the whole file under an exclusive lock. Done here,
|
||||
// at startup and under the migration lock, only for a file up to
|
||||
// AUTO_VACUUM_CONVERT_MAX_BYTES (well under a second); a bigger one is
|
||||
// converted by the manual Compact (server/lib/db-retention.js). Best effort: a
|
||||
// second process holding a read open makes it fail, and the next start retries.
|
||||
const AUTO_VACUUM_CONVERT_MAX_BYTES = 32 * 1024 * 1024;
|
||||
function convertAutoVacuum() {
|
||||
try {
|
||||
if (db.pragma("auto_vacuum", { simple: true }) !== 0) return false;
|
||||
const bytes =
|
||||
db.pragma("page_count", { simple: true }) * db.pragma("page_size", { simple: true });
|
||||
if (bytes > AUTO_VACUUM_CONVERT_MAX_BYTES) return false;
|
||||
db.pragma("auto_vacuum = INCREMENTAL");
|
||||
db.exec("VACUUM");
|
||||
return db.pragma("auto_vacuum", { simple: true }) === 2;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
convertAutoVacuum();
|
||||
|
||||
migrationLock.exec("COMMIT");
|
||||
migrationLock.close();
|
||||
@@ -2535,7 +2577,9 @@ const stmts = {
|
||||
* on a reader — the other dashboard's), after which the next write truncates
|
||||
* the WAL to `journal_size_limit`; and `PRAGMA optimize`, which refreshes the
|
||||
* planner's statistics only where they went stale. Never VACUUM: it rewrites
|
||||
* the whole file under an exclusive lock.
|
||||
* the whole file under an exclusive lock. The opt-in retention and the
|
||||
* bounded `incremental_vacuum` run after this, from
|
||||
* `server/lib/db-retention.js`'s `runScheduledMaintenance`.
|
||||
*/
|
||||
function maintainDatabase() {
|
||||
const out = {};
|
||||
@@ -2561,4 +2605,6 @@ module.exports = {
|
||||
applyIntroPricing,
|
||||
topUpDefaultPricing,
|
||||
maintainDatabase,
|
||||
convertAutoVacuum,
|
||||
AUTO_VACUUM_CONVERT_MAX_BYTES,
|
||||
};
|
||||
|
||||
+59
-13
@@ -33,6 +33,20 @@ if (process.env.GIT_EDITOR === "true") delete process.env.GIT_EDITOR;
|
||||
// server/lib/settings-env.js. Only when this
|
||||
// file IS the process: the test suite requires it dozens of times, and a
|
||||
// developer's real settings file pins DASHBOARD_DATA_DIR at their live database.
|
||||
/** What to tell the user when the dashboard cannot bind its port. The health
|
||||
* probe above already turned away a port held by a running dashboard, so a
|
||||
* port in use here belongs to some other program. */
|
||||
function listenFailure(err, port) {
|
||||
if (err?.code === "EADDRINUSE")
|
||||
return (
|
||||
`Port ${port} is already in use by another program, so AgentHub cannot start there. ` +
|
||||
`Stop that program, or run AgentHub on another port with DASHBOARD_PORT (for example DASHBOARD_PORT=4821).`
|
||||
);
|
||||
if (err?.code === "EACCES")
|
||||
return `Not allowed to listen on port ${port}. Pick a port above 1024 with DASHBOARD_PORT.`;
|
||||
return `AgentHub could not start its server: ${err?.stack || err}`;
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
const settingsEnv = require("./lib/settings-env");
|
||||
settingsEnv.loadEnvFiles({
|
||||
@@ -337,8 +351,12 @@ function startServer(app, port) {
|
||||
const host = resolveHost();
|
||||
const boundLoopback = isLoopbackHostname(host);
|
||||
|
||||
return new Promise((resolve) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
// A port another program holds fails here, not as an uncaught 'error'
|
||||
// event: the caller says what happened instead of a bare stack trace.
|
||||
server.once("error", reject);
|
||||
server.listen(port, host, () => {
|
||||
server.off("error", reject);
|
||||
// Publish the live port so the Claude Code hook handler can find this
|
||||
// server even when it bound a non-default port (the desktop app falls
|
||||
// back off 4820 when that port is already taken).
|
||||
@@ -482,11 +500,17 @@ function startBackgroundServices() {
|
||||
.catch(() => {});
|
||||
|
||||
// Hourly DB upkeep: a non-blocking checkpoint (the WAL then shrinks to
|
||||
// journal_size_limit) and PRAGMA optimize. Off with DASHBOARD_DB_MAINTAIN_MS=0.
|
||||
// journal_size_limit), PRAGMA optimize, the opt-in retention
|
||||
// (AGENTHUB_RETENTION_DAYS, off by default) and a bounded incremental_vacuum
|
||||
// (server/lib/db-retention.js). Off with DASHBOARD_DB_MAINTAIN_MS=0.
|
||||
{
|
||||
const every = Number(process.env.DASHBOARD_DB_MAINTAIN_MS ?? 60 * 60 * 1000);
|
||||
if (every > 0) {
|
||||
const t = setInterval(() => require("./db").maintainDatabase(), every);
|
||||
const t = setInterval(() => {
|
||||
require("./lib/db-retention")
|
||||
.runScheduledMaintenance()
|
||||
.catch(() => {});
|
||||
}, every);
|
||||
if (t.unref) t.unref();
|
||||
}
|
||||
}
|
||||
@@ -807,18 +831,35 @@ function startBackgroundServices() {
|
||||
}
|
||||
// Another dashboard on the same database (hooks reach only one of them)
|
||||
// moving a lane: re-broadcast it here. One pragma per beat when nothing
|
||||
// changed. Off with DASHBOARD_LANE_SYNC_MS=0.
|
||||
// changed — and only while such a dashboard runs at all: alone on its data
|
||||
// dir, this server only looks for one every LANE_PEER_CHECK_MS (the first
|
||||
// call primes what it has seen, so a peer that starts later is compared
|
||||
// against it). Off with DASHBOARD_LANE_SYNC_MS=0.
|
||||
const LANE_SYNC_MS = Number(process.env.DASHBOARD_LANE_SYNC_MS ?? 2_000);
|
||||
if (Number.isFinite(LANE_SYNC_MS) && LANE_SYNC_MS > 0) {
|
||||
const { broadcastForeignLaneChanges } = require("./routes/lanes");
|
||||
const laneSyncTimer = setInterval(() => {
|
||||
const LANE_PEER_CHECK_MS = Math.max(LANE_SYNC_MS, 30_000);
|
||||
let peersSeenAt = 0;
|
||||
let hasPeers = false;
|
||||
const syncLanes = () => {
|
||||
try {
|
||||
broadcastForeignLaneChanges();
|
||||
} catch (err) {
|
||||
console.warn("lane sync failed:", err.message);
|
||||
}
|
||||
}, LANE_SYNC_MS);
|
||||
if (laneSyncTimer.unref) laneSyncTimer.unref();
|
||||
};
|
||||
syncLanes();
|
||||
const laneSyncTick = () => {
|
||||
if (Date.now() - peersSeenAt >= LANE_PEER_CHECK_MS) {
|
||||
hasPeers = peersSharingDataDir().length > 0;
|
||||
peersSeenAt = Date.now();
|
||||
}
|
||||
if (hasPeers) syncLanes();
|
||||
const t = setTimeout(laneSyncTick, hasPeers ? LANE_SYNC_MS : LANE_PEER_CHECK_MS);
|
||||
if (t.unref) t.unref();
|
||||
};
|
||||
const first = setTimeout(laneSyncTick, LANE_SYNC_MS);
|
||||
if (first.unref) first.unref();
|
||||
}
|
||||
// Continuous discovery of sessions under ~/.claude/projects. The one-time
|
||||
// legacy backfill above runs only once (marker-gated), so a project added
|
||||
@@ -1210,12 +1251,17 @@ if (require.main === module) {
|
||||
return;
|
||||
}
|
||||
const app = createApp();
|
||||
startServer(app, PORT).then((server) => {
|
||||
httpServer = server;
|
||||
startBackgroundServices();
|
||||
// The status-area icon (server/lib/tray.js) — production servers only.
|
||||
require("./lib/tray").startTrayWatch();
|
||||
});
|
||||
startServer(app, PORT)
|
||||
.then((server) => {
|
||||
httpServer = server;
|
||||
startBackgroundServices();
|
||||
// The status-area icon (server/lib/tray.js) — production servers only.
|
||||
require("./lib/tray").startTrayWatch();
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(listenFailure(err, PORT));
|
||||
process.exit(1);
|
||||
});
|
||||
});
|
||||
|
||||
// Graceful shutdown — close connections and DB cleanly
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* @file account-pins.js
|
||||
* @description Account pins: an admin's choice that one server-mode user's
|
||||
* new sessions of a tool run on one named pool account instead of the one the
|
||||
* balancer would pick (claude-pool.js / codex-pool.js `pick`) — the Users
|
||||
* page's "switch a user's account". One pin per user and tool
|
||||
* (`account_pins`); the user is the workspace's OWNER
|
||||
* (`lanes.owner_id`), never whoever clicked Start. A pin is a preference the
|
||||
* pool still bounds: an account a pane may not use (expired, or a login the
|
||||
* pane's home cannot take) falls back to the balancer. A Claude login is
|
||||
* written into the user's home right away (`applyPin`), over the pool login
|
||||
* their running panes use, so those move to it without a restart.
|
||||
*
|
||||
* `setAccountUsers` is the Users page's Edit of one account: who runs on it.
|
||||
*
|
||||
* Server mode only: in local mode there are no users and nothing is pinned.
|
||||
* Removing the account drops its pins (`dropAccount`); deleting the user drops
|
||||
* theirs (ON DELETE CASCADE, and `auth.deleteUser`).
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const TOOLS = ["claude", "codex"];
|
||||
|
||||
const err = (code, message) => Object.assign(new Error(message), { code });
|
||||
const db = () => require("../db").db;
|
||||
const poolOf = (tool) => require(tool === "codex" ? "./codex-pool" : "./claude-pool");
|
||||
|
||||
function validTool(tool) {
|
||||
if (!TOOLS.includes(tool)) throw err("EBADTOOL", "tool: claude or codex");
|
||||
return tool;
|
||||
}
|
||||
|
||||
/** The account name `ownerId`'s new `tool` sessions are pinned to, or null. */
|
||||
function pinFor(ownerId, tool) {
|
||||
if (!require("./auth").isServerMode() || !Number.isInteger(ownerId)) return null;
|
||||
try {
|
||||
return (
|
||||
db()
|
||||
.prepare("SELECT account FROM account_pins WHERE user_id = ? AND tool = ?")
|
||||
.get(ownerId, tool)?.account ?? null
|
||||
);
|
||||
} catch {
|
||||
return null; // a spawn never fails over a pin
|
||||
}
|
||||
}
|
||||
|
||||
/** Every pin of `tool`, with its user's name: `[{userId, username, account, pinnedAt}]`. */
|
||||
function listPins(tool) {
|
||||
return db()
|
||||
.prepare(
|
||||
`SELECT p.user_id AS userId, u.username, p.account, p.pinned_at AS pinnedAt
|
||||
FROM account_pins p JOIN users u ON u.id = p.user_id
|
||||
WHERE p.tool = ? ORDER BY u.username`
|
||||
)
|
||||
.all(validTool(tool));
|
||||
}
|
||||
|
||||
/**
|
||||
* Pin `userId`'s new `tool` sessions to `account`, or unpin them (`account`
|
||||
* null). Returns `{userId, username, account}`.
|
||||
*/
|
||||
function setPin(userId, tool, account) {
|
||||
validTool(tool);
|
||||
const user = Number.isInteger(userId)
|
||||
? db().prepare("SELECT id, username FROM users WHERE id = ?").get(userId)
|
||||
: null;
|
||||
if (!user) throw err("ENOUSER", `no user ${userId}`);
|
||||
if (account == null || account === "") {
|
||||
db().prepare("DELETE FROM account_pins WHERE user_id = ? AND tool = ?").run(user.id, tool);
|
||||
return { userId: user.id, username: user.username, account: null };
|
||||
}
|
||||
const name = String(account);
|
||||
if (!poolOf(tool).hasAccount(name)) {
|
||||
throw err("ENOACCOUNT", `no ${tool} account ${name} in the pool`);
|
||||
}
|
||||
db()
|
||||
.prepare(
|
||||
`INSERT INTO account_pins (user_id, tool, account) VALUES (?, ?, ?)
|
||||
ON CONFLICT(user_id, tool) DO UPDATE SET account = excluded.account,
|
||||
pinned_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now')`
|
||||
)
|
||||
.run(user.id, tool, name);
|
||||
return { userId: user.id, username: user.username, account: name };
|
||||
}
|
||||
|
||||
/**
|
||||
* The Users page's Edit of one account: exactly `userIds` run on `account`
|
||||
* afterwards. A user pinned to another account of the tool moves here; one
|
||||
* pinned here but left out goes back to the balancer. One transaction.
|
||||
* Returns `{added, removed}` (each `[{userId, username}]`).
|
||||
*/
|
||||
function setAccountUsers(tool, account, userIds) {
|
||||
validTool(tool);
|
||||
const name = String(account ?? "");
|
||||
if (!poolOf(tool).hasAccount(name)) {
|
||||
throw err("ENOACCOUNT", `no ${tool} account ${name} in the pool`);
|
||||
}
|
||||
if (!Array.isArray(userIds) || !userIds.every(Number.isInteger)) {
|
||||
throw err("EBADUSER", "userIds: an array of user ids");
|
||||
}
|
||||
const want = [...new Set(userIds)];
|
||||
const users = want.map((id) => {
|
||||
const u = db().prepare("SELECT id, username FROM users WHERE id = ?").get(id);
|
||||
if (!u) throw err("ENOUSER", `no user ${id}`);
|
||||
return u;
|
||||
});
|
||||
const before = listPins(tool);
|
||||
const here = new Set(before.filter((p) => p.account === name).map((p) => p.userId));
|
||||
const added = users.filter((u) => !here.has(u.id));
|
||||
const removed = before.filter((p) => p.account === name && !want.includes(p.userId));
|
||||
db().transaction(() => {
|
||||
for (const u of added) setPin(u.id, tool, name);
|
||||
for (const p of removed) setPin(p.userId, tool, null);
|
||||
})();
|
||||
return {
|
||||
added: added.map((u) => ({ userId: u.id, username: u.username })),
|
||||
removed: removed.map((p) => ({ userId: p.userId, username: p.username })),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Make a pin take effect now where it can: a Claude login is written into
|
||||
* the user's home at once (claude-pool `switchHome`), so their running panes
|
||||
* move to it without a restart. Anything else goes in at the next spawn.
|
||||
* Answers what happened (see `switchHome`).
|
||||
*/
|
||||
async function applyPin(userId, tool) {
|
||||
const pin = pinFor(userId, tool);
|
||||
if (!pin || tool !== "claude") return "next-session";
|
||||
const user = db().prepare("SELECT username FROM users WHERE id = ?").get(userId);
|
||||
const member = user ? require("./run-as").accountForUser(user.username) : null;
|
||||
return poolOf(tool).switchHome(member, pin);
|
||||
}
|
||||
|
||||
/** A removed account takes its pins with it. */
|
||||
function dropAccount(tool, account) {
|
||||
try {
|
||||
db().prepare("DELETE FROM account_pins WHERE tool = ? AND account = ?").run(tool, account);
|
||||
} catch {
|
||||
/* no database (a bare CLI test): nothing pinned */
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { TOOLS, pinFor, listPins, setPin, setAccountUsers, applyPin, dropAccount };
|
||||
@@ -425,6 +425,9 @@ function writeSession(f, conv, now) {
|
||||
}
|
||||
|
||||
let running = null;
|
||||
// Fresh sessions the last pass left for a later one to settle (the poll keeps
|
||||
// its base pace while there are any).
|
||||
let lastPending = 0;
|
||||
|
||||
/**
|
||||
* One pass over every conversation file: a changed one is re-read, an
|
||||
@@ -440,12 +443,16 @@ function ingestAntigravityUsage({
|
||||
running = (async () => {
|
||||
let read = 0;
|
||||
let written = 0;
|
||||
let pending = 0; // still-fresh sessions a later pass may have to settle
|
||||
for (const f of conversationFiles()) {
|
||||
try {
|
||||
const seen = getSeen.get(f.path);
|
||||
if (seen && seen.mtime_ms === f.mtime) {
|
||||
const a = activity(f.id, f.mtime);
|
||||
if (fresh(a, now)) continue;
|
||||
if (fresh(a, now)) {
|
||||
pending += 1;
|
||||
continue;
|
||||
}
|
||||
const s = stmts.getSession.get(f.id);
|
||||
if (s && s.tool === "antigravity" && s.status === "active") {
|
||||
const at = new Date(a.last).toISOString();
|
||||
@@ -486,6 +493,7 @@ function ingestAntigravityUsage({
|
||||
}
|
||||
await new Promise((r) => setImmediate(r));
|
||||
}
|
||||
lastPending = pending;
|
||||
return { files: read, sessions: written };
|
||||
})().finally(() => {
|
||||
running = null;
|
||||
@@ -504,16 +512,16 @@ function startAntigravityUsagePoll(broadcast, broadcastLane) {
|
||||
if (!Number.isFinite(POLL_MS) || POLL_MS <= 0) return;
|
||||
// Files an older build could not read get another try.
|
||||
db.prepare("DELETE FROM antigravity_conversations WHERE session_id = ''").run();
|
||||
const tick = () => {
|
||||
ingestAntigravityUsage({ broadcast, broadcastLane })
|
||||
.then((r) => {
|
||||
// Slowed to once a minute after a pass that read nothing, wrote nothing and
|
||||
// left no fresh session to settle; back to POLL_MS once one finds work.
|
||||
require("./backoff-poll").startBackoffPoll(
|
||||
() =>
|
||||
ingestAntigravityUsage({ broadcast, broadcastLane }).then((r) => {
|
||||
if (r.sessions > 0 && pricingSync.syncEnabled()) void pricingSync.syncPricing(db);
|
||||
})
|
||||
.catch(() => {});
|
||||
};
|
||||
tick();
|
||||
const timer = setInterval(tick, POLL_MS);
|
||||
if (timer.unref) timer.unref();
|
||||
return r.files + r.sessions + lastPending > 0;
|
||||
}),
|
||||
{ baseMs: POLL_MS }
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
||||
+177
-60
@@ -57,7 +57,8 @@ const KINDS = ["page", "file", "skill", "plugin"];
|
||||
const DOC_EXT =
|
||||
/\.(html?|md|markdown|mdx|pdf|png|jpe?g|gif|webp|svg|csv|tsv|json|ya?ml|txt|log|xlsx?|docx?|pptx?|ipynb|mp4|webm|mp3|wav|zip)$/i;
|
||||
const PAGE_URL_RE = /^https:\/\/claude\.ai\/[A-Za-z0-9._~\-/?#=&%]+$/;
|
||||
const PAGE_IN_TEXT_RE = /https:\/\/claude\.ai\/(?:code\/)?artifact\/[A-Za-z0-9_-]+[A-Za-z0-9._~\-/?#=&%]*/;
|
||||
const PAGE_IN_TEXT_RE =
|
||||
/https:\/\/claude\.ai\/(?:code\/)?artifact\/[A-Za-z0-9_-]+[A-Za-z0-9._~\-/?#=&%]*/;
|
||||
const SKILL_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
|
||||
const PLUGIN_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}@[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
|
||||
const GITHUB_REPO_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}\/[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/;
|
||||
@@ -86,7 +87,8 @@ const canSee = (req, row) => {
|
||||
};
|
||||
|
||||
/** Only the owner changes a row — or an admin, or anyone in local mode. */
|
||||
const canChange = (req, row) => !req?.user || req.user.role === "admin" || row.owner_id === req.user.id;
|
||||
const canChange = (req, row) =>
|
||||
!req?.user || req.user.role === "admin" || row.owner_id === req.user.id;
|
||||
|
||||
/** For scope.js's PATH_RULES: may this request name artifact `id`? */
|
||||
function canSeeId(req, id) {
|
||||
@@ -101,12 +103,18 @@ function load(req, id) {
|
||||
return row;
|
||||
}
|
||||
|
||||
function view(row, req) {
|
||||
function view(row, req, owners = null) {
|
||||
if (!row) return null;
|
||||
const owner =
|
||||
row.owner_id == null
|
||||
? null
|
||||
: sql("SELECT username, display_name FROM users WHERE id = ?").get(row.owner_id);
|
||||
let owner = null;
|
||||
if (row.owner_id != null) {
|
||||
// A list passes one cache, so each owner is looked up once, not per row.
|
||||
if (owners?.has(row.owner_id)) owner = owners.get(row.owner_id);
|
||||
else {
|
||||
owner =
|
||||
sql("SELECT username, display_name FROM users WHERE id = ?").get(row.owner_id) || null;
|
||||
owners?.set(row.owner_id, owner);
|
||||
}
|
||||
}
|
||||
return {
|
||||
id: row.id,
|
||||
kind: row.kind,
|
||||
@@ -159,15 +167,22 @@ function list(req, { scope = "all", kind, q, laneId, sessionId, limit = 200 } =
|
||||
params.push(String(sessionId));
|
||||
}
|
||||
if (q && String(q).trim()) {
|
||||
where.push("(a.title LIKE ? OR a.description LIKE ? OR a.source LIKE ?)");
|
||||
const like = `%${String(q).trim().replace(/[%_]/g, (c) => `\\${c}`)}%`;
|
||||
// `\` escapes `%`/`_` (and itself) only with an ESCAPE clause: SQLite
|
||||
// has no default escape character, so without it `my_skill` found nothing.
|
||||
where.push(
|
||||
"(a.title LIKE ? ESCAPE '\\' OR a.description LIKE ? ESCAPE '\\' OR a.source LIKE ? ESCAPE '\\')"
|
||||
);
|
||||
const like = `%${String(q)
|
||||
.trim()
|
||||
.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
|
||||
params.push(like, like, like);
|
||||
}
|
||||
const n = Math.min(Math.max(Number(limit) || 200, 1), 500);
|
||||
const rows = sql(
|
||||
`SELECT a.* FROM artifacts a WHERE ${where.join(" AND ")} ORDER BY a.updated_at DESC, a.id DESC LIMIT ${n}`
|
||||
).all(...params);
|
||||
return rows.map((r) => view(r, req));
|
||||
const owners = new Map();
|
||||
return rows.map((r) => view(r, req, owners));
|
||||
}
|
||||
|
||||
// ── Small helpers ─────────────────────────────────────────────────────────
|
||||
@@ -176,8 +191,7 @@ function cleanTitle(v, fallback) {
|
||||
const t = typeof v === "string" ? v.trim().slice(0, TITLE_MAX) : "";
|
||||
return t || String(fallback || "Untitled").slice(0, TITLE_MAX);
|
||||
}
|
||||
const cleanDescription = (v) =>
|
||||
typeof v === "string" ? v.trim().slice(0, DESCRIPTION_MAX) : "";
|
||||
const cleanDescription = (v) => (typeof v === "string" ? v.trim().slice(0, DESCRIPTION_MAX) : "");
|
||||
|
||||
function insert(fields) {
|
||||
const cols = Object.keys(fields);
|
||||
@@ -215,9 +229,9 @@ function sessionOwner(sessionId) {
|
||||
function sessionLane(sessionId) {
|
||||
const row =
|
||||
sql("SELECT lane_id FROM sessions WHERE id = ?").get(String(sessionId)) ||
|
||||
sql("SELECT lane_id FROM dashboard_runs WHERE session_id = ? AND lane_id IS NOT NULL LIMIT 1").get(
|
||||
String(sessionId)
|
||||
);
|
||||
sql(
|
||||
"SELECT lane_id FROM dashboard_runs WHERE session_id = ? AND lane_id IS NOT NULL LIMIT 1"
|
||||
).get(String(sessionId));
|
||||
return row?.lane_id ?? null;
|
||||
}
|
||||
|
||||
@@ -235,9 +249,10 @@ function validPageUrl(url) {
|
||||
function addPage(req, { url, title, description, laneId, sessionId }) {
|
||||
const u = validPageUrl(url);
|
||||
const ownerId = req?.user ? req.user.id : null;
|
||||
const same = sql(
|
||||
"SELECT * FROM artifacts WHERE kind = 'page' AND url = ? AND owner_id IS ?"
|
||||
).get(u, ownerId);
|
||||
const same = sql("SELECT * FROM artifacts WHERE kind = 'page' AND url = ? AND owner_id IS ?").get(
|
||||
u,
|
||||
ownerId
|
||||
);
|
||||
if (same) {
|
||||
sql(
|
||||
"UPDATE artifacts SET title = ?, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?"
|
||||
@@ -272,9 +287,10 @@ function captureFromHook(sessionId, data) {
|
||||
const url = m[0].replace(/[\\"]+$/, "");
|
||||
if (!PAGE_URL_RE.test(url)) return null;
|
||||
const ownerId = sessionOwner(sessionId);
|
||||
const same = sql(
|
||||
"SELECT * FROM artifacts WHERE kind = 'page' AND url = ? AND owner_id IS ?"
|
||||
).get(url, ownerId);
|
||||
const same = sql("SELECT * FROM artifacts WHERE kind = 'page' AND url = ? AND owner_id IS ?").get(
|
||||
url,
|
||||
ownerId
|
||||
);
|
||||
if (same) return same;
|
||||
const file = typeof input.file_path === "string" ? input.file_path : "";
|
||||
return insert({
|
||||
@@ -370,7 +386,7 @@ async function pinFile(req, { laneId, path: rel, title, description, sessionId }
|
||||
kind: "file",
|
||||
title: cleanTitle(title, name),
|
||||
description: cleanDescription(description),
|
||||
owner_id: req?.user ? req.user.id : lane.owner_id ?? null,
|
||||
owner_id: req?.user ? req.user.id : (lane.owner_id ?? null),
|
||||
lane_id: lane.id,
|
||||
session_id: sessionId ? String(sessionId) : null,
|
||||
source: relPosix,
|
||||
@@ -391,7 +407,11 @@ function uploadFile(req, { name, data, title, description }) {
|
||||
if (data.length > FILE_MAX_BYTES) throw fail("ETOOBIG", "a file artifact is at most 25 MB");
|
||||
const base = path.posix.basename(String(name || "").replace(/\\/g, "/"));
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const clean = base.replace(/[\x00-\x1f/]/g, "").replace(/^\.+/, "").slice(0, 200) || "file";
|
||||
const clean =
|
||||
base
|
||||
.replace(/[\x00-\x1f/]/g, "")
|
||||
.replace(/^\.+/, "")
|
||||
.slice(0, 200) || "file";
|
||||
const snap = newSnapshotDir();
|
||||
try {
|
||||
fs.writeFileSync(path.join(snap.dir, clean), data, { mode: 0o600 });
|
||||
@@ -530,7 +550,8 @@ function addSkill(req, { name, laneId, title, description }) {
|
||||
if (!inside(top, real) || path.basename(real) !== name) {
|
||||
throw fail("ESYMLINK", "the skill folder is a link elsewhere");
|
||||
}
|
||||
if (!fs.existsSync(path.join(real, "SKILL.md"))) throw fail("ENOFILE", "no SKILL.md in that folder");
|
||||
if (!fs.existsSync(path.join(real, "SKILL.md")))
|
||||
throw fail("ENOFILE", "no SKILL.md in that folder");
|
||||
const { files } = walkSkill(real);
|
||||
const runAs = require("./run-as");
|
||||
return storeSkill(req, {
|
||||
@@ -577,7 +598,10 @@ function storeSkill(req, { name, files, title, description, laneId = null }) {
|
||||
}
|
||||
let summary = "";
|
||||
try {
|
||||
summary = frontmatterField(fs.readFileSync(path.join(snap.dir, "SKILL.md"), "utf8"), "description");
|
||||
summary = frontmatterField(
|
||||
fs.readFileSync(path.join(snap.dir, "SKILL.md"), "utf8"),
|
||||
"description"
|
||||
);
|
||||
} catch {
|
||||
/* no frontmatter */
|
||||
}
|
||||
@@ -624,7 +648,10 @@ function skillSlug(text) {
|
||||
function validSkillName(raw) {
|
||||
const name = skillSlug(raw);
|
||||
if (!SKILL_NAME_RE.test(name)) {
|
||||
throw fail("EBADNAME", "skill name: letters, digits, '.', '_' or '-' (it becomes the folder and the /command)");
|
||||
throw fail(
|
||||
"EBADNAME",
|
||||
"skill name: letters, digits, '.', '_' or '-' (it becomes the folder and the /command)"
|
||||
);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
@@ -638,8 +665,10 @@ function cleanUploadPath(raw) {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
if (!p || /[\x00-\x1f]/.test(p)) throw fail("EBADPATH", "an uploaded file has no usable name");
|
||||
const parts = p.split("/").filter(Boolean);
|
||||
if (parts.some((x) => x === ".." || x === ".")) throw fail("EBADPATH", `not a path inside the skill: ${p}`);
|
||||
if (parts.length > SKILL_MAX_DEPTH + 2) throw fail("ETOOBIG", "the skill folder is nested too deep");
|
||||
if (parts.some((x) => x === ".." || x === "."))
|
||||
throw fail("EBADPATH", `not a path inside the skill: ${p}`);
|
||||
if (parts.length > SKILL_MAX_DEPTH + 2)
|
||||
throw fail("ETOOBIG", "the skill folder is nested too deep");
|
||||
return parts.join("/");
|
||||
}
|
||||
|
||||
@@ -684,7 +713,9 @@ function skillsFromUpload(uploads, { name, description }) {
|
||||
const p = cleanUploadPath(u.path);
|
||||
if (JUNK_RE.test(p)) continue;
|
||||
if (ZIP_RE.test(p) && uploads.length === 1) {
|
||||
files.push(...unzipSkill(u.data).map((f) => ({ path: cleanUploadPath(f.path), data: f.data })));
|
||||
files.push(
|
||||
...unzipSkill(u.data).map((f) => ({ path: cleanUploadPath(f.path), data: f.data }))
|
||||
);
|
||||
} else {
|
||||
files.push({ path: p, data: u.data });
|
||||
}
|
||||
@@ -760,8 +791,16 @@ function checkSkillFiles(files) {
|
||||
function withFrontmatter(text, name, description) {
|
||||
const body = String(text).replace(/^\uFEFF/, "");
|
||||
const fm = /^---\r?\n([\s\S]*?)\r?\n---[^\n]*(\r?\n|$)/.exec(body);
|
||||
const desc = String(description || "").trim().replace(/\s+/g, " ");
|
||||
const quote = (v) => (/^[\w .,()/-]*$/.test(v) && !/^[\d.]+$/.test(v) ? v : JSON.stringify(v));
|
||||
const desc = String(description || "")
|
||||
.trim()
|
||||
.replace(/\s+/g, " ");
|
||||
// Plain only when YAML cannot read it as anything else: starts with a
|
||||
// letter or digit (never `-`, `?`, `[`… — `- note` is a list item), no
|
||||
// trailing space, not a bare number. Anything else goes in double quotes.
|
||||
const quote = (v) =>
|
||||
/^[A-Za-z0-9][\w .,()/-]*$/.test(v) && !/\s$/.test(v) && !/^[\d.]+$/.test(v)
|
||||
? v
|
||||
: JSON.stringify(v);
|
||||
if (!fm) {
|
||||
if (!desc) {
|
||||
throw fail(
|
||||
@@ -773,12 +812,28 @@ function withFrontmatter(text, name, description) {
|
||||
}
|
||||
let lines = fm[1].split(/\r?\n/);
|
||||
const has = (k) => lines.some((l) => new RegExp(`^${k}:`).test(l));
|
||||
lines = has("name")
|
||||
? lines.map((l) => (/^name:/.test(l) ? `name: ${name}` : l))
|
||||
: [`name: ${name}`, ...lines];
|
||||
// Replace a top-level key AND its continuation lines (a `>`/`|` block or a
|
||||
// wrapped value is indented under it) — else the old text stays behind
|
||||
// and YAML folds it into the new value.
|
||||
const setKey = (k, value) => {
|
||||
const out = [];
|
||||
let skipping = false;
|
||||
for (const l of lines) {
|
||||
if (new RegExp(`^${k}:`).test(l)) {
|
||||
out.push(`${k}: ${value}`);
|
||||
skipping = true;
|
||||
continue;
|
||||
}
|
||||
if (skipping && (/^\s/.test(l) || l === "")) continue;
|
||||
skipping = false;
|
||||
out.push(l);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
lines = has("name") ? setKey("name", name) : [`name: ${name}`, ...lines];
|
||||
if (desc) {
|
||||
lines = has("description")
|
||||
? lines.map((l) => (/^description:/.test(l) ? `description: ${quote(desc)}` : l))
|
||||
? setKey("description", quote(desc))
|
||||
: [...lines, `description: ${quote(desc)}`];
|
||||
} else if (!frontmatterField(body, "description")) {
|
||||
throw fail(
|
||||
@@ -835,7 +890,8 @@ function writeSkill(req, { name, description, content, title }) {
|
||||
const n = validSkillName(name);
|
||||
const text = typeof content === "string" ? content : "";
|
||||
if (!text.trim()) throw fail("EBADSKILL", "write the skill's instructions");
|
||||
if (Buffer.byteLength(text) > SKILL_MAX_BYTES) throw fail("ETOOBIG", "the skill is larger than 5 MB");
|
||||
if (Buffer.byteLength(text) > SKILL_MAX_BYTES)
|
||||
throw fail("ETOOBIG", "the skill is larger than 5 MB");
|
||||
return saveSkillFiles(req, {
|
||||
name: n,
|
||||
files: [{ path: "SKILL.md", data: Buffer.from(text, "utf8") }],
|
||||
@@ -889,15 +945,37 @@ async function fetchMarketJson(market) {
|
||||
if (/^https:\/\/.*\.json$/i.test(market)) {
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(market, { signal: AbortSignal.timeout(MARKET_TIMEOUT_MS), redirect: "follow" });
|
||||
res = await fetch(market, {
|
||||
signal: AbortSignal.timeout(MARKET_TIMEOUT_MS),
|
||||
redirect: "follow",
|
||||
});
|
||||
} catch (e) {
|
||||
throw fail("EMARKETFETCH", `could not read ${market}: ${e.message}`);
|
||||
}
|
||||
if (!res.url.startsWith("https://")) throw fail("EMARKETFETCH", "the link redirected off https");
|
||||
if (!res.url.startsWith("https://"))
|
||||
throw fail("EMARKETFETCH", "the link redirected off https");
|
||||
if (!res.ok) throw fail("EMARKETFETCH", `${market} answered ${res.status}`);
|
||||
const text = await res.text();
|
||||
if (text.length > MARKET_JSON_MAX) throw fail("ETOOBIG", "marketplace.json is larger than 1 MB");
|
||||
return text;
|
||||
// Read at most 1 MB: a link the user names may serve anything, and
|
||||
// `res.text()` would hold all of it in memory before the size check.
|
||||
const tooBig = () => fail("ETOOBIG", "marketplace.json is larger than 1 MB");
|
||||
if (Number(res.headers.get("content-length")) > MARKET_JSON_MAX) {
|
||||
res.body?.cancel().catch(() => {});
|
||||
throw tooBig();
|
||||
}
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
const reader = res.body?.getReader();
|
||||
while (reader) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
size += value.length;
|
||||
if (size > MARKET_JSON_MAX) {
|
||||
reader.cancel().catch(() => {});
|
||||
throw tooBig();
|
||||
}
|
||||
chunks.push(Buffer.from(value));
|
||||
}
|
||||
return Buffer.concat(chunks).toString("utf8");
|
||||
}
|
||||
const url = cloneUrl(market);
|
||||
if (!url) {
|
||||
@@ -912,32 +990,59 @@ async function fetchMarketJson(market) {
|
||||
// so a URL a browser names never receives a token stored for another use.
|
||||
const env = { GIT_TERMINAL_PROMPT: "0", GIT_ASKPASS: "", SSH_ASKPASS: "" };
|
||||
const safe = [
|
||||
"-c", "credential.helper=",
|
||||
"-c", "protocol.allow=never",
|
||||
"-c", "protocol.https.allow=always",
|
||||
"-c", "core.hooksPath=/dev/null",
|
||||
"-c",
|
||||
"credential.helper=",
|
||||
"-c",
|
||||
"protocol.allow=never",
|
||||
"-c",
|
||||
"protocol.https.allow=always",
|
||||
"-c",
|
||||
"core.hooksPath=/dev/null",
|
||||
];
|
||||
try {
|
||||
try {
|
||||
await git(tmp, [...safe, "clone", "--depth", "1", "--filter=blob:none", "--no-checkout", "--quiet", "--", url, "repo"], {
|
||||
literal: true,
|
||||
timeout: MARKET_TIMEOUT_MS,
|
||||
env,
|
||||
});
|
||||
await git(
|
||||
tmp,
|
||||
[
|
||||
...safe,
|
||||
"clone",
|
||||
"--depth",
|
||||
"1",
|
||||
"--filter=blob:none",
|
||||
"--no-checkout",
|
||||
"--quiet",
|
||||
"--",
|
||||
url,
|
||||
"repo",
|
||||
],
|
||||
{
|
||||
literal: true,
|
||||
timeout: MARKET_TIMEOUT_MS,
|
||||
env,
|
||||
}
|
||||
);
|
||||
} catch (e) {
|
||||
const why = String(e?.git?.stderr || e?.stderr || e?.message || "");
|
||||
if (/terminal prompts disabled|could not read Username|Authentication failed|403|401/i.test(why)) {
|
||||
if (
|
||||
/terminal prompts disabled|could not read Username|Authentication failed|403|401/i.test(why)
|
||||
) {
|
||||
throw fail(
|
||||
"ENEEDLOGIN",
|
||||
"the repository does not exist, or it needs a login to read — check the link, or type the plugin as name@marketplace by hand (installing uses each user's own git login)"
|
||||
);
|
||||
}
|
||||
if (/not found|does not exist|404/i.test(why)) throw fail("EMARKETFETCH", "no repository at that link");
|
||||
if (/not found|does not exist|404/i.test(why))
|
||||
throw fail("EMARKETFETCH", "no repository at that link");
|
||||
throw fail("EMARKETFETCH", `could not read the repository: ${why.trim().split("\n").pop()}`);
|
||||
}
|
||||
const repo = path.join(tmp, "repo");
|
||||
const show = (p) =>
|
||||
git(repo, ["show", `HEAD:${p}`], { literal: true, timeout: MARKET_TIMEOUT_MS, env, maxBuffer: MARKET_JSON_MAX }).then(
|
||||
git(repo, ["show", `HEAD:${p}`], {
|
||||
literal: true,
|
||||
timeout: MARKET_TIMEOUT_MS,
|
||||
env,
|
||||
maxBuffer: MARKET_JSON_MAX,
|
||||
}).then(
|
||||
(r) => (typeof r === "string" ? r : r.stdout),
|
||||
() => null
|
||||
);
|
||||
@@ -983,7 +1088,12 @@ async function inspectMarket(raw) {
|
||||
version: str(p.version, 50),
|
||||
category: str(p.category, 50),
|
||||
}));
|
||||
return { market, name, description: str(json.description || json.metadata?.description), plugins };
|
||||
return {
|
||||
market,
|
||||
name,
|
||||
description: str(json.description || json.metadata?.description),
|
||||
plugins,
|
||||
};
|
||||
}
|
||||
|
||||
function __setInspectImpl(fn) {
|
||||
@@ -999,10 +1109,9 @@ function addPlugin(req, { key, market, title, description }) {
|
||||
if (!PLUGIN_RE.test(k)) throw fail("EBADPLUGIN", "plugin: name@marketplace");
|
||||
const ownerId = req?.user ? req.user.id : null;
|
||||
const src = normalizeMarket(market);
|
||||
const same = sql("SELECT * FROM artifacts WHERE kind = 'plugin' AND source = ? AND owner_id IS ?").get(
|
||||
k,
|
||||
ownerId
|
||||
);
|
||||
const same = sql(
|
||||
"SELECT * FROM artifacts WHERE kind = 'plugin' AND source = ? AND owner_id IS ?"
|
||||
).get(k, ownerId);
|
||||
if (same) {
|
||||
sql(
|
||||
`UPDATE artifacts SET market = ?, title = ?, description = ?,
|
||||
@@ -1102,7 +1211,12 @@ function snapshotFile(req, id, rel) {
|
||||
const want = typeof rel === "string" && rel ? rel : files[0]?.path;
|
||||
const hit = files.find((f) => f.path === want);
|
||||
if (!hit) throw fail("ENOFILE", "no such file in this artifact");
|
||||
return { row, abs: path.join(root(), row.snapshot, ...hit.path.split("/")), name: path.basename(hit.path), size: hit.size };
|
||||
return {
|
||||
row,
|
||||
abs: path.join(root(), row.snapshot, ...hit.path.split("/")),
|
||||
name: path.basename(hit.path),
|
||||
size: hit.size,
|
||||
};
|
||||
}
|
||||
|
||||
// ── install ───────────────────────────────────────────────────────────────
|
||||
@@ -1146,7 +1260,10 @@ async function installSkill(req, row, { replace = false } = {}) {
|
||||
);
|
||||
if (acct) {
|
||||
if (!runAs.writeAsCanMove()) {
|
||||
throw fail("EUPGRADE", "replacing needs the updated helper: run `agenthub server install-system` once");
|
||||
throw fail(
|
||||
"EUPGRADE",
|
||||
"replacing needs the updated helper: run `agenthub server install-system` once"
|
||||
);
|
||||
}
|
||||
runAs.mkdirAs(acct, path.dirname(aside));
|
||||
await runAs.writeAsAsync(acct, target, ["move", aside]);
|
||||
|
||||
@@ -367,6 +367,7 @@ function deleteUser(username) {
|
||||
} catch {
|
||||
/* no personal profiles */
|
||||
}
|
||||
sql("DELETE FROM account_pins WHERE user_id = ?").run(u.id);
|
||||
sql("DELETE FROM users WHERE id = ?").run(u.id);
|
||||
return { id: u.id, username: u.username, workspaces: lanes.length };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* @file A background poll that slows down while it finds nothing to do: the
|
||||
* next pass runs `baseMs` after a pass that did work (or failed), `idleMs`
|
||||
* after one whose `tick` resolved `false` (nothing changed, nothing pending).
|
||||
* One pass at a time — the next is scheduled only once the last settled — and
|
||||
* every timer is `unref`'d. Used by the Cursor and Antigravity usage polls.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
/** Default slow interval: 60 s, never faster than the base one. */
|
||||
const idleDefault = (baseMs) => Math.max(baseMs, 60_000);
|
||||
|
||||
/**
|
||||
* Run `tick` now, then again and again. `tick` resolves `false` for an idle
|
||||
* pass; anything else (or a throw) keeps the base pace.
|
||||
* @returns {{stop: () => void}}
|
||||
*/
|
||||
function startBackoffPoll(tick, { baseMs, idleMs = idleDefault(baseMs) }) {
|
||||
let timer = null;
|
||||
let stopped = false;
|
||||
const schedule = (ms) => {
|
||||
if (stopped) return;
|
||||
timer = setTimeout(run, ms);
|
||||
if (timer.unref) timer.unref();
|
||||
};
|
||||
function run() {
|
||||
Promise.resolve()
|
||||
.then(tick)
|
||||
.then(
|
||||
(busy) => schedule(busy === false ? idleMs : baseMs),
|
||||
() => schedule(baseMs)
|
||||
);
|
||||
}
|
||||
run();
|
||||
return {
|
||||
stop() {
|
||||
stopped = true;
|
||||
clearTimeout(timer);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { startBackoffPoll, idleDefault };
|
||||
@@ -18,6 +18,10 @@
|
||||
* 3. least $ spent in the last 5 hours, then in the last 7 days — the
|
||||
* sessions its runs (`dashboard_runs.account`) held, over the hours they
|
||||
* held them (pool-usage.js).
|
||||
* An admin may switch a user to one account (account-pins.js): that user's
|
||||
* panes skip the ranking whenever they may use it, and a login is written
|
||||
* into their home at once (`switchHome`) — running panes take it at their
|
||||
* next credentials read, without a restart.
|
||||
* The quota is read with the account's own token in the background, at most
|
||||
* every `QUOTA_TTL_MS`; a token the usage endpoint refuses simply has no
|
||||
* reading, and ranking falls back to spend.
|
||||
@@ -193,6 +197,7 @@ function removeAccount(name) {
|
||||
}
|
||||
}
|
||||
fs.rmSync(fileOf(n));
|
||||
require("./account-pins").dropAccount("claude", n);
|
||||
quotaCache.delete(n);
|
||||
}
|
||||
|
||||
@@ -332,6 +337,40 @@ async function refreshLogins() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An admin's switch (account-pins.js): put pool login `name` into `member`'s
|
||||
* home NOW, over the pool login it holds — never over a login the member made
|
||||
* themselves. Every home's newer pair is copied back first (refreshLogins),
|
||||
* so the login leaving the home keeps its only live refresh token. Running
|
||||
* panes are not restarted: Claude Code takes the new pair when it next
|
||||
* re-reads its credentials (before a refresh), new panes at once. Answers
|
||||
* `switched`, `kept` (already there), `own-login` (left alone), `expired`, or
|
||||
* `next-session` (a setup-token, or no member home: it goes in at spawn).
|
||||
*/
|
||||
async function switchHome(member, name) {
|
||||
const first = readAccount(validName(name));
|
||||
if (!first) throw err("ENOACCOUNT", `no account ${name} in the pool`);
|
||||
if (first.kind !== "login" || !member || member.host) return "next-session";
|
||||
await refreshLogins();
|
||||
const a = readAccount(first.name);
|
||||
if (!a || expired(a)) return "expired";
|
||||
const disk = homeCreds(member);
|
||||
if (disk && ownsHome(a, member.name, disk)) return "kept";
|
||||
const holder = disk && allAccounts().find((x) => ownsHome(x, member.name, disk));
|
||||
if (disk && !holder) return "own-login";
|
||||
if (holder) {
|
||||
const placed = { ...holder.placed };
|
||||
delete placed[member.name];
|
||||
save({ ...holder, placed });
|
||||
}
|
||||
save(writeLogin(a, member));
|
||||
runAs().markClaudeOnboarded(member, {
|
||||
...(a.account ? { oauthAccount: a.account } : {}),
|
||||
...(a.userID ? { userID: a.userID } : {}),
|
||||
});
|
||||
return "switched";
|
||||
}
|
||||
|
||||
// ── Quota, read in the background ──────────────────────────────────────────
|
||||
|
||||
/** name → { at, fiveHour?, sevenDay?, error? } */
|
||||
@@ -434,10 +473,15 @@ function liveInHome(name, member) {
|
||||
});
|
||||
}
|
||||
|
||||
/** The full record a new Claude pane should run on, or null. `member` = run-as account. */
|
||||
function pick(member) {
|
||||
/**
|
||||
* The full record a new Claude pane should run on, or null. `member` = run-as
|
||||
* account; `ownerId` = the workspace owner, whose pin (account-pins.js) wins
|
||||
* over the ranking when this pane may use that account.
|
||||
*/
|
||||
function pick(member, ownerId = null) {
|
||||
let usable = allAccounts().filter((a) => !expired(a));
|
||||
if (usable.length === 0) return null;
|
||||
let live = null;
|
||||
if (!member) {
|
||||
// A host pane's home holds the host's own login — a pool account only when
|
||||
// it was moved in from there (`hostHolds`) and is still the pair on disk:
|
||||
@@ -453,10 +497,18 @@ function pick(member) {
|
||||
} else {
|
||||
// One .credentials.json per home: while a pane of theirs runs on a
|
||||
// pool login, the next pane stays on that one.
|
||||
const live = usable.find((a) => a.kind === "login" && liveInHome(a.name, member));
|
||||
if (live) return live;
|
||||
// The login in the home is the one they run on — after an admin's
|
||||
// switch (switchHome) it is no longer the one those panes started on.
|
||||
const liveLogin = usable.find((a) => a.kind === "login" && liveInHome(a.name, member));
|
||||
live = liveLogin ? placed || liveLogin : null;
|
||||
}
|
||||
}
|
||||
// A pinned token goes in by env and wins outright; a pinned login waits
|
||||
// while another login holds this home.
|
||||
const pin = require("./account-pins").pinFor(ownerId, "claude");
|
||||
const pinned = pin ? usable.find((a) => a.name === pin) : null;
|
||||
if (pinned && (pinned.kind === "token" || !live || live === pinned)) return pinned;
|
||||
if (live) return live;
|
||||
if (usable.length === 0) return null;
|
||||
refreshQuotas().catch(() => {});
|
||||
const ranked = usable
|
||||
@@ -489,8 +541,8 @@ function pick(member) {
|
||||
* background re-read. A `login` is offered for a member, and for a host pane
|
||||
* only when it is the host's own login (`hostHolds`), which stays as it is.
|
||||
*/
|
||||
function pickAccount(member = null) {
|
||||
const a = pick(member);
|
||||
function pickAccount(member = null, ownerId = null) {
|
||||
const a = pick(member, ownerId);
|
||||
if (!a) return null;
|
||||
return a.kind === "login"
|
||||
? { name: a.name, kind: "login" }
|
||||
@@ -502,8 +554,8 @@ function pickAccount(member = null) {
|
||||
* `env` goes through tmux `-e` (a member's launch file); `place()` runs just
|
||||
* before the pane starts and writes a login into the member's home.
|
||||
*/
|
||||
function forSpawn(member = null) {
|
||||
const a = pick(member);
|
||||
function forSpawn(member = null, ownerId = null) {
|
||||
const a = pick(member, ownerId);
|
||||
if (!a) return null;
|
||||
if (a.kind === "token") {
|
||||
return { name: a.name, env: { CLAUDE_CODE_OAUTH_TOKEN: a.token }, place: () => {} };
|
||||
@@ -524,8 +576,12 @@ function forSpawn(member = null) {
|
||||
};
|
||||
}
|
||||
|
||||
/** Is `name` an account in the pool (any state)? */
|
||||
const hasAccount = (name) => NAME_RE.test(String(name)) && Boolean(readAccount(String(name)));
|
||||
|
||||
module.exports = {
|
||||
BLOCK_PERCENT,
|
||||
hasAccount,
|
||||
REFRESH_AHEAD_MS,
|
||||
addAccount,
|
||||
addLoginAccount,
|
||||
@@ -533,6 +589,7 @@ module.exports = {
|
||||
poolStatus,
|
||||
pickAccount,
|
||||
forSpawn,
|
||||
switchHome,
|
||||
refreshQuotas,
|
||||
refreshLogins,
|
||||
__read: readAccount,
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
* the last 5 h, then 7 d. The reading is the newest `rate_limits` in the
|
||||
* rollouts of the sessions that account's runs started (no network), each
|
||||
* from the CODEX_HOME of the account its workspace runs as.
|
||||
* A user an admin pinned to one account (account-pins.js) skips the ranking.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
@@ -139,6 +140,7 @@ function removeAccount(name) {
|
||||
const n = validName(name);
|
||||
if (!readAccount(n)) throw err("ENOACCOUNT", `no account ${n} in the pool`);
|
||||
fs.rmSync(fileOf(n));
|
||||
require("./account-pins").dropAccount("codex", n);
|
||||
quotaCache = null;
|
||||
}
|
||||
|
||||
@@ -332,10 +334,15 @@ function syncBack() {
|
||||
|
||||
// ── Picking ────────────────────────────────────────────────────────────────
|
||||
|
||||
/** The full record a new Codex pane should run on, or null. `member` = run-as account. */
|
||||
function pick(member) {
|
||||
/**
|
||||
* The full record a new Codex pane should run on, or null. `member` = run-as
|
||||
* account; `ownerId` = the workspace owner, whose pin (account-pins.js) wins
|
||||
* over the ranking when this pane may use that account.
|
||||
*/
|
||||
function pick(member, ownerId = null) {
|
||||
let usable = allAccounts();
|
||||
if (usable.length === 0) return null;
|
||||
let live = null;
|
||||
if (!member) {
|
||||
// A host pane's CODEX_HOME holds the host's own login.
|
||||
usable = usable.filter((a) => a.kind === "apikey");
|
||||
@@ -348,10 +355,15 @@ function pick(member) {
|
||||
} else {
|
||||
// One auth.json per home: while a pane of theirs runs on a pool
|
||||
// login, the next pane stays on that one.
|
||||
const live = usable.find((a) => a.kind === "chatgpt" && liveInHome(a.name, member));
|
||||
if (live) return live;
|
||||
live = usable.find((a) => a.kind === "chatgpt" && liveInHome(a.name, member)) || null;
|
||||
}
|
||||
}
|
||||
// A pinned API key goes in by env and wins outright; a pinned ChatGPT login
|
||||
// waits while another login holds this home.
|
||||
const pin = require("./account-pins").pinFor(ownerId, "codex");
|
||||
const pinned = pin ? usable.find((a) => a.name === pin) : null;
|
||||
if (pinned && (pinned.kind === "apikey" || !live || live === pinned)) return pinned;
|
||||
if (live) return live;
|
||||
if (usable.length === 0) return null;
|
||||
const ranked = usable
|
||||
.map((a) => {
|
||||
@@ -395,8 +407,8 @@ function liveInHome(name, member) {
|
||||
}
|
||||
|
||||
/** `{name, kind}` of the account a new Codex pane would get, or null. */
|
||||
function pickAccount(member = null) {
|
||||
const a = pick(member);
|
||||
function pickAccount(member = null, ownerId = null) {
|
||||
const a = pick(member, ownerId);
|
||||
return a ? { name: a.name, kind: a.kind } : null;
|
||||
}
|
||||
|
||||
@@ -405,8 +417,8 @@ function pickAccount(member = null) {
|
||||
* this pane may use): `{name, argv, env, place}`. `env` goes through tmux `-e`
|
||||
* (a member's launch file); `place()` runs just before the pane starts.
|
||||
*/
|
||||
function forSpawn(member = null) {
|
||||
const a = pick(member);
|
||||
function forSpawn(member = null, ownerId = null) {
|
||||
const a = pick(member, ownerId);
|
||||
if (!a) return null;
|
||||
if (a.kind === "apikey") {
|
||||
const provider = `{name="OpenAI (AgentHub pool)",base_url="https://api.openai.com/v1",env_key="${KEY_ENV}",wire_api="responses"}`;
|
||||
@@ -439,8 +451,12 @@ function forSpawn(member = null) {
|
||||
};
|
||||
}
|
||||
|
||||
/** Is `name` an account in the pool? */
|
||||
const hasAccount = (name) => NAME_RE.test(String(name)) && Boolean(readAccount(String(name)));
|
||||
|
||||
module.exports = {
|
||||
BLOCK_PERCENT,
|
||||
hasAccount,
|
||||
addAccount,
|
||||
removeAccount,
|
||||
poolStatus,
|
||||
|
||||
@@ -235,7 +235,9 @@ function threadNames(home = getCodexHome()) {
|
||||
const names = new Map();
|
||||
let text = "";
|
||||
try {
|
||||
text = require("./run-as").readFileSafe(path.join(home, "session_index.jsonl"), "utf8", { max: 16 << 20 });
|
||||
text = require("./run-as").readFileSafe(path.join(home, "session_index.jsonl"), "utf8", {
|
||||
max: 16 << 20,
|
||||
});
|
||||
} catch {
|
||||
return names;
|
||||
}
|
||||
@@ -251,6 +253,17 @@ function threadNames(home = getCodexHome()) {
|
||||
}
|
||||
|
||||
const getRollout = db.prepare("SELECT * FROM codex_rollouts WHERE path = ?");
|
||||
// What a pass needs to skip an unchanged journal, for every journal at once:
|
||||
// one query per pass instead of one (with its whole parse state) per file.
|
||||
const rolloutStamps = db.prepare(
|
||||
`SELECT path, size, mtime_ms, instr(state, '"more":true') > 0 AS more FROM codex_rollouts`
|
||||
);
|
||||
// Journals that may still be growing outside the newest day folders: written
|
||||
// within RECENT_ROW_MS, or not yet read to the end.
|
||||
const liveRolloutPaths = db.prepare(
|
||||
`SELECT path FROM codex_rollouts WHERE mtime_ms > ? OR instr(state, '"more":true') > 0`
|
||||
);
|
||||
const threadPath = db.prepare("SELECT path FROM codex_rollouts WHERE thread_id = ? LIMIT 1");
|
||||
const upsertRollout = db.prepare(
|
||||
`INSERT INTO codex_rollouts (path, session_id, thread_id, size, mtime_ms, offset, state, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
|
||||
@@ -400,6 +413,59 @@ function writeSession(sessionId, names, now, origin = LOCAL) {
|
||||
|
||||
const running = new Map(); // home ("" = CODEX_HOME) → the pass in flight
|
||||
|
||||
// A RECENT pass (the poll's, between full ones) stats only the newest
|
||||
// RECENT_DAY_DIRS day folders plus the journals the table says may still grow
|
||||
// (RECENT_ROW_MS) — not every rollout Codex ever wrote. A journal in an older
|
||||
// folder that wakes up again (a resumed thread quiet for over RECENT_ROW_MS)
|
||||
// is picked up by the next full pass.
|
||||
const RECENT_DAY_DIRS = 2;
|
||||
const RECENT_ROW_MS = 60 * 60_000;
|
||||
|
||||
function numericDirs(dir) {
|
||||
try {
|
||||
return fs
|
||||
.readdirSync(dir, { withFileTypes: true })
|
||||
.filter((e) => e.isDirectory() && /^\d+$/.test(e.name))
|
||||
.map((e) => e.name)
|
||||
.sort((a, b) => Number(b) - Number(a));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function recentRolloutFiles(home, now) {
|
||||
const root = path.join(home || getCodexHome(), "sessions");
|
||||
const days = [];
|
||||
outer: for (const y of numericDirs(root))
|
||||
for (const m of numericDirs(path.join(root, y)))
|
||||
for (const d of numericDirs(path.join(root, y, m))) {
|
||||
days.push(path.join(root, y, m, d));
|
||||
if (days.length >= RECENT_DAY_DIRS) break outer;
|
||||
}
|
||||
const paths = new Set();
|
||||
for (const dir of days) {
|
||||
try {
|
||||
for (const e of fs.readdirSync(dir, { withFileTypes: true }))
|
||||
if (e.isFile() && /^rollout-.*\.jsonl$/.test(e.name)) paths.add(path.join(dir, e.name));
|
||||
} catch {
|
||||
/* vanished mid-scan */
|
||||
}
|
||||
}
|
||||
const prefix = root + path.sep;
|
||||
for (const { path: p } of liveRolloutPaths.all(now - RECENT_ROW_MS))
|
||||
if (p.startsWith(prefix)) paths.add(p);
|
||||
const out = [];
|
||||
for (const p of paths) {
|
||||
try {
|
||||
const stat = fs.statSync(p);
|
||||
if (stat.isFile()) out.push({ path: p, mtime: stat.mtimeMs, size: stat.size });
|
||||
} catch {
|
||||
/* gone */
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* One pass over every journal. Yields to the event loop between files; a
|
||||
* second call for the same home while one runs joins it. `home`, `source` and
|
||||
@@ -413,21 +479,42 @@ function ingestCodexUsage({
|
||||
home,
|
||||
source = LOCAL.source,
|
||||
activeMs = LOCAL.activeMs,
|
||||
recent = false,
|
||||
} = {}) {
|
||||
const key = home || "";
|
||||
if (running.has(key)) return running.get(key);
|
||||
const pass = (async () => {
|
||||
const files = allRolloutFiles(home);
|
||||
const files = recent ? recentRolloutFiles(home, now) : allRolloutFiles(home);
|
||||
const byThread = new Map();
|
||||
for (const f of files) {
|
||||
const m = FILE_NAME.exec(path.basename(f.path));
|
||||
if (m) byThread.set(m[1], f.path);
|
||||
}
|
||||
// A recent pass lists only part of the tree: a fork's parent may live in
|
||||
// an older folder, known to the table (or, failing that, to a full walk).
|
||||
let walkedAll = !recent;
|
||||
const parentPath = (id) => {
|
||||
if (byThread.has(id)) return byThread.get(id);
|
||||
if (walkedAll) return null;
|
||||
const known = threadPath.get(id)?.path;
|
||||
const root = path.join(home || getCodexHome(), "sessions") + path.sep;
|
||||
if (known && known.startsWith(root) && fs.existsSync(known)) return known;
|
||||
walkedAll = true;
|
||||
for (const f of allRolloutFiles(home)) {
|
||||
const m = FILE_NAME.exec(path.basename(f.path));
|
||||
if (m && !byThread.has(m[1])) byThread.set(m[1], f.path);
|
||||
}
|
||||
return byThread.get(id) || null;
|
||||
};
|
||||
const stamps = new Map();
|
||||
for (const r of rolloutStamps.all()) stamps.set(r.path, r);
|
||||
const touched = new Set();
|
||||
let read = 0;
|
||||
for (const f of files) {
|
||||
try {
|
||||
const mtime = Math.floor(f.mtime);
|
||||
const seen = stamps.get(f.path);
|
||||
if (seen && seen.size === f.size && seen.mtime_ms === mtime && !seen.more) continue;
|
||||
const row = getRollout.get(f.path);
|
||||
let offset = row ? row.offset : 0;
|
||||
let state = row ? JSON.parse(row.state) : {};
|
||||
@@ -439,7 +526,8 @@ function ingestCodexUsage({
|
||||
let skip = null;
|
||||
const parent = offset === 0 ? firstLineMeta(f.path).forked_from_id : state.forkedFrom;
|
||||
if (parent && !state.pastFork) {
|
||||
if (byThread.has(parent)) skip = await parentTotals(byThread.get(parent));
|
||||
const pp = parentPath(parent);
|
||||
if (pp) skip = await parentTotals(pp);
|
||||
else if (offset === 0)
|
||||
console.warn(`[codex-usage] fork parent ${parent} not found; ${f.path} may overcount`);
|
||||
}
|
||||
@@ -508,10 +596,15 @@ function startCodexUsagePoll(broadcast) {
|
||||
.memberHomes()
|
||||
.map((h) => path.join(h, ".codex")),
|
||||
];
|
||||
// Every FULL_EVERY-th pass (and the first) walks every journal; the others
|
||||
// only the recent ones (recentRolloutFiles).
|
||||
const FULL_EVERY = Math.max(1, Math.round((5 * 60_000) / POLL_MS));
|
||||
let passNo = 0;
|
||||
const ingestAll = async () => {
|
||||
const total = { sessions: 0 };
|
||||
const recent = passNo++ % FULL_EVERY !== 0;
|
||||
for (const home of homes()) {
|
||||
const r = await ingestCodexUsage({ broadcast, home });
|
||||
const r = await ingestCodexUsage({ broadcast, home, recent });
|
||||
total.sessions += r?.sessions || 0;
|
||||
}
|
||||
return total;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user