perf: v2.5.10 — ready for 10+ concurrent users, leaner locally
Measured on a copy of a real 1.2 GB / 253K-event database, 10 simulated browsers + 10 hooks/s for 90 s: event-loop delay p99 1239 ms → 32 ms (max 2.0 s → 94 ms), 266 failed requests → 0, 74 → 111 requests/s served, server RSS 633 → 346 MB. Entry bundle 975 KB raw → 394 KB (106 KB brotli). Server - /api/analytics: the events-table scans run in the read worker (scoped-stats eventAggregates, read-pool job analyticsEvents); runRead takes maxAgeMs — analytics 10 s, /api/workflows 30 s — keyed by the args - /api/workflows/skill-usage: +event_type and a tool_name range instead of LIKE, so it uses idx_events_tool (784 ms → a few ms) - idx_events_session_type_tool (session_id, event_type, tool_name, created_at) replaces idx_events_session_type: covering reads for session stats, the hook dedupes and the import resume point (1.2 s → 20 ms); 64 MB cache_size and 256 MB mmap_size on both connections - WAL: the server sets wal_autocheckpoint = 0 and checkpoints PASSIVE every DASHBOARD_WAL_CHECKPOINT_MS (5 s) from the read worker's own writable connection; a failed checkpoint restores the automatic one (hook COMMIT p95 109 ms → 15 ms at 100 hooks/s) - tmux: one list-sessions answers a whole GET /api/lanes and the heal beat (liveSessions), shared for 1 s and cleared by this process's new/kill — GET /api/run's sync spawns had blocked 60 s of a 90 s run; the heal beat skips tmux when nothing runs; attach options chained into 2 spawns - hooks: TurnDuration/APIError deduped against one read per hook instead of a query per transcript entry (23 ms/hook on a 763-turn session); one lane scan per hook; hourly upserts skip rows that did not grow; frames are sent after the transaction commits (and after the pane binding); new_event carries its row id; a split pane's (slot 1–9) hooks no longer rebind the lane's session_id - watchdog liveness probe runs ps asynchronously; transcript newline scan via indexOf; startup subagent backfill fingerprints the files it already checked - pty attach: backpressure (pause past 1 MB unsent, resume under 256 KB) - static: hashed assets served from their pre-compressed .br/.gz sibling Client - hidden tabs neither refetch on WS events nor poll (useLiveRefresh, panes, lane cards, git header, changes panel, settings); no per-tab hourly /updates/check (the server already checks) - refetch storms throttled (workspace tree/session list 3 s, /api/run only on a run-key change, notification pane lookup only when shown); WS reconnect jitter; terminal retry backoff 1.5 → 30 s, stops on 1008 - heavier throttles for aggregates (15 s) and detail views; Monitor keepIfSame; GET in-flight dedupe in request() - lazy Dashboard/History, xterm (with the first terminal), lane modals, Sagi (only while enabled); only the active locale loads; Workspace chunk prefetched on a /workspace deep link - Sagi: no work while disabled, pupil via CSS variables, memo avatar - build: .br/.gz siblings, sourcemap hidden; service worker no longer caches /assets/ (cache v3 drops the old one) Tests: scripts/test-server.js drops the GIT_DIR-family variables a hook exports, so a suite run from a linked worktree's pre-commit can no longer commit into the real repository or set core.bare. Docs: ARCHITECTURE, DATABASE, API, DEPLOYMENT, client README, docs/plans/perf/README.md (audit, checklist, results).
This commit is contained in:
+7
-3
@@ -333,7 +333,7 @@ graph TD
|
||||
| `lib/webhooks.js` | Universal webhook delivery engine driven by the provider registry. `buildRequest()` resolves the URL, formats the provider-native payload, and assembles headers (provider auth headers + generic-family custom headers + optional HMAC-SHA256 signature via `X-Webhook-Signature` / `X-Webhook-Timestamp`). `dispatchAlert()` fans a fired alert out to every enabled, in-scope target (optional per-rule scoping via `rule_ids`); each `deliver()` POSTs with an `AbortController` timeout and bounded retry/backoff (retries transport errors / 429 / 5xx, never other 4xx) and records the attempt-chain outcome in `webhook_deliveries` (pruned to the newest 2000 rows). Delivery is detached and fully fail-safe — it never throws into the alert path. Enabled targets are cached like alert rules; tunables (`WEBHOOK_TIMEOUT_MS`, `WEBHOOK_MAX_ATTEMPTS`, `WEBHOOK_RETRY_BASE_MS`) are env-overridable. `sendTest()` awaits a synthetic delivery for the test endpoint |
|
||||
| `routes/workflows.js` | Aggregate workflow visualization data (agent orchestration graphs, tool transition flows, collaboration networks, workflow pattern detection, model delegation, error propagation, concurrency timelines, session complexity metrics, compaction impact). Accepts `?status=active\|completed` query parameter to filter all data by session status and `?sections=a,b` to compute only those parts. The `GET /` bundle itself lives in `lib/workflow-stats.js` and runs in the read worker (`lib/read-pool.js`). `GET /api/workflows/skill-usage` reports per-skill and per-plugin call counts, counting `PreToolUse` rows only so a call is not double-counted against its `PostToolUse` twin. Per-session drill-in endpoint with agent tree, tool timeline, and event details |
|
||||
| `lib/workflow-stats.js` | The eleven `GET /api/workflows` aggregations as pure reads over a passed-in connection (`computeWorkflowData(conn, status, sections)`), so they run in the read worker. `stats.topFlow` is the head of `toolFlow.transitions`: tool pairs come from one `LEAD() OVER (PARTITION BY session_id ORDER BY id)` pass — never a correlated `MIN(id) … id > ?` per event, which is quadratic in a session's size |
|
||||
| `lib/read-pool.js` | Heavy read-only jobs off the event loop: one worker thread with its own `query_only` connection (same driver order as `db.js`), identical in-flight calls shared, a job past `AGENTHUB_READ_TIMEOUT_MS` (60 s) refused `EREADTIMEOUT` and its worker replaced, inline when `AGENTHUB_READ_WORKER=0` or a worker cannot start. Add a job to `JOBS` to move another aggregate there |
|
||||
| `lib/read-pool.js` | Heavy read-only jobs off the event loop: one worker thread with its own `query_only` connection (same driver order as `db.js`), identical in-flight calls shared, a caller's `maxAgeMs` reusing a result that young (`/api/workflows` 30 s, `/api/analytics`'s events scans 10 s — args are the key, so a member's scoped result is never shared), a job past `AGENTHUB_READ_TIMEOUT_MS` (60 s) refused `EREADTIMEOUT` and its worker replaced, inline when `AGENTHUB_READ_WORKER=0` or a worker cannot start. Add a job to `JOBS` to move another aggregate there. The server's WAL checkpoint (`walCheckpoint`, every `DASHBOARD_WAL_CHECKPOINT_MS`, default 5 s) also runs here, on a second writable connection of the worker: the main connection sets `wal_autocheckpoint = 0`, so no hook's `COMMIT` pays for a checkpoint; a failed checkpoint turns the automatic one back on |
|
||||
| `lib/transcript-cache.js` | Stat-based JSONL transcript cache with incremental byte-offset reads. Shared between `hooks.js` (token extraction on every event) and the periodic compaction scanner (`index.js`). Extracts tokens, compaction entries, API errors (`isApiErrorMessage` + raw error responses), turn durations (`system` subtype `turn_duration`), thinking block counts, usage extras (service_tier, speed, inference_geo), user-interrupt markers (the transcript `[Request interrupted by user]` entry / `interruptedMessageId` field — surfaced as `pendingInterrupt`, computed from transcript ordering: latest interrupt vs latest real turn activity, both on Claude Code's clock), and the latest session title — `custom-title` (`/rename`, `claude -n`, picker Ctrl+R) and `ai-title` (auto / plan-accept), append-only so the last value wins, carried through both full and incremental reads — plus the session's **first user prompt** (`firstUserMessage`: tool-result, meta/caveat, slash-command plumbing, compact-summary, and interrupt entries skipped; whitespace-collapsed, capped at 500 chars; first value wins across incremental reads), used as a fallback descriptor for placeholder-named sessions/agents. Uses `(path, mtime, size)` cache key — unchanged files return cached results instantly, grown files only parse new bytes, shrunk files (compaction) trigger full re-read. Each cache entry stores **only** `{mtimeMs, size, bytesRead, result}` — the previous shape that duplicated every growable array at both the top level and inside `result` is gone, halving steady-state memory per entry. Per-entry growable arrays (`turnDurations`, `errors`, `compaction.entries`, `usageExtras.*`) are bounded to `TRANSCRIPT_CACHE_MAX_ARRAY_LEN` (default `1000`, tail-kept) — older items remain in the `events` table thanks to hook dedup, so the cap only affects the in-memory view. Trimming runs both during parse (when an array reaches `2 * MAX_ARRAY_LEN`, amortized O(N)) and at finalize, so even a fresh full-file parse on a multi-day session cannot accumulate an unbounded transient before returning. **Chunked sync byte-stream reader** (`_streamRange`, 4 MiB chunks split on `0x0A` bytes — safe across UTF-8 multibyte sequences — with a growable per-line byte buffer capped at 64 MiB) replaces the previous `readFileSync("utf8")` so transcripts larger than V8's max JS string length (~512 MiB on 64-bit Node 20) parse without aborting Node with `FATAL ERROR: v8::ToLocalChecked Empty MaybeLocal`. Both full and incremental reads share the same line-level state machine (`_initParseState` / `_consumeLine` / `_finalizeState`). LRU eviction caps at 200 entries. Entries evicted on SessionEnd and abandoned session cleanup |
|
||||
| `lib/session-liveness.js` | Process-liveness probe for the watchdog's dead-session reap. `probeLiveCwds()` enumerates running `claude` CLI processes (`ps -Ao pid=,args=`, then `lsof -a -p <pids> -d cwd -Fn` on macOS or `/proc/<pid>/cwd` on Linux) and returns the set of their working directories; `isClaudeCommand()` matches the bare binary and `node`/`bun`-launched shims while rejecting lookalikes (`claude-mem`, `Claude.app`). Fail-safe by contract: returns `available: false` (callers must change nothing) on Windows, inside containers (reuses `isInsideContainer` from `scripts/install-hooks.js` — host processes are invisible there, so an empty list would lie), on `ps`/`lsof` failure, or when `DASHBOARD_LIVENESS_PROBE=0` |
|
||||
| `bin/agenthub.js` | Dependency-free umbrella CLI (`agenthub <command>`) exposing the full dashboard surface in the terminal: monitoring (health / stats / kanban / tail via short-interval event polling), data browsing (sessions, per-session detail with an indented agent tree + cost + recent events, agents, events), insights (analytics, workflow intelligence, dynamic Workflow-tool runs, per-model cost), alerts + rules + webhook test probes, pricing CRUD, imports (rescan / scan-path), and administration (doctor, info, export, cleanup, reinstall-hooks, clear-data). Linked globally by `npm run setup` via a fail-soft `npm link` (`link-cli` script). Discovers the live server through `server/lib/server-info.js` (`~/.claude/.agenthub.json`, PID-liveness-checked) with `CLAUDE_DASHBOARD_PORT` / `DASHBOARD_PORT` env overrides and a 4820 fallback; renders a full terminal UI — box-drawn width-fitted tables with right-aligned numeric columns, status icons, inline bar charts (stats / analytics / cost), `├─`/`└─` agent trees, and a TTY spinner for `start` — whose ANSI styling degrades to plain text when piped (`--no-color` / `NO_COLOR` / `FORCE_COLOR` / `AGENTHUB_COLOR` respected); the one destructive command (`clear-data`) refuses to run without `--yes`. Server lifecycle: `agenthub status` shows a ●/○ up/down indicator and `agenthub start` boots a detached production server (waits for /api/health, logs to `data/agenthub-server.log`). `agenthub repl` (aliases `shell` / `i`) opens an interactive shell — a readline prompt with tab-completion (commands / subcommands / flags), persisted arrow-key history (`data/.agenthub_repl_history`), and a live server-status prompt; each entered line runs as a short-lived child `agenthub` process (via `runCommand` dispatch), so an offline refusal or a blocking `tail` cannot take the shell down, and piped input runs each line in order then exits at EOF. When the server is down, read-only commands (sessions / session / agents / events / kanban / stats / pricing list / alerts list / rules / export / doctor) fall back to direct SQLite reads of `data/dashboard.db` under a ⚠ Offline-mode banner — the connection is opened without SQLite readonly mode so a live WAL stays visible, and is SELECT-only by construction — while server-only commands (tail, analytics, workflows, runs, cost, mutations) refuse with the specific reason |
|
||||
@@ -911,10 +911,10 @@ erDiagram
|
||||
| `idx_agents_status` | agents | `status` | Kanban board column queries |
|
||||
| `idx_events_session_created` | events | `session_id, created_at` | A session's newest event / time order (watchdog every 15 s, every lane payload) |
|
||||
| `idx_events_tool` | events | `tool_name` | Per-tool counts (analytics, workflows) and the events filter's tool list without a scan of every event row |
|
||||
| `idx_events_session` | events | `session_id, id` | A session's events in insert order: every hook's duplicate guard reads the latest one. Not a prefix of `idx_events_session_type` (that one is not id-ordered); dropping it once made every hook sort its whole session |
|
||||
| `idx_events_session` | events | `session_id, id` | A session's events in insert order: every hook's duplicate guard reads the latest one. Not a prefix of `idx_events_session_type_tool` (that one is not id-ordered); dropping it once made every hook sort its whole session |
|
||||
| `idx_events_type` | events | `event_type` | Filter events by type |
|
||||
| `idx_events_created` | events | `created_at DESC` | Activity feed ordering |
|
||||
| `idx_events_session_type` | events | `session_id, event_type` | Per-session event-type filters |
|
||||
| `idx_events_session_type_tool` | events | `session_id, event_type, tool_name, created_at` | Per-session event-type filters, and a covering read for session stats (per-tool and per-type counts), the hook's TurnDuration/APIError dedupe and the import's newest-per-type resume point (1.2 s → 20 ms on a 29K-event session). Replaces `idx_events_session_type` (dropped at startup), so a hook writes no more index entries than before |
|
||||
| `idx_events_agent_type` | events | `agent_id, event_type` | `importSubagentFromJsonl` reads the agent's existing `tool_use_id`s once through it (it used to run a `data LIKE` per tool event) |
|
||||
| `idx_sessions_status` | sessions | `status` | Status filter on Sessions page and Kanban Sessions view |
|
||||
| `idx_sessions_started` | sessions | `started_at DESC` | Default sort order |
|
||||
@@ -966,6 +966,10 @@ All messages are JSON with this envelope:
|
||||
}
|
||||
```
|
||||
|
||||
Frames a hook produces are sent only after its transaction committed and its
|
||||
pane binding (`bindRunSession`) ran — in order, in the same tick — so no frame
|
||||
describes a rolled-back row. `new_event` carries the event's row `id` (additive).
|
||||
|
||||
The `remote_source.status` message (emitted by the **Remote Data Sources**
|
||||
sync poller and the `/api/remote-sources` routes) carries
|
||||
`{ id, status, error?, last_sync_at? }`, where `status` is one of
|
||||
|
||||
+1
-1
@@ -525,7 +525,7 @@ function App() {
|
||||
}
|
||||
```
|
||||
|
||||
The heavy pages — `Workspace` (xterm, the diff viewer), `SettingsHub` and `SessionDetail` — are `React.lazy` imports in `App.tsx`, each route wrapped in `<Suspense>` (the `Page` helper), so they load on first visit instead of in the initial bundle. `App.tsx` also mounts the app-wide `<Toaster />` and `<ConfirmHost />` once, beside `<GlobalTooltip />`.
|
||||
Every page — `Dashboard`, `History`, `Workspace` (the diff viewer), `SettingsHub`, `SessionDetail`, `SnapshotView` — is a `React.lazy` import in `App.tsx`, each route wrapped in `<Suspense>` (the `Page` helper), so it loads on first visit instead of in the initial bundle; `main.tsx` starts the Workspace chunk early on a `/workspace` deep link. xterm and its addons load with the first terminal (`loadXterm` in `TerminalView.tsx`), the sidebar's add/destructive workspace modals on first open, and Sagi only while it is enabled (`SagiMount`). Only the active UI language is fetched (`i18n/index.ts`, one lazy chunk per language; `main.tsx` renders once it is in). `vite build` writes hidden source maps and a `.br`/`.gz` sibling of every text asset ≥ 1 KB. `App.tsx` also mounts the app-wide `<Toaster />` and `<ConfirmHost />` once, beside `<GlobalTooltip />`.
|
||||
|
||||
### Navigation Flow
|
||||
|
||||
|
||||
+9
-21
@@ -1,12 +1,15 @@
|
||||
/**
|
||||
* @description Service Worker for caching static assets and handling push notifications.
|
||||
* @description Service Worker: network-first navigations with an offline fallback, and push
|
||||
* notifications. Hashed `/assets/` bundles are left to the HTTP cache (immutable).
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
// Bump this any time the SW logic changes - old clients will install the new
|
||||
// SW, drop their existing caches in `activate`, and `skipWaiting` so the
|
||||
// freshly-built bundle starts being served on the very next request.
|
||||
const CACHE_NAME = "dashboard-v2";
|
||||
// v3: drops v2's cache-first `/assets/` entries, which grew with every build
|
||||
// and were never pruned.
|
||||
const CACHE_NAME = "dashboard-v3";
|
||||
|
||||
self.addEventListener("install", () => {
|
||||
// No pre-cache: network-first below means the cache fills lazily, and
|
||||
@@ -39,25 +42,10 @@ self.addEventListener("fetch", (event) => {
|
||||
)
|
||||
return;
|
||||
|
||||
// Hashed bundles under /assets/ are immutable for a given URL - cache-first
|
||||
// is safe and fast. A new build emits new filenames, so stale entries simply
|
||||
// don't get re-requested.
|
||||
if (url.pathname.startsWith("/assets/")) {
|
||||
event.respondWith(
|
||||
caches.match(request).then(
|
||||
(cached) =>
|
||||
cached ||
|
||||
fetch(request).then((response) => {
|
||||
if (response.ok && response.type === "basic") {
|
||||
const clone = response.clone();
|
||||
caches.open(CACHE_NAME).then((cache) => cache.put(request, clone));
|
||||
}
|
||||
return response;
|
||||
})
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Hashed bundles under /assets/ are immutable and the server marks them so:
|
||||
// the browser's HTTP cache keeps them. Caching them here too only grew a
|
||||
// second copy of every build, forever.
|
||||
if (url.pathname.startsWith("/assets/")) return;
|
||||
|
||||
// Everything else (navigations, sw.js, manifest, icons, root /): network-first
|
||||
// with cache fallback. The user always gets the freshest UI while online and
|
||||
|
||||
+22
-7
@@ -38,8 +38,8 @@
|
||||
* ## Internal dependencies
|
||||
* - `./components/Layout`
|
||||
* - `./components/SplashScreen`
|
||||
* - `./pages/Dashboard`
|
||||
* - `./pages/History`
|
||||
* - `./pages/Dashboard` (lazy)
|
||||
* - `./pages/History` (lazy)
|
||||
* - `./pages/SessionDetail` (lazy)
|
||||
* - `./pages/SettingsHub` (lazy)
|
||||
* - `./pages/Workspace` (lazy)
|
||||
@@ -64,8 +64,6 @@ import { GlobalTooltip } from "./components/Tooltip";
|
||||
import { Toaster } from "./components/Toaster";
|
||||
import { ConfirmHost } from "./components/ConfirmHost";
|
||||
import { RouteErrorBoundary, reloadOnce } from "./components/RouteErrorBoundary";
|
||||
import { Dashboard } from "./pages/Dashboard";
|
||||
import { History } from "./pages/History";
|
||||
import { NotFound } from "./pages/NotFound";
|
||||
import { useWebSocket } from "./hooks/useWebSocket";
|
||||
import { useNotifications } from "./hooks/useNotifications";
|
||||
@@ -75,7 +73,10 @@ import { reloadOnNewBuild } from "./lib/newBuildReload";
|
||||
import type { WSMessage } from "./lib/types";
|
||||
|
||||
// The heavy pages (xterm, the diff viewer, the settings editors) load on first
|
||||
// visit instead of in the initial bundle.
|
||||
// visit instead of in the initial bundle — the Dashboard and History too, so the
|
||||
// entry chunk holds only the shell.
|
||||
const Dashboard = lazy(() => import("./pages/Dashboard").then((m) => ({ default: m.Dashboard })));
|
||||
const History = lazy(() => import("./pages/History").then((m) => ({ default: m.History })));
|
||||
const Workspace = lazy(() => import("./pages/Workspace").then((m) => ({ default: m.Workspace })));
|
||||
const SettingsHub = lazy(() =>
|
||||
import("./pages/SettingsHub").then((m) => ({ default: m.SettingsHub }))
|
||||
@@ -156,8 +157,22 @@ export default function App() {
|
||||
<DocumentTitle />
|
||||
<Routes>
|
||||
<Route element={<Layout wsConnected={connected} />}>
|
||||
<Route index element={<Dashboard />} />
|
||||
<Route path="sessions" element={<History />} />
|
||||
<Route
|
||||
index
|
||||
element={
|
||||
<Page>
|
||||
<Dashboard />
|
||||
</Page>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="sessions"
|
||||
element={
|
||||
<Page>
|
||||
<History />
|
||||
</Page>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="sessions/:id"
|
||||
element={
|
||||
|
||||
@@ -51,7 +51,7 @@
|
||||
* ## Internal dependencies
|
||||
* - `./Sidebar`
|
||||
* - `./UpdateNotifier`
|
||||
* - `./Sagi/Sagi`
|
||||
* - `./Sagi/SagiMount`
|
||||
*
|
||||
* ## Public surface
|
||||
* - `Layout` — exported API; see TSDoc on the symbol for behavior.
|
||||
@@ -81,7 +81,7 @@ import { Menu } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Sidebar, SIDEBAR_STORAGE_KEY, loadCollapsed } from "./Sidebar";
|
||||
import { UpdateNotifier } from "./UpdateNotifier";
|
||||
import { Sagi } from "./Sagi/Sagi";
|
||||
import { SagiMount } from "./Sagi/SagiMount";
|
||||
import { StatusBar } from "./StatusBar";
|
||||
|
||||
const WIDTH_KEY = "agenthub.sidebar.width";
|
||||
@@ -171,7 +171,7 @@ export function Layout({ wsConnected }: LayoutProps) {
|
||||
{t("skipToContent")}
|
||||
</a>
|
||||
<UpdateNotifier />
|
||||
<Sagi />
|
||||
<SagiMount />
|
||||
{drawer && drawerOpen && (
|
||||
<div
|
||||
aria-hidden
|
||||
|
||||
@@ -14,6 +14,7 @@ import { BellRing } from "lucide-react";
|
||||
import { api, type RunHandle } from "../lib/api";
|
||||
import { timeAgo } from "../lib/format";
|
||||
import { useLiveRefresh } from "../hooks/useLiveRefresh";
|
||||
import { laneChangeMatcher, runKeyOf } from "../lib/laneChange";
|
||||
import { workspaceHref } from "./SessionRowMenu";
|
||||
import type { Session } from "../lib/types";
|
||||
|
||||
@@ -32,6 +33,9 @@ export function NeedsYouStrip({ compact = false }: { compact?: boolean }) {
|
||||
setTotal(r.total);
|
||||
})
|
||||
.catch(() => undefined); // the strip is a shortcut; the pages show errors
|
||||
}, []);
|
||||
// The live panes (for the links) move only when a lane's run columns do.
|
||||
const loadRuns = useCallback(() => {
|
||||
api.run
|
||||
.list()
|
||||
.then((r) => setRuns(r.items))
|
||||
@@ -40,11 +44,14 @@ export function NeedsYouStrip({ compact = false }: { compact?: boolean }) {
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
loadRuns();
|
||||
}, [load, loadRuns]);
|
||||
useLiveRefresh(load, {
|
||||
intervalMs: 15000,
|
||||
match: (msg) => msg.type === "session_updated" || msg.type === "session_created",
|
||||
});
|
||||
const [runChanged] = useState(() => laneChangeMatcher(runKeyOf));
|
||||
useLiveRefresh(loadRuns, { intervalMs: 15000, match: runChanged });
|
||||
|
||||
if (sessions.length === 0) return null;
|
||||
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
/**
|
||||
* @file Sagi.tsx
|
||||
* @description Floating mascot companion shell. Mounts once (next to UpdateNotifier
|
||||
* in Layout) so it persists across routes and shares the single WebSocket.
|
||||
* @description Floating mascot companion shell. Mounted once by `SagiMount` (next
|
||||
* to UpdateNotifier in Layout), which loads this chunk only while the mascot is
|
||||
* 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
|
||||
* detection, and route navigation. Reactive personality + status/Ask come
|
||||
* from useSagiBrain; the avatar is draggable (AssistiveTouch-style) via
|
||||
@@ -81,6 +84,7 @@ import { SpeechBubble } from "./SpeechBubble";
|
||||
import { SagiPanel } from "./SagiPanel";
|
||||
import { useSagiBrain } from "./useSagiBrain";
|
||||
import { useSagiPosition } from "./useSagiPosition";
|
||||
import { useSagiEnabled } from "./SagiMount";
|
||||
import { matchIntent } from "./intents";
|
||||
import { sagiPrefs } from "./prefs";
|
||||
import { api } from "../../lib/api";
|
||||
@@ -195,9 +199,13 @@ function SagiFlyout({
|
||||
);
|
||||
}
|
||||
|
||||
/** Renders nothing — and runs no hook below — while the mascot is disabled. */
|
||||
export function Sagi() {
|
||||
return useSagiEnabled() ? <SagiBody /> : null;
|
||||
}
|
||||
|
||||
function SagiBody() {
|
||||
const { t } = useTranslation("settings");
|
||||
const [enabled, setEnabled] = useState(() => sagiPrefs.getEnabled());
|
||||
const [pet, setPet] = useState(() => sagiPrefs.getPet());
|
||||
const [size, setSize] = useState(() => sagiPrefs.getSize());
|
||||
const [open, setOpen] = useState(false);
|
||||
@@ -209,11 +217,11 @@ export function Sagi() {
|
||||
const brain = useSagiBrain();
|
||||
const place = useSagiPosition(size);
|
||||
|
||||
// Keep enabled, the pet and its size in sync with Settings / other tabs.
|
||||
// Keep the pet and its size in sync with Settings / other tabs (enabled is
|
||||
// the `Sagi` gate's: it unmounts this body when the mascot is turned off).
|
||||
useEffect(
|
||||
() =>
|
||||
sagiPrefs.subscribe(() => {
|
||||
setEnabled(sagiPrefs.getEnabled());
|
||||
setPet(sagiPrefs.getPet());
|
||||
setSize(sagiPrefs.getSize());
|
||||
}),
|
||||
@@ -223,7 +231,6 @@ export function Sagi() {
|
||||
// ⌘B / Ctrl+B toggles the panel; Esc closes it. Only while the mascot is
|
||||
// shown, and never from an editable field, where Ctrl+B belongs to the field.
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "b") {
|
||||
if (isEditable(e.target) || isEditable(document.activeElement)) return;
|
||||
@@ -235,7 +242,7 @@ export function Sagi() {
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [enabled]);
|
||||
}, []);
|
||||
|
||||
const onNavigate = useCallback(
|
||||
(route: string) => {
|
||||
@@ -279,8 +286,6 @@ export function Sagi() {
|
||||
[brain, navigate, t]
|
||||
);
|
||||
|
||||
if (!enabled) return null;
|
||||
|
||||
const anchor: Anchor = {
|
||||
left: place.left,
|
||||
top: place.top,
|
||||
|
||||
@@ -36,7 +36,7 @@
|
||||
* - `skills/file-headers/` — mandatory `@author` header policy.
|
||||
* ============================================================================= */
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { memo, useEffect, useRef } from "react";
|
||||
import type { Mood } from "./brain";
|
||||
|
||||
interface SagiAvatarProps {
|
||||
@@ -76,10 +76,21 @@ if (typeof window !== "undefined") {
|
||||
});
|
||||
}
|
||||
|
||||
export function SagiAvatar({ mood, reducedMotion, size = 68 }: SagiAvatarProps) {
|
||||
// The pupil offset is written as CSS variables on the root, never as state, so
|
||||
// following the cursor costs no React render.
|
||||
function setPupil(el: SVGSVGElement | null, x: number, y: number) {
|
||||
el?.style.setProperty("--sagi-px", `${x}px`);
|
||||
el?.style.setProperty("--sagi-py", `${y}px`);
|
||||
}
|
||||
|
||||
// memo: Sagi re-renders on every brain tick; the avatar only on mood/size/motion.
|
||||
export const SagiAvatar = memo(function SagiAvatar({
|
||||
mood,
|
||||
reducedMotion,
|
||||
size = 68,
|
||||
}: SagiAvatarProps) {
|
||||
const rootRef = useRef<SVGSVGElement | null>(null);
|
||||
const rafRef = useRef<number>();
|
||||
const [pupil, setPupil] = useState({ x: 0, y: 0 });
|
||||
|
||||
// Pupils follow the cursor whenever motion is allowed and the eyes are open.
|
||||
// (Only `sleeping` closes them by intent; `disconnected` hides the open-eye
|
||||
@@ -89,7 +100,7 @@ export function SagiAvatar({ mood, reducedMotion, size = 68 }: SagiAvatarProps)
|
||||
|
||||
useEffect(() => {
|
||||
if (!tracking) {
|
||||
setPupil({ x: 0, y: 0 });
|
||||
setPupil(rootRef.current, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -105,7 +116,7 @@ export function SagiAvatar({ mood, reducedMotion, size = 68 }: SagiAvatarProps)
|
||||
// Normalize then clamp to the eye socket range.
|
||||
const nx = (dx / dist) * Math.min(1, dist / 240);
|
||||
const ny = (dy / dist) * Math.min(1, dist / 240);
|
||||
setPupil({ x: nx * MAX_PUPIL_SHIFT, y: ny * MAX_PUPIL_SHIFT });
|
||||
setPupil(el, nx * MAX_PUPIL_SHIFT, ny * MAX_PUPIL_SHIFT);
|
||||
};
|
||||
|
||||
// Immediately aim at the last-known cursor (next frame, so layout is ready)
|
||||
@@ -202,7 +213,7 @@ export function SagiAvatar({ mood, reducedMotion, size = 68 }: SagiAvatarProps)
|
||||
<g className="sagi-eye sagi-eye-left">
|
||||
<g
|
||||
className="sagi-eye-track"
|
||||
style={{ transform: `translate(${pupil.x}px, ${pupil.y}px)` }}
|
||||
style={{ transform: "translate(var(--sagi-px, 0px), var(--sagi-py, 0px))" }}
|
||||
>
|
||||
<g className="sagi-eye-blink">
|
||||
<path
|
||||
@@ -226,7 +237,7 @@ export function SagiAvatar({ mood, reducedMotion, size = 68 }: SagiAvatarProps)
|
||||
<g className="sagi-eye sagi-eye-right">
|
||||
<g
|
||||
className="sagi-eye-track"
|
||||
style={{ transform: `translate(${pupil.x}px, ${pupil.y}px)` }}
|
||||
style={{ transform: "translate(var(--sagi-px, 0px), var(--sagi-py, 0px))" }}
|
||||
>
|
||||
<g className="sagi-eye-blink">
|
||||
<path
|
||||
@@ -792,4 +803,4 @@ export function SagiAvatar({ mood, reducedMotion, size = 68 }: SagiAvatarProps)
|
||||
</g>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* @file SagiMount.tsx
|
||||
* @description Gate for the Sagi mascot: follows the enabled preference
|
||||
* (`useSagiEnabled`) and only while it is on lazy-loads and mounts `Sagi` — so
|
||||
* a disabled mascot costs no chunk download, no brain, no 1 Hz tick and no
|
||||
* WebSocket reducer.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { lazy, Suspense, useEffect, useState } from "react";
|
||||
import { sagiPrefs } from "./prefs";
|
||||
|
||||
const Sagi = lazy(() => import("./Sagi").then((m) => ({ default: m.Sagi })));
|
||||
|
||||
/** The mascot's enabled preference, followed live (Settings, other tabs). */
|
||||
export function useSagiEnabled(): boolean {
|
||||
const [enabled, setEnabled] = useState(() => sagiPrefs.getEnabled());
|
||||
useEffect(() => sagiPrefs.subscribe(() => setEnabled(sagiPrefs.getEnabled())), []);
|
||||
return enabled;
|
||||
}
|
||||
|
||||
export function SagiMount() {
|
||||
if (!useSagiEnabled()) return null;
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<Sagi />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
@@ -168,7 +168,10 @@ export function useSagiBrain(): SagiBrain {
|
||||
// Advance the clock so timed moods (stuck/sleeping, and exit from
|
||||
// happy/worried) re-evaluate without needing a new event.
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => setTick(Date.now()), 1000);
|
||||
// Hidden tab: no re-render; the first visible tick catches the mood up.
|
||||
const id = setInterval(() => {
|
||||
if (document.visibilityState === "visible") setTick(Date.now());
|
||||
}, 1000);
|
||||
return () => clearInterval(id);
|
||||
}, []);
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ interface SessionOverviewProps {
|
||||
}
|
||||
|
||||
/** Throttle window for stats refresh - coalesces bursts of hook events into one fetch. */
|
||||
const REFRESH_THROTTLE_MS = 1000;
|
||||
const REFRESH_THROTTLE_MS = 5000;
|
||||
|
||||
/** Compact tile used in the top stat row. */
|
||||
function StatTile({
|
||||
|
||||
@@ -22,8 +22,8 @@
|
||||
*
|
||||
* ## State sources
|
||||
* - Initial fetch via `api.updates.status()` on mount.
|
||||
* - Background re-check via `api.updates.check()` every hour
|
||||
* ({@link AUTO_CHECK_INTERVAL_MS}), plus the manual "Check now" button.
|
||||
* - No client-side background re-check: the server checks on its own
|
||||
* schedule and broadcasts `update_status`; "Check now" stays manual.
|
||||
* - Live refresh from WebSocket `update_status` events on {@link eventBus}.
|
||||
*
|
||||
* ## Dismissal persistence
|
||||
@@ -92,9 +92,6 @@ import type { UpdateStatusPayload, WSMessage } from "../lib/types";
|
||||
/** `localStorage` key storing the dismissed release tag (or upstream SHA). */
|
||||
const DISMISS_KEY = "agent-monitor-update-dismissed-sha";
|
||||
|
||||
/** How often to silently re-check for updates in the background. */
|
||||
const AUTO_CHECK_INTERVAL_MS = 60 * 60 * 1000;
|
||||
|
||||
/** Situations `POST /api/updates/apply` will actually act on. Mirrors the
|
||||
* server: `release_available` / `tracking_canonical` / `fork_or_diverged_tracking`
|
||||
* go through a git fast-forward, and `plugin_managed` goes through the detached
|
||||
@@ -172,19 +169,6 @@ export function UpdateNotifier() {
|
||||
});
|
||||
}, [syncFromPayload]);
|
||||
|
||||
// Background re-check every hour, on top of the initial mount fetch and the
|
||||
// manual "Check now" button — so a long-lived tab notices an update without
|
||||
// the user having to click anything.
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => {
|
||||
api.updates
|
||||
.check()
|
||||
.then(syncFromPayload)
|
||||
.catch(() => {});
|
||||
}, AUTO_CHECK_INTERVAL_MS);
|
||||
return () => clearInterval(id);
|
||||
}, [syncFromPayload]);
|
||||
|
||||
useEffect(() => {
|
||||
// An explicit "Check for updates" undoes both kinds of close.
|
||||
const handler = () => {
|
||||
|
||||
@@ -6,14 +6,23 @@
|
||||
* workspace — or `+` on its row — opens its home (`/workspace?lane=<id>`); a
|
||||
* live tab is opened from its session row. Live status comes from the shared
|
||||
* lane list (`useLanes`), live panes from `GET /api/run`, re-read whenever a
|
||||
* lane's status or session moves and handed over by the Workspace page's own
|
||||
* poll (`LIVE_RUNS_EVENT`). Owns its own Add-workspace and
|
||||
* destructive modals so the row menu works from any page. Which rows are
|
||||
* lane's status or session moves (at most every 3 s) and handed over by the
|
||||
* Workspace page's own poll (`LIVE_RUNS_EVENT`). Owns its own Add-workspace and
|
||||
* destructive modals (lazy-loaded on first open) so the row menu works from any page. Which rows are
|
||||
* expanded lives in `projectTreePrefs.ts` (`expanded`).
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type DragEvent } from "react";
|
||||
import {
|
||||
lazy,
|
||||
Suspense,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type DragEvent,
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useLocation, useNavigate } from "react-router-dom";
|
||||
import { Plus, Search } from "lucide-react";
|
||||
@@ -21,6 +30,7 @@ import { api, type CwdSuggestion, type RunHandle } from "../lib/api";
|
||||
import type { Lane } from "../lib/types";
|
||||
import { useLanes } from "../hooks/useLanes";
|
||||
import { useAiTools } from "../hooks/useAiTools";
|
||||
import { useThrottledValue } from "../hooks/useThrottledValue";
|
||||
import {
|
||||
insertionIndex,
|
||||
moveBefore,
|
||||
@@ -33,8 +43,15 @@ import { useProjectTreePrefs, writeProjectTreePrefs } from "../lib/projectTreePr
|
||||
import { LANE_DRAG_TYPE, WorkspaceRow, isLaneDrag, workspaceName } from "./lanes/WorkspaceRow";
|
||||
import { WorkspaceSessionList } from "./lanes/WorkspaceSessionList";
|
||||
import { WorkspaceRowMenu, type WorkspaceMenuAction } from "./lanes/WorkspaceRowMenu";
|
||||
import { AddLaneModal } from "./lanes/AddLaneModal";
|
||||
import { DestructiveLaneModal } from "./lanes/DestructiveLaneModal";
|
||||
|
||||
// The sidebar is in the entry chunk; its two modals (and the run form the add
|
||||
// modal pulls in) load when first opened.
|
||||
const AddLaneModal = lazy(() =>
|
||||
import("./lanes/AddLaneModal").then((m) => ({ default: m.AddLaneModal }))
|
||||
);
|
||||
const DestructiveLaneModal = lazy(() =>
|
||||
import("./lanes/DestructiveLaneModal").then((m) => ({ default: m.DestructiveLaneModal }))
|
||||
);
|
||||
|
||||
/** The workspace (and attached run) the Workspace page shows, from its URL. */
|
||||
/** The workspace, pane run and replayed session the URL names (Workspace page only). */
|
||||
@@ -72,8 +89,12 @@ export function WorkspaceTree() {
|
||||
// A slot-0 pane starts, ends or learns its session id exactly when a lane's
|
||||
// status or session moves, so that is when the live-pane list is re-read;
|
||||
// the Workspace page also hands over every run list it polls (a tab in
|
||||
// slots 1–3 moves no lane column).
|
||||
const runKey = lanes.map((l) => `${l.id}:${l.status}:${l.session_id}:${l.run_id}`).join(",");
|
||||
// slots 1–3 moves no lane column). Throttled: with two sessions in one
|
||||
// workspace these columns flip on every hook, and each flip was a GET.
|
||||
const runKey = useThrottledValue(
|
||||
lanes.map((l) => `${l.id}:${l.status}:${l.session_id}:${l.run_id}`).join(","),
|
||||
3000
|
||||
);
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
api.run
|
||||
@@ -349,28 +370,32 @@ export function WorkspaceTree() {
|
||||
onAction={(a) => onMenuAction(menu.lane, a)}
|
||||
/>
|
||||
)}
|
||||
{destructive && (
|
||||
<DestructiveLaneModal
|
||||
lane={destructive.lane}
|
||||
action={destructive.action}
|
||||
open
|
||||
onClose={() => setDestructive(null)}
|
||||
onConfirm={(body) => void confirmDestructive(body)}
|
||||
/>
|
||||
)}
|
||||
<AddLaneModal
|
||||
open={addOpen}
|
||||
cwdSuggestions={cwdSuggestions}
|
||||
prefill={addPrefill}
|
||||
onClose={() => {
|
||||
setAddOpen(false);
|
||||
setAddPrefill(null);
|
||||
}}
|
||||
onAdded={(lane) => {
|
||||
void refreshLanes();
|
||||
select(lane.id);
|
||||
}}
|
||||
/>
|
||||
<Suspense fallback={null}>
|
||||
{destructive && (
|
||||
<DestructiveLaneModal
|
||||
lane={destructive.lane}
|
||||
action={destructive.action}
|
||||
open
|
||||
onClose={() => setDestructive(null)}
|
||||
onConfirm={(body) => void confirmDestructive(body)}
|
||||
/>
|
||||
)}
|
||||
{addOpen && (
|
||||
<AddLaneModal
|
||||
open
|
||||
cwdSuggestions={cwdSuggestions}
|
||||
prefill={addPrefill}
|
||||
onClose={() => {
|
||||
setAddOpen(false);
|
||||
setAddPrefill(null);
|
||||
}}
|
||||
onAdded={(lane) => {
|
||||
void refreshLanes();
|
||||
select(lane.id);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Suspense>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -242,6 +242,8 @@ export function ConversationView({ sessionId, initialTranscriptId }: Conversatio
|
||||
// also poll below to catch what WS misses.
|
||||
useEffect(() => {
|
||||
const unsubscribe = eventBus.subscribe((msg: WSMessage) => {
|
||||
// Hidden tab: the visibility handler below catches up once on show.
|
||||
if (document.visibilityState !== "visible") return;
|
||||
if (isRemoteDataRefreshMessage(msg)) {
|
||||
fetchNewMessages();
|
||||
return;
|
||||
|
||||
@@ -57,7 +57,10 @@ export function useLaneRuntime(laneId: number, bump: number): LaneRuntime | null
|
||||
});
|
||||
};
|
||||
read();
|
||||
const timer = setInterval(read, RUNTIME_REFRESH_MS);
|
||||
const timer = setInterval(
|
||||
() => document.visibilityState === "visible" && read(),
|
||||
RUNTIME_REFRESH_MS
|
||||
);
|
||||
return () => {
|
||||
alive = false;
|
||||
clearInterval(timer);
|
||||
@@ -88,7 +91,10 @@ function useLaneLocks(laneSlot: number | null): NamedLock[] {
|
||||
});
|
||||
};
|
||||
read();
|
||||
const timer = setInterval(read, LOCKS_REFRESH_MS);
|
||||
const timer = setInterval(
|
||||
() => document.visibilityState === "visible" && read(),
|
||||
LOCKS_REFRESH_MS
|
||||
);
|
||||
return () => {
|
||||
alive = false;
|
||||
clearInterval(timer);
|
||||
|
||||
@@ -880,7 +880,10 @@ export function LaneChangesPanel({
|
||||
void load();
|
||||
// Only the cheap shape polls; see the file header.
|
||||
if (mode !== "overview") return;
|
||||
const timer = window.setInterval(() => void load(), OVERVIEW_REFRESH_MS);
|
||||
const timer = window.setInterval(
|
||||
() => document.visibilityState === "visible" && void load(),
|
||||
OVERVIEW_REFRESH_MS
|
||||
);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [load, mode]);
|
||||
|
||||
|
||||
@@ -65,7 +65,10 @@ export function useLaneGitFacts(
|
||||
});
|
||||
};
|
||||
read();
|
||||
const timer = setInterval(read, GIT_REFRESH_MS);
|
||||
const timer = setInterval(
|
||||
() => document.visibilityState === "visible" && read(),
|
||||
GIT_REFRESH_MS
|
||||
);
|
||||
return () => {
|
||||
alive = false;
|
||||
clearInterval(timer);
|
||||
|
||||
@@ -43,6 +43,7 @@ import { timeAgo } from "../../lib/format";
|
||||
import { ConfirmModal } from "../ConfirmModal";
|
||||
import { AiToolIcon } from "../AiToolIcon";
|
||||
import { useAiTools } from "../../hooks/useAiTools";
|
||||
import { useThrottledValue } from "../../hooks/useThrottledValue";
|
||||
import { ContextMenu, MenuItem, MenuSeparator, useContextMenu } from "../ContextMenu";
|
||||
import { SessionMenu } from "./SessionMenu";
|
||||
|
||||
@@ -267,10 +268,16 @@ export function WorkspaceSessionList({
|
||||
);
|
||||
// The lane's own session/status/needs-you move on every hook, which is when
|
||||
// a session can appear or change state, and a tab opening or getting its
|
||||
// session is too — re-read then, not on a timer.
|
||||
const refreshKey = `${lane.session_id}:${lane.status}:${lane.needs_action}:${version}:${laneRuns
|
||||
.map((r) => `${r.id}=${r.sessionId ?? ""}`)
|
||||
.join(",")}`;
|
||||
// session is too — re-read then, not on a timer. Throttled to one re-read per
|
||||
// 3 s: two sessions in one workspace flip these on every hook. A rename or an
|
||||
// archive (`version`) re-reads at once.
|
||||
const hookKey = useThrottledValue(
|
||||
`${lane.session_id}:${lane.status}:${lane.needs_action}:${laneRuns
|
||||
.map((r) => `${r.id}=${r.sessionId ?? ""}`)
|
||||
.join(",")}`,
|
||||
3000
|
||||
);
|
||||
const refreshKey = `${hookKey}:${version}`;
|
||||
// A Terminal tab closing is when one joins the history.
|
||||
const shellKey = liveShells.map((r) => r.id).join(",");
|
||||
const [closedShells, setClosedShells] = useState<RunHistoryItem[]>([]);
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
* The socket auto-reconnects: a server restart kills the attach PTY, and
|
||||
* without a retry the pane silently freezes on its last painted frame — it
|
||||
* still LOOKS live, but no keystroke or mouse report reaches tmux again.
|
||||
* Retries back off from 1.5 s to 30 s (reset once a socket opens) and stop on
|
||||
* close code 1008. xterm and its addons are loaded on the first terminal
|
||||
* (`loadXterm`), not bundled with the Workspace chunk.
|
||||
* Always painted dark, in the palette of the user's chosen DARK theme
|
||||
* (`lib/terminalTheme.ts`), recoloured live without re-attaching.
|
||||
* An image dropped on it is saved on the server (`POST /api/run/drop-image`)
|
||||
@@ -32,12 +35,10 @@
|
||||
*/
|
||||
import { useEffect, useId, useMemo, useRef, useState, type DragEvent } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Terminal } from "@xterm/xterm";
|
||||
import { FitAddon } from "@xterm/addon-fit";
|
||||
import { CanvasAddon } from "@xterm/addon-canvas";
|
||||
import { ClipboardAddon, type IClipboardProvider } from "@xterm/addon-clipboard";
|
||||
import { SearchAddon } from "@xterm/addon-search";
|
||||
import { WebLinksAddon } from "@xterm/addon-web-links";
|
||||
import type { Terminal } from "@xterm/xterm";
|
||||
import type { CanvasAddon } from "@xterm/addon-canvas";
|
||||
import type { ClipboardAddon, IClipboardProvider } from "@xterm/addon-clipboard";
|
||||
import type { SearchAddon } from "@xterm/addon-search";
|
||||
import { ArrowDown, ArrowUp, X } from "lucide-react";
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
import { useTheme } from "../../hooks/useTheme";
|
||||
@@ -72,11 +73,49 @@ const clipboardProvider: IClipboardProvider = {
|
||||
if (text) void navigator.clipboard?.writeText(text).catch(() => undefined);
|
||||
},
|
||||
};
|
||||
// The addon's typings declare one argument, its code takes (base64, provider).
|
||||
const ClipboardWithProvider = ClipboardAddon as unknown as new (
|
||||
base64: undefined,
|
||||
provider: IClipboardProvider
|
||||
) => ClipboardAddon;
|
||||
|
||||
/** xterm and its addons (~400 KB) load with the first terminal, not with the
|
||||
* Workspace chunk. The result is cached, so every later pane (and a test that
|
||||
* awaits `loadXterm()` first) sets up synchronously. */
|
||||
const importXterm = async () => {
|
||||
const [xterm, fit, canvas, clipboard, search, links] = await Promise.all([
|
||||
import("@xterm/xterm"),
|
||||
import("@xterm/addon-fit"),
|
||||
import("@xterm/addon-canvas"),
|
||||
import("@xterm/addon-clipboard"),
|
||||
import("@xterm/addon-search"),
|
||||
import("@xterm/addon-web-links"),
|
||||
]);
|
||||
return {
|
||||
Terminal: xterm.Terminal,
|
||||
FitAddon: fit.FitAddon,
|
||||
CanvasAddon: canvas.CanvasAddon,
|
||||
SearchAddon: search.SearchAddon,
|
||||
WebLinksAddon: links.WebLinksAddon,
|
||||
// The addon's typings declare one argument, its code takes (base64, provider).
|
||||
ClipboardWithProvider: clipboard.ClipboardAddon as unknown as new (
|
||||
base64: undefined,
|
||||
provider: IClipboardProvider
|
||||
) => ClipboardAddon,
|
||||
};
|
||||
};
|
||||
type Xterm = Awaited<ReturnType<typeof importXterm>>;
|
||||
let xtermLoaded: Xterm | null = null;
|
||||
let xtermLoading: Promise<Xterm> | null = null;
|
||||
export function loadXterm(): Promise<Xterm> {
|
||||
xtermLoading ??= importXterm().then(
|
||||
(x) => (xtermLoaded = x),
|
||||
(err) => {
|
||||
xtermLoading = null; // a failed chunk fetch may be retried by the next pane
|
||||
throw err;
|
||||
}
|
||||
);
|
||||
return xtermLoading;
|
||||
}
|
||||
|
||||
/** Reconnect delay: 1.5 s, doubling per failed attempt up to 30 s. */
|
||||
const RETRY_MIN_MS = 1500;
|
||||
const RETRY_MAX_MS = 30_000;
|
||||
const hasFiles = (e: DragEvent) => Array.from(e.dataTransfer.types).includes("Files");
|
||||
|
||||
interface TerminalViewProps {
|
||||
@@ -160,265 +199,293 @@ export function TerminalView({ runId, wsBaseUrl, onExit, autoFocus = true }: Ter
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
// An explicit fontFamily pins every glyph to one bundled webfont. Left
|
||||
// unset, xterm falls back to the browser/OS default (`courier-new`),
|
||||
// which on Windows lacks Vietnamese precomposed diacritics — the OS then
|
||||
// substitutes those specific glyphs from a different face with a
|
||||
// mismatched advance width, corrupting the cell it's drawn into even
|
||||
// under the canvas renderer (which only stops a glyph from shoving its
|
||||
// *neighbours*, not from overflowing its own cell). JetBrains Mono is
|
||||
// already bundled for the rest of the UI; main.tsx additionally imports
|
||||
// its `vietnamese` subset so this covers the diacritics too.
|
||||
// NO `convertEol`. It rewrites every bare LF as CR+LF, i.e. it forces the
|
||||
// cursor to column 0 on a line feed — and xterm's own docs say not to use
|
||||
// it on a PTY, where termios already does that translation for the streams
|
||||
// that want it. tmux scrolls a pane by emitting a bare LF and then keeps
|
||||
// drawing at the column it was on; with this on, that draw landed at
|
||||
// column 0 instead, stamping the first characters of the line into the
|
||||
// left margin of the rows below. That is the torn left edge of issue #33,
|
||||
// and why it only showed up once content scrolled.
|
||||
const term = new Terminal({
|
||||
fontSize: 13,
|
||||
cursorBlink: true,
|
||||
fontFamily: '"JetBrains Mono", monospace',
|
||||
theme: paletteRef.current,
|
||||
screenReaderMode: readFlag(SCREEN_READER_KEY),
|
||||
});
|
||||
termRef.current = term;
|
||||
const fit = new FitAddon();
|
||||
term.loadAddon(fit);
|
||||
const search = new SearchAddon();
|
||||
term.loadAddon(search);
|
||||
searchRef.current = search;
|
||||
term.loadAddon(new ClipboardWithProvider(undefined, clipboardProvider));
|
||||
term.loadAddon(
|
||||
new WebLinksAddon((_e, uri) => {
|
||||
window.open(uri, "_blank", "noopener,noreferrer");
|
||||
})
|
||||
);
|
||||
if (containerRef.current) term.open(containerRef.current);
|
||||
term.textarea?.setAttribute("aria-describedby", hintId);
|
||||
|
||||
// Draw each cell at a fixed position instead of letting the browser lay the
|
||||
// row out as text. xterm's default DOM renderer aligns a row with a single
|
||||
// `letter-spacing`, which only holds while every glyph comes from one
|
||||
// monospace font — Vietnamese diacritics and CJK fall through to a fallback
|
||||
// face whose advance width differs, so glyphs shove their neighbours along
|
||||
// and the row's tail spills onto the row below. The buffer is correct
|
||||
// throughout (copying the line yields clean text); only the painting drifts,
|
||||
// and no CSS can correct it. Best-effort: a browser that cannot give a 2D
|
||||
// context keeps the DOM renderer rather than losing the terminal.
|
||||
let canvas: CanvasAddon | null = null;
|
||||
try {
|
||||
canvas = new CanvasAddon();
|
||||
term.loadAddon(canvas);
|
||||
} catch {
|
||||
canvas = null;
|
||||
}
|
||||
|
||||
fit.fit();
|
||||
// Take the keyboard as soon as the pane is on screen: the terminal IS the
|
||||
// page here, and having to click it first meant the first thing typed went
|
||||
// nowhere. A click elsewhere still moves focus away, as in any editor.
|
||||
if (autoFocusRef.current) term.focus();
|
||||
|
||||
// When the pane's program has NOT enabled wheel reporting, xterm falls back
|
||||
// to converting each wheel notch on an alt-screen buffer into a cursor-key
|
||||
// press (ESC[A / ESC[B). In a `claude` pane that reads as arrow up/down —
|
||||
// the wheel silently walks the prompt history instead of scrolling. Kill
|
||||
// ONLY that branch: xterm runs this same handler before sending a real SGR
|
||||
// mouse report too (`bindMouse`'s wheel case consults it), so a blanket
|
||||
// `false` also blocks tmux's own wheel scrolling. `x10` counts as off here
|
||||
// because that protocol reports button presses only, never the wheel — so
|
||||
// xterm takes the emulation path for it as well.
|
||||
term.attachCustomWheelEventHandler(() => {
|
||||
const mode = term.modes.mouseTrackingMode;
|
||||
const tracked = mode !== "none" && mode !== "x10";
|
||||
return tracked || term.buffer.active.type !== "alternate";
|
||||
});
|
||||
|
||||
// xterm sends Shift+Tab as ESC[Z but — unlike plain Tab — never marks the
|
||||
// event cancelled, so the browser still runs its default action and moves
|
||||
// focus out of the terminal. The pane then only ever sees the first press,
|
||||
// which is why `shift+tab to cycle` (permission mode in claude) looked dead
|
||||
// here while working in a real terminal. Returning true keeps xterm's own
|
||||
// handling; the preventDefault only stops focus from escaping.
|
||||
// Ctrl+M toggles "Tab moves focus" (VS Code's way out of its terminal);
|
||||
// in that mode Tab and Shift+Tab are not the pane's, so the browser moves
|
||||
// focus. Cmd+F / Ctrl+Shift+F open the find bar. Returning false keeps xterm from
|
||||
// handling — and from cancelling — the key.
|
||||
term.attachCustomKeyEventHandler((ev) => {
|
||||
if (ev.type !== "keydown") return true;
|
||||
const key = ev.key.toLowerCase();
|
||||
if (ev.ctrlKey && !ev.altKey && !ev.metaKey && !ev.shiftKey && key === "m") {
|
||||
ev.preventDefault();
|
||||
tabMovesRef.current = !tabMovesRef.current;
|
||||
setTabMoves(tabMovesRef.current);
|
||||
return false;
|
||||
}
|
||||
// Find: Cmd+F on macOS, Ctrl+Shift+F elsewhere — never plain Ctrl+F,
|
||||
// which is readline's forward-char (and bound by many TUIs).
|
||||
const findChord =
|
||||
!ev.altKey &&
|
||||
key === "f" &&
|
||||
((ev.metaKey && !ev.ctrlKey && !ev.shiftKey) || (ev.ctrlKey && ev.shiftKey && !ev.metaKey));
|
||||
if (findChord) {
|
||||
ev.preventDefault();
|
||||
setFind((f) => f ?? "");
|
||||
requestAnimationFrame(() => findInput.current?.focus());
|
||||
return false;
|
||||
}
|
||||
if (ev.key === "Tab" && tabMovesRef.current) return false;
|
||||
if (ev.key === "Tab" && ev.shiftKey) ev.preventDefault();
|
||||
return true;
|
||||
});
|
||||
|
||||
const decoder = new TextDecoder();
|
||||
let ws: WebSocket | null = null;
|
||||
|
||||
/**
|
||||
* Tell the server this terminal's size. tmux draws the pane at whatever
|
||||
* width it last heard, and a pane WIDER than xterm is silently corrupting:
|
||||
* every over-long row autowraps its tail onto the next row's left margin,
|
||||
* and tmux — believing that row unchanged — never repaints over it. The
|
||||
* result is stray characters glued to the left edge of blank lines, which
|
||||
* only becomes visible once a scroll repaints history. Reproduced with a
|
||||
* one-column difference; two columns leaves two characters per line.
|
||||
*
|
||||
* A zero-size fit is never reported: the console collapses with CSS
|
||||
* (`display:none` leaves the container 0×0), and fitting to that would
|
||||
* resize the real tmux pane down to nothing.
|
||||
*/
|
||||
const sendSizeNow = () => {
|
||||
if (!ws || ws.readyState !== WebSocket.OPEN) return;
|
||||
if (term.cols < 2 || term.rows < 2) return;
|
||||
ws.send(JSON.stringify({ type: "resize", cols: term.cols, rows: term.rows }));
|
||||
};
|
||||
// A divider drag or a window resize fires a resize per frame; tmux and the
|
||||
// program in the pane redraw on each, so the LAST size is sent once things
|
||||
// settle (trailing, 150 ms).
|
||||
let sizeTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
const sendSize = () => {
|
||||
if (sizeTimer) clearTimeout(sizeTimer);
|
||||
sizeTimer = setTimeout(() => {
|
||||
sizeTimer = null;
|
||||
sendSizeNow();
|
||||
}, 150);
|
||||
};
|
||||
let retryTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let ended = false; // server said the pane exited — nothing left to attach to
|
||||
let disposed = false;
|
||||
const attach = ({
|
||||
Terminal,
|
||||
FitAddon,
|
||||
CanvasAddon,
|
||||
SearchAddon,
|
||||
WebLinksAddon,
|
||||
ClipboardWithProvider,
|
||||
}: Xterm) => {
|
||||
// An explicit fontFamily pins every glyph to one bundled webfont. Left
|
||||
// unset, xterm falls back to the browser/OS default (`courier-new`),
|
||||
// which on Windows lacks Vietnamese precomposed diacritics — the OS then
|
||||
// substitutes those specific glyphs from a different face with a
|
||||
// mismatched advance width, corrupting the cell it's drawn into even
|
||||
// under the canvas renderer (which only stops a glyph from shoving its
|
||||
// *neighbours*, not from overflowing its own cell). JetBrains Mono is
|
||||
// already bundled for the rest of the UI; main.tsx additionally imports
|
||||
// its `vietnamese` subset so this covers the diacritics too.
|
||||
// NO `convertEol`. It rewrites every bare LF as CR+LF, i.e. it forces the
|
||||
// cursor to column 0 on a line feed — and xterm's own docs say not to use
|
||||
// it on a PTY, where termios already does that translation for the streams
|
||||
// that want it. tmux scrolls a pane by emitting a bare LF and then keeps
|
||||
// drawing at the column it was on; with this on, that draw landed at
|
||||
// column 0 instead, stamping the first characters of the line into the
|
||||
// left margin of the rows below. That is the torn left edge of issue #33,
|
||||
// and why it only showed up once content scrolled.
|
||||
const term = new Terminal({
|
||||
fontSize: 13,
|
||||
cursorBlink: true,
|
||||
fontFamily: '"JetBrains Mono", monospace',
|
||||
theme: paletteRef.current,
|
||||
screenReaderMode: readFlag(SCREEN_READER_KEY),
|
||||
});
|
||||
termRef.current = term;
|
||||
const fit = new FitAddon();
|
||||
term.loadAddon(fit);
|
||||
const search = new SearchAddon();
|
||||
term.loadAddon(search);
|
||||
searchRef.current = search;
|
||||
term.loadAddon(new ClipboardWithProvider(undefined, clipboardProvider));
|
||||
term.loadAddon(
|
||||
new WebLinksAddon((_e, uri) => {
|
||||
window.open(uri, "_blank", "noopener,noreferrer");
|
||||
})
|
||||
);
|
||||
if (containerRef.current) term.open(containerRef.current);
|
||||
term.textarea?.setAttribute("aria-describedby", hintId);
|
||||
|
||||
const connect = () => {
|
||||
// The attach itself carries this terminal's size. tmux sizes the window
|
||||
// to the client that attached most recently, so spawning the attach at a
|
||||
// default 80×24 and correcting it from the first `resize` message a beat
|
||||
// later makes the pane's program (claude) redraw its whole UI at 80
|
||||
// columns first — and everything painted at that width stays in the
|
||||
// scrollback as torn fragments along the left margin, visible as soon as
|
||||
// you scroll back (issue #33). Happens on every attach: page load,
|
||||
// lane switch, and each 1.5 s reconnect.
|
||||
const size = term.cols > 1 && term.rows > 1 ? `?cols=${term.cols}&rows=${term.rows}` : "";
|
||||
const sock = new WebSocket(`${wsBaseUrl}/ws-pty/${encodeURIComponent(runId)}${size}`);
|
||||
ws = sock;
|
||||
wsRef.current = sock;
|
||||
// Server sends PTY bytes as binary frames — default binaryType ("blob")
|
||||
// would hand onmessage a Blob that the string checks below never match,
|
||||
// silently dropping all terminal output. "arraybuffer" keeps it sync.
|
||||
sock.binaryType = "arraybuffer";
|
||||
// Draw each cell at a fixed position instead of letting the browser lay the
|
||||
// row out as text. xterm's default DOM renderer aligns a row with a single
|
||||
// `letter-spacing`, which only holds while every glyph comes from one
|
||||
// monospace font — Vietnamese diacritics and CJK fall through to a fallback
|
||||
// face whose advance width differs, so glyphs shove their neighbours along
|
||||
// and the row's tail spills onto the row below. The buffer is correct
|
||||
// throughout (copying the line yields clean text); only the painting drifts,
|
||||
// and no CSS can correct it. Best-effort: a browser that cannot give a 2D
|
||||
// context keeps the DOM renderer rather than losing the terminal.
|
||||
let canvas: CanvasAddon | null = null;
|
||||
try {
|
||||
canvas = new CanvasAddon();
|
||||
term.loadAddon(canvas);
|
||||
} catch {
|
||||
canvas = null;
|
||||
}
|
||||
|
||||
sock.onopen = () => {
|
||||
setReconnecting(false);
|
||||
sendSizeNow();
|
||||
};
|
||||
sock.onmessage = (event) => {
|
||||
const isArrayBuffer = Object.prototype.toString.call(event.data) === "[object ArrayBuffer]";
|
||||
// `stream: true` carries a UTF-8 multi-byte char's trailing bytes over
|
||||
// to the next decode() call when a PTY chunk splits mid-character —
|
||||
// without it, a Vietnamese/accented char split across two WS frames
|
||||
// decodes to garbage on both sides (U+FFFD or stray bytes).
|
||||
const data = isArrayBuffer
|
||||
? decoder.decode(event.data as ArrayBuffer, { stream: true })
|
||||
: event.data;
|
||||
if (typeof data === "string") {
|
||||
// A JSON control frame is the only thing that starts with `{"type"`.
|
||||
if (data.startsWith('{"type"')) {
|
||||
try {
|
||||
const msg = JSON.parse(data);
|
||||
if (msg.type === "exit") {
|
||||
ended = true;
|
||||
term.write(`\r\n${tRef.current("terminal.ended", { code: msg.code })}\r\n`);
|
||||
onExitRef.current?.();
|
||||
}
|
||||
return;
|
||||
} catch {
|
||||
/* not JSON — fall through and render as PTY output */
|
||||
}
|
||||
}
|
||||
term.write(data);
|
||||
fit.fit();
|
||||
// Take the keyboard as soon as the pane is on screen: the terminal IS the
|
||||
// page here, and having to click it first meant the first thing typed went
|
||||
// nowhere. A click elsewhere still moves focus away, as in any editor.
|
||||
if (autoFocusRef.current) term.focus();
|
||||
|
||||
// When the pane's program has NOT enabled wheel reporting, xterm falls back
|
||||
// to converting each wheel notch on an alt-screen buffer into a cursor-key
|
||||
// press (ESC[A / ESC[B). In a `claude` pane that reads as arrow up/down —
|
||||
// the wheel silently walks the prompt history instead of scrolling. Kill
|
||||
// ONLY that branch: xterm runs this same handler before sending a real SGR
|
||||
// mouse report too (`bindMouse`'s wheel case consults it), so a blanket
|
||||
// `false` also blocks tmux's own wheel scrolling. `x10` counts as off here
|
||||
// because that protocol reports button presses only, never the wheel — so
|
||||
// xterm takes the emulation path for it as well.
|
||||
term.attachCustomWheelEventHandler(() => {
|
||||
const mode = term.modes.mouseTrackingMode;
|
||||
const tracked = mode !== "none" && mode !== "x10";
|
||||
return tracked || term.buffer.active.type !== "alternate";
|
||||
});
|
||||
|
||||
// xterm sends Shift+Tab as ESC[Z but — unlike plain Tab — never marks the
|
||||
// event cancelled, so the browser still runs its default action and moves
|
||||
// focus out of the terminal. The pane then only ever sees the first press,
|
||||
// which is why `shift+tab to cycle` (permission mode in claude) looked dead
|
||||
// here while working in a real terminal. Returning true keeps xterm's own
|
||||
// handling; the preventDefault only stops focus from escaping.
|
||||
// Ctrl+M toggles "Tab moves focus" (VS Code's way out of its terminal);
|
||||
// in that mode Tab and Shift+Tab are not the pane's, so the browser moves
|
||||
// focus. Cmd+F / Ctrl+Shift+F open the find bar. Returning false keeps xterm from
|
||||
// handling — and from cancelling — the key.
|
||||
term.attachCustomKeyEventHandler((ev) => {
|
||||
if (ev.type !== "keydown") return true;
|
||||
const key = ev.key.toLowerCase();
|
||||
if (ev.ctrlKey && !ev.altKey && !ev.metaKey && !ev.shiftKey && key === "m") {
|
||||
ev.preventDefault();
|
||||
tabMovesRef.current = !tabMovesRef.current;
|
||||
setTabMoves(tabMovesRef.current);
|
||||
return false;
|
||||
}
|
||||
// Find: Cmd+F on macOS, Ctrl+Shift+F elsewhere — never plain Ctrl+F,
|
||||
// which is readline's forward-char (and bound by many TUIs).
|
||||
const findChord =
|
||||
!ev.altKey &&
|
||||
key === "f" &&
|
||||
((ev.metaKey && !ev.ctrlKey && !ev.shiftKey) ||
|
||||
(ev.ctrlKey && ev.shiftKey && !ev.metaKey));
|
||||
if (findChord) {
|
||||
ev.preventDefault();
|
||||
setFind((f) => f ?? "");
|
||||
requestAnimationFrame(() => findInput.current?.focus());
|
||||
return false;
|
||||
}
|
||||
if (ev.key === "Tab" && tabMovesRef.current) return false;
|
||||
if (ev.key === "Tab" && ev.shiftKey) ev.preventDefault();
|
||||
return true;
|
||||
});
|
||||
|
||||
const decoder = new TextDecoder();
|
||||
let ws: WebSocket | null = null;
|
||||
|
||||
/**
|
||||
* Tell the server this terminal's size. tmux draws the pane at whatever
|
||||
* width it last heard, and a pane WIDER than xterm is silently corrupting:
|
||||
* every over-long row autowraps its tail onto the next row's left margin,
|
||||
* and tmux — believing that row unchanged — never repaints over it. The
|
||||
* result is stray characters glued to the left edge of blank lines, which
|
||||
* only becomes visible once a scroll repaints history. Reproduced with a
|
||||
* one-column difference; two columns leaves two characters per line.
|
||||
*
|
||||
* A zero-size fit is never reported: the console collapses with CSS
|
||||
* (`display:none` leaves the container 0×0), and fitting to that would
|
||||
* resize the real tmux pane down to nothing.
|
||||
*/
|
||||
const sendSizeNow = () => {
|
||||
if (!ws || ws.readyState !== WebSocket.OPEN) return;
|
||||
if (term.cols < 2 || term.rows < 2) return;
|
||||
ws.send(JSON.stringify({ type: "resize", cols: term.cols, rows: term.rows }));
|
||||
};
|
||||
sock.onclose = () => {
|
||||
if (disposed || ended) return;
|
||||
// tmux keeps the session alive across a server restart, so re-attaching
|
||||
// repaints the pane in full — no output is lost by retrying. Input is
|
||||
// not: the overlay says so rather than letting keystrokes vanish.
|
||||
setReconnecting(true);
|
||||
retryTimer = setTimeout(connect, 1500);
|
||||
// A divider drag or a window resize fires a resize per frame; tmux and the
|
||||
// program in the pane redraw on each, so the LAST size is sent once things
|
||||
// settle (trailing, 150 ms).
|
||||
let sizeTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
const sendSize = () => {
|
||||
if (sizeTimer) clearTimeout(sizeTimer);
|
||||
sizeTimer = setTimeout(() => {
|
||||
sizeTimer = null;
|
||||
sendSizeNow();
|
||||
}, 150);
|
||||
};
|
||||
let retryTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let ended = false; // server said the pane exited — nothing left to attach to
|
||||
let retryMs = RETRY_MIN_MS;
|
||||
|
||||
const connect = () => {
|
||||
// The attach itself carries this terminal's size. tmux sizes the window
|
||||
// to the client that attached most recently, so spawning the attach at a
|
||||
// default 80×24 and correcting it from the first `resize` message a beat
|
||||
// later makes the pane's program (claude) redraw its whole UI at 80
|
||||
// columns first — and everything painted at that width stays in the
|
||||
// scrollback as torn fragments along the left margin, visible as soon as
|
||||
// you scroll back (issue #33). Happens on every attach: page load,
|
||||
// lane switch, and each reconnect.
|
||||
const size = term.cols > 1 && term.rows > 1 ? `?cols=${term.cols}&rows=${term.rows}` : "";
|
||||
const sock = new WebSocket(`${wsBaseUrl}/ws-pty/${encodeURIComponent(runId)}${size}`);
|
||||
ws = sock;
|
||||
wsRef.current = sock;
|
||||
// Server sends PTY bytes as binary frames — default binaryType ("blob")
|
||||
// would hand onmessage a Blob that the string checks below never match,
|
||||
// silently dropping all terminal output. "arraybuffer" keeps it sync.
|
||||
sock.binaryType = "arraybuffer";
|
||||
|
||||
sock.onopen = () => {
|
||||
retryMs = RETRY_MIN_MS;
|
||||
setReconnecting(false);
|
||||
sendSizeNow();
|
||||
};
|
||||
sock.onmessage = (event) => {
|
||||
const isArrayBuffer =
|
||||
Object.prototype.toString.call(event.data) === "[object ArrayBuffer]";
|
||||
// `stream: true` carries a UTF-8 multi-byte char's trailing bytes over
|
||||
// to the next decode() call when a PTY chunk splits mid-character —
|
||||
// without it, a Vietnamese/accented char split across two WS frames
|
||||
// decodes to garbage on both sides (U+FFFD or stray bytes).
|
||||
const data = isArrayBuffer
|
||||
? decoder.decode(event.data as ArrayBuffer, { stream: true })
|
||||
: event.data;
|
||||
if (typeof data === "string") {
|
||||
// A JSON control frame is the only thing that starts with `{"type"`.
|
||||
if (data.startsWith('{"type"')) {
|
||||
try {
|
||||
const msg = JSON.parse(data);
|
||||
if (msg.type === "exit") {
|
||||
ended = true;
|
||||
term.write(`\r\n${tRef.current("terminal.ended", { code: msg.code })}\r\n`);
|
||||
onExitRef.current?.();
|
||||
}
|
||||
return;
|
||||
} catch {
|
||||
/* not JSON — fall through and render as PTY output */
|
||||
}
|
||||
}
|
||||
term.write(data);
|
||||
}
|
||||
};
|
||||
sock.onclose = (e?: CloseEvent) => {
|
||||
// 1008: the server refused this attach (policy) — retrying cannot help.
|
||||
if (disposed || ended || e?.code === 1008) return;
|
||||
// tmux keeps the session alive across a server restart, so re-attaching
|
||||
// repaints the pane in full — no output is lost by retrying. Input is
|
||||
// not: the overlay says so rather than letting keystrokes vanish.
|
||||
// Backoff (1.5 s → 30 s, reset on open) so a server that stays down is
|
||||
// not hammered by every open pane.
|
||||
setReconnecting(true);
|
||||
retryTimer = setTimeout(connect, retryMs);
|
||||
retryMs = Math.min(retryMs * 2, RETRY_MAX_MS);
|
||||
};
|
||||
};
|
||||
connect();
|
||||
|
||||
const dataDisposable = term.onData((data) => {
|
||||
if (ws && ws.readyState === WebSocket.OPEN) ws.send(data);
|
||||
});
|
||||
|
||||
// xterm's own size change is the event worth reporting, not the
|
||||
// container's: cols also move when the webfont finishes loading or the
|
||||
// page zooms, neither of which resizes the element ResizeObserver watches.
|
||||
const resizeDisposable = term.onResize(sendSize);
|
||||
|
||||
// Re-assert on focus. Several attach clients can share one tmux session
|
||||
// (a second tab, another lane pane), and tmux's `window-size latest` sizes
|
||||
// the window to whichever client was last active — resizing this pane out
|
||||
// from under a terminal that is never told. Coming back to it says so.
|
||||
const reassert = () => sendSizeNow();
|
||||
term.textarea?.addEventListener("focus", reassert);
|
||||
|
||||
const refit = () => {
|
||||
// Never fit a collapsed console — see sendSize.
|
||||
const el = containerRef.current;
|
||||
if (!el || !el.clientWidth || !el.clientHeight) return;
|
||||
fit.fit(); // a real change fires onResize, which reports it
|
||||
};
|
||||
const resizeObserver = new ResizeObserver(refit);
|
||||
if (containerRef.current) resizeObserver.observe(containerRef.current);
|
||||
// A webfont landing after open changes the cell, not the container, so the
|
||||
// observer never fires — and xterm re-measures its cell only on a font
|
||||
// option change or a resize, so the fit kept the fallback font's cell and
|
||||
// the rows/cols overflowed the pane. Re-setting the family (a trailing
|
||||
// space keeps it a change) makes xterm measure again before the fit.
|
||||
const onFontLoaded = () => {
|
||||
const family = term.options.fontFamily ?? "";
|
||||
term.options.fontFamily = family.endsWith(" ") ? family.trimEnd() : `${family} `;
|
||||
refit();
|
||||
};
|
||||
document.fonts?.addEventListener("loadingdone", onFontLoaded);
|
||||
|
||||
return () => {
|
||||
if (retryTimer) clearTimeout(retryTimer);
|
||||
if (sizeTimer) clearTimeout(sizeTimer);
|
||||
searchRef.current = null;
|
||||
resizeObserver.disconnect();
|
||||
document.fonts?.removeEventListener("loadingdone", onFontLoaded);
|
||||
term.textarea?.removeEventListener("focus", reassert);
|
||||
resizeDisposable.dispose();
|
||||
dataDisposable.dispose();
|
||||
ws?.close();
|
||||
canvas?.dispose();
|
||||
term.dispose();
|
||||
termRef.current = null;
|
||||
};
|
||||
};
|
||||
connect();
|
||||
|
||||
const dataDisposable = term.onData((data) => {
|
||||
if (ws && ws.readyState === WebSocket.OPEN) ws.send(data);
|
||||
});
|
||||
|
||||
// xterm's own size change is the event worth reporting, not the
|
||||
// container's: cols also move when the webfont finishes loading or the
|
||||
// page zooms, neither of which resizes the element ResizeObserver watches.
|
||||
const resizeDisposable = term.onResize(sendSize);
|
||||
|
||||
// Re-assert on focus. Several attach clients can share one tmux session
|
||||
// (a second tab, another lane pane), and tmux's `window-size latest` sizes
|
||||
// the window to whichever client was last active — resizing this pane out
|
||||
// from under a terminal that is never told. Coming back to it says so.
|
||||
const reassert = () => sendSizeNow();
|
||||
term.textarea?.addEventListener("focus", reassert);
|
||||
|
||||
const refit = () => {
|
||||
// Never fit a collapsed console — see sendSize.
|
||||
const el = containerRef.current;
|
||||
if (!el || !el.clientWidth || !el.clientHeight) return;
|
||||
fit.fit(); // a real change fires onResize, which reports it
|
||||
// Synchronous once xterm is loaded; the first pane waits for the chunk, and
|
||||
// `disposed` drops a setup that lands after this effect was cleaned up.
|
||||
let teardown: (() => void) | undefined;
|
||||
const start = (x: Xterm) => {
|
||||
if (!disposed) teardown = attach(x);
|
||||
};
|
||||
const resizeObserver = new ResizeObserver(refit);
|
||||
if (containerRef.current) resizeObserver.observe(containerRef.current);
|
||||
// A webfont landing after open changes the cell, not the container, so the
|
||||
// observer never fires — and xterm re-measures its cell only on a font
|
||||
// option change or a resize, so the fit kept the fallback font's cell and
|
||||
// the rows/cols overflowed the pane. Re-setting the family (a trailing
|
||||
// space keeps it a change) makes xterm measure again before the fit.
|
||||
const onFontLoaded = () => {
|
||||
const family = term.options.fontFamily ?? "";
|
||||
term.options.fontFamily = family.endsWith(" ") ? family.trimEnd() : `${family} `;
|
||||
refit();
|
||||
};
|
||||
document.fonts?.addEventListener("loadingdone", onFontLoaded);
|
||||
|
||||
if (xtermLoaded) start(xtermLoaded);
|
||||
else loadXterm().then(start, () => undefined);
|
||||
return () => {
|
||||
disposed = true;
|
||||
if (retryTimer) clearTimeout(retryTimer);
|
||||
if (sizeTimer) clearTimeout(sizeTimer);
|
||||
searchRef.current = null;
|
||||
resizeObserver.disconnect();
|
||||
document.fonts?.removeEventListener("loadingdone", onFontLoaded);
|
||||
term.textarea?.removeEventListener("focus", reassert);
|
||||
resizeDisposable.dispose();
|
||||
dataDisposable.dispose();
|
||||
ws?.close();
|
||||
canvas?.dispose();
|
||||
term.dispose();
|
||||
termRef.current = null;
|
||||
teardown?.();
|
||||
};
|
||||
}, [runId, wsBaseUrl]);
|
||||
|
||||
|
||||
@@ -3,13 +3,14 @@
|
||||
* @description Tests for the xterm.js-backed terminal view: verifies it opens
|
||||
* a WS connection to the right URL, writes incoming binary frames to the
|
||||
* mocked terminal, forwards typed input as outgoing binary frames, and
|
||||
* re-attaches after the socket drops (server restart) but not after `exit`,
|
||||
* re-attaches after the socket drops (server restart) with backoff, but not
|
||||
* after `exit` or a policy close,
|
||||
* and recolours live on a dark-theme change without re-attaching.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from "vitest";
|
||||
import { render, cleanup, act, fireEvent, screen, waitFor } from "@testing-library/react";
|
||||
import { TerminalView } from "../TerminalView";
|
||||
import { TerminalView, loadXterm } from "../TerminalView";
|
||||
import { pasteToRun } from "../../../lib/panePaste";
|
||||
|
||||
const writeMock = vi.fn();
|
||||
@@ -87,7 +88,7 @@ class MockWebSocket {
|
||||
sent: unknown[] = [];
|
||||
onopen: (() => void) | null = null;
|
||||
onmessage: ((e: { data: unknown }) => void) | null = null;
|
||||
onclose: (() => void) | null = null;
|
||||
onclose: ((e?: { code: number }) => void) | null = null;
|
||||
readyState = 1; // OPEN — the component only sends on an open socket
|
||||
static OPEN = 1;
|
||||
constructor(url: string) {
|
||||
@@ -105,6 +106,9 @@ class MockWebSocket {
|
||||
global.WebSocket = MockWebSocket;
|
||||
|
||||
describe("TerminalView", () => {
|
||||
// xterm is a lazy chunk; once loaded every terminal sets up synchronously.
|
||||
beforeAll(() => loadXterm());
|
||||
|
||||
beforeEach(() => {
|
||||
termState.modes.mouseTrackingMode = "none";
|
||||
termState.buffer.active.type = "alternate";
|
||||
@@ -388,6 +392,23 @@ describe("TerminalView", () => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("backs off between failed re-attaches, and stops on a policy close (1008)", () => {
|
||||
vi.useFakeTimers();
|
||||
render(<TerminalView runId="agenthub-lane-1" wsBaseUrl="ws://localhost:4820" />);
|
||||
MockWebSocket.instances[0]!.close();
|
||||
vi.advanceTimersByTime(1600);
|
||||
expect(MockWebSocket.instances).toHaveLength(2);
|
||||
MockWebSocket.instances[1]!.close(); // failed again: now 3 s
|
||||
vi.advanceTimersByTime(1600);
|
||||
expect(MockWebSocket.instances).toHaveLength(2);
|
||||
vi.advanceTimersByTime(1500);
|
||||
expect(MockWebSocket.instances).toHaveLength(3);
|
||||
act(() => MockWebSocket.instances[2]!.onclose?.({ code: 1008 }));
|
||||
vi.advanceTimersByTime(60_000);
|
||||
expect(MockWebSocket.instances).toHaveLength(3);
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("does not re-attach once the server reported the pane exited", () => {
|
||||
vi.useFakeTimers();
|
||||
render(<TerminalView runId="agenthub-lane-1" wsBaseUrl="ws://localhost:4820" />);
|
||||
|
||||
@@ -56,6 +56,7 @@ export function ClaudeAgentHubSettings({ onHomeChanged }: { onHomeChanged?: () =
|
||||
// badge current the way the old Settings page did, every 10 s.
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => {
|
||||
if (!(document.visibilityState === "visible")) return;
|
||||
api.settings
|
||||
.info()
|
||||
.then((r) => setHooks(r.hooks))
|
||||
|
||||
@@ -15,6 +15,7 @@ import { useCallback, useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { api } from "../../lib/api";
|
||||
import { useLiveRefresh } from "../../hooks/useLiveRefresh";
|
||||
import { laneChangeMatcher } from "../../lib/laneChange";
|
||||
import type { PipelineStats } from "../../lib/types";
|
||||
|
||||
/** Percentage of `n` out of `total`, 0 when nothing was recorded. */
|
||||
@@ -52,8 +53,12 @@ export function LanePipelinePanel({
|
||||
}, [refresh]);
|
||||
|
||||
// Stages move as agents declare them; throttled (not debounced) so a burst
|
||||
// costs one fetch and a steady stream still refreshes every 3 s.
|
||||
useLiveRefresh(() => void refresh(), { match: (msg) => msg.type === "lane_update" });
|
||||
// costs one fetch and a steady stream still refreshes every 3 s. A lane's
|
||||
// re-broadcast that moved no stage column is ignored.
|
||||
const [stageChanged] = useState(() =>
|
||||
laneChangeMatcher((l) => `${l.pipeline}:${l.stage}:${l.active_feature_id}`)
|
||||
);
|
||||
useLiveRefresh(() => void refresh(), { match: stageChanged });
|
||||
|
||||
const hasPipelines = !!data && data.pipelines.length > 0;
|
||||
useEffect(() => {
|
||||
|
||||
@@ -33,8 +33,10 @@ export function SkillUsagePanel({ statusFilter }: { statusFilter: string }) {
|
||||
void refresh();
|
||||
}, [refresh]);
|
||||
|
||||
// Throttled (not debounced): a steady event stream still refreshes every 3 s.
|
||||
// Throttled (not debounced): a steady event stream still refreshes, every
|
||||
// 15 s — it is an aggregate over every event.
|
||||
useLiveRefresh(() => void refresh(), {
|
||||
throttleMs: 15000,
|
||||
match: (msg) => msg.type === "new_event" || msg.type === "session_updated",
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* @file useThrottledValue.test.ts
|
||||
* @description Tests for `useThrottledValue`: the first change lands at once, a
|
||||
* burst inside the window collapses into one trailing update with the last value.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
import { describe, it, expect, vi, afterEach } from "vitest";
|
||||
import { renderHook, act } from "@testing-library/react";
|
||||
import { useThrottledValue } from "../useThrottledValue";
|
||||
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
describe("useThrottledValue", () => {
|
||||
it("is leading + trailing", () => {
|
||||
vi.useFakeTimers();
|
||||
const { result, rerender } = renderHook(({ v }) => useThrottledValue(v, 3000), {
|
||||
initialProps: { v: "a" },
|
||||
});
|
||||
expect(result.current).toBe("a");
|
||||
act(() => vi.advanceTimersByTime(5000));
|
||||
rerender({ v: "b" });
|
||||
expect(result.current).toBe("b"); // leading
|
||||
rerender({ v: "c" });
|
||||
rerender({ v: "d" });
|
||||
expect(result.current).toBe("b"); // inside the window
|
||||
act(() => vi.advanceTimersByTime(3000));
|
||||
expect(result.current).toBe("d"); // trailing, last value
|
||||
});
|
||||
});
|
||||
@@ -36,8 +36,9 @@ export function useLiveRefresh(load: () => void, opts: LiveRefreshOptions = {}):
|
||||
if (!enabled) return;
|
||||
const live = throttle(() => loadRef.current(), throttleMs);
|
||||
const visible = () => document.visibilityState === "visible";
|
||||
// A hidden tab ignores events: onVis reloads once when it is shown again.
|
||||
const offMsg = eventBus.subscribe((msg) => {
|
||||
if (matchRef.current?.(msg)) live();
|
||||
if (visible() && matchRef.current?.(msg)) live();
|
||||
});
|
||||
let wasDown = !eventBus.connected;
|
||||
// (Guarded: test doubles of the bus often stub `subscribe` only.)
|
||||
@@ -47,7 +48,7 @@ export function useLiveRefresh(load: () => void, opts: LiveRefreshOptions = {}):
|
||||
if (!up) wasDown = true;
|
||||
else if (wasDown) {
|
||||
wasDown = false;
|
||||
live();
|
||||
if (visible()) live();
|
||||
}
|
||||
})
|
||||
: () => undefined;
|
||||
|
||||
@@ -121,9 +121,11 @@ export function useNotifications() {
|
||||
type: NotifType,
|
||||
title: string,
|
||||
body: string,
|
||||
url?: Promise<string | undefined>
|
||||
// A thunk: the pane lookup (GET /api/run) runs only for a
|
||||
// notification that is actually shown, never per incoming event.
|
||||
url?: () => Promise<string | undefined>
|
||||
) =>
|
||||
void Promise.resolve(url)
|
||||
void Promise.resolve(url?.())
|
||||
.then((u) => notify(title, body, u))
|
||||
.then((r) => {
|
||||
if (r.via === "native" || r.via === "push" || r.via === "local")
|
||||
@@ -138,7 +140,7 @@ export function useNotifications() {
|
||||
"onNewSession",
|
||||
i18n.t("errors:notifications.newSession"),
|
||||
s.name || `${i18n.t("errors:notifications.sessionDefault")}${s.id.slice(0, 8)}`,
|
||||
laneUrlForSession(s.id)
|
||||
() => laneUrlForSession(s.id)
|
||||
);
|
||||
break;
|
||||
}
|
||||
@@ -149,7 +151,7 @@ export function useNotifications() {
|
||||
"onSessionError",
|
||||
i18n.t("errors:notifications.sessionError"),
|
||||
s.name || `${i18n.t("errors:notifications.sessionDefault")}${s.id.slice(0, 8)}`,
|
||||
laneUrlForSession(s.id)
|
||||
() => laneUrlForSession(s.id)
|
||||
);
|
||||
}
|
||||
break;
|
||||
@@ -158,10 +160,7 @@ export function useNotifications() {
|
||||
if (!prefs.onSubagentSpawn) return;
|
||||
const a = msg.data as Agent;
|
||||
if (a.type === "subagent") {
|
||||
show(
|
||||
"onSubagentSpawn",
|
||||
i18n.t("errors:notifications.subagentSpawned"),
|
||||
a.name,
|
||||
show("onSubagentSpawn", i18n.t("errors:notifications.subagentSpawned"), a.name, () =>
|
||||
laneUrlForSession(a.session_id)
|
||||
);
|
||||
}
|
||||
@@ -169,7 +168,7 @@ export function useNotifications() {
|
||||
}
|
||||
case "new_event": {
|
||||
const ev = msg.data as DashboardEvent;
|
||||
const url = laneUrlForSession(ev.session_id);
|
||||
const url = () => laneUrlForSession(ev.session_id);
|
||||
// The two states where Claude is BLOCKED on the user get their own
|
||||
// flags (issue #29): `Notification` is a permission prompt or a
|
||||
// question, `Stop` is the end of a turn. Both used to hang off
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* @file useThrottledValue.ts
|
||||
* @description Returns `value`, but lets it change at most once per `ms`
|
||||
* (leading + trailing, via `lib/throttle.ts`): the first change shows at once,
|
||||
* a burst collapses into one more update when it settles, and the last value
|
||||
* always lands. For effect keys that move on every hook (a lane's status or
|
||||
* session flipping between two sessions) so the fetch they drive cannot storm.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { throttle } from "../lib/throttle";
|
||||
|
||||
export function useThrottledValue<T>(value: T, ms: number): T {
|
||||
const [shown, setShown] = useState(value);
|
||||
const latest = useRef(value);
|
||||
latest.current = value;
|
||||
const push = useMemo(() => throttle(() => setShown(latest.current), ms), [ms]);
|
||||
useEffect(() => () => push.cancel(), [push]);
|
||||
useEffect(() => push(), [value, push]);
|
||||
return shown;
|
||||
}
|
||||
@@ -128,7 +128,10 @@ export function useWebSocket(onMessage: MessageHandler) {
|
||||
// restart is picked up within a few seconds rather than after a long
|
||||
// idle wait. The focus/online/visibility listeners below reconnect
|
||||
// instantly on top of this for the common "user comes back" case.
|
||||
const delay = Math.min(500 * Math.pow(2, reconnectAttempts.current), 3000);
|
||||
// Jittered (×0.5–1.5) so a server restart is not met by every
|
||||
// browser reconnecting in the same instant.
|
||||
const delay =
|
||||
Math.min(500 * Math.pow(2, reconnectAttempts.current), 3000) * (0.5 + Math.random());
|
||||
reconnectAttempts.current++;
|
||||
reconnectTimer.current = setTimeout(connect, delay);
|
||||
}
|
||||
|
||||
+32
-88
@@ -1,8 +1,10 @@
|
||||
/**
|
||||
* @file index.ts
|
||||
* @description i18next bootstrap for the dashboard client. Registers bundled JSON
|
||||
* locale files for English (`en`) and Vietnamese (`vi`), wires browser language detection, and exports the configured
|
||||
* singleton consumed by `react-i18next`.
|
||||
* @description i18next bootstrap for the dashboard client. Loads the JSON locale
|
||||
* files for English (`en`) and Vietnamese (`vi`) lazily — only the active language
|
||||
* (and the `en` fallback) — wires browser language detection, and exports the
|
||||
* configured singleton consumed by `react-i18next` plus `i18nReady`, the promise
|
||||
* the entry point awaits before the first render.
|
||||
*
|
||||
* ## Namespaces
|
||||
* Translations are split by feature area (`dashboard`, `sessions`, `settings`,
|
||||
@@ -38,14 +40,7 @@
|
||||
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
|
||||
*
|
||||
* ## Internal dependencies
|
||||
* - `./locales/en/common.json`
|
||||
* - `./locales/vi/common.json`
|
||||
* - `./locales/en/nav.json`
|
||||
* - `./locales/vi/nav.json`
|
||||
* - `./locales/en/dashboard.json`
|
||||
* - `./locales/vi/dashboard.json`
|
||||
* - `./locales/en/sessions.json`
|
||||
* - `./locales/vi/sessions.json`
|
||||
* - `./locales/<lng>/<ns>.json` (lazy, via `import.meta.glob`)
|
||||
*
|
||||
* ## Testing pointers
|
||||
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
|
||||
@@ -57,44 +52,30 @@
|
||||
* - `skills/file-headers/` — mandatory `@author` header policy.
|
||||
* ============================================================================= */
|
||||
|
||||
import i18n from "i18next";
|
||||
import i18n, { type BackendModule, type ResourceKey } from "i18next";
|
||||
import { initReactI18next } from "react-i18next";
|
||||
import LanguageDetector from "i18next-browser-languagedetector";
|
||||
|
||||
import common_en from "./locales/en/common.json";
|
||||
import common_vi from "./locales/vi/common.json";
|
||||
import nav_en from "./locales/en/nav.json";
|
||||
import nav_vi from "./locales/vi/nav.json";
|
||||
import dashboard_en from "./locales/en/dashboard.json";
|
||||
import dashboard_vi from "./locales/vi/dashboard.json";
|
||||
import sessions_en from "./locales/en/sessions.json";
|
||||
import sessions_vi from "./locales/vi/sessions.json";
|
||||
import activity_en from "./locales/en/activity.json";
|
||||
import activity_vi from "./locales/vi/activity.json";
|
||||
import analytics_en from "./locales/en/analytics.json";
|
||||
import analytics_vi from "./locales/vi/analytics.json";
|
||||
import workflows_en from "./locales/en/workflows.json";
|
||||
import workflows_vi from "./locales/vi/workflows.json";
|
||||
import settings_en from "./locales/en/settings.json";
|
||||
import settings_vi from "./locales/vi/settings.json";
|
||||
import kanban_en from "./locales/en/kanban.json";
|
||||
import kanban_vi from "./locales/vi/kanban.json";
|
||||
import errors_en from "./locales/en/errors.json";
|
||||
import errors_vi from "./locales/vi/errors.json";
|
||||
import updates_en from "./locales/en/updates.json";
|
||||
import updates_vi from "./locales/vi/updates.json";
|
||||
import ccConfig_en from "./locales/en/ccConfig.json";
|
||||
import ccConfig_vi from "./locales/vi/ccConfig.json";
|
||||
import codexConfig_en from "./locales/en/codexConfig.json";
|
||||
import codexConfig_vi from "./locales/vi/codexConfig.json";
|
||||
import run_en from "./locales/en/run.json";
|
||||
import run_vi from "./locales/vi/run.json";
|
||||
import alerts_en from "./locales/en/alerts.json";
|
||||
import alerts_vi from "./locales/vi/alerts.json";
|
||||
import splash_en from "./locales/en/splash.json";
|
||||
import splash_vi from "./locales/vi/splash.json";
|
||||
import lanes_en from "./locales/en/lanes.json";
|
||||
import lanes_vi from "./locales/vi/lanes.json";
|
||||
// Every locale file is its own lazy chunk (vite.config.ts groups them into one
|
||||
// chunk per language), so a page loads only the language it shows. i18next
|
||||
// reads them through this inline backend: `init` fetches the detected language
|
||||
// (plus the `en` fallback), and `changeLanguage` fetches a new one BEFORE it
|
||||
// switches, so no raw key is ever painted.
|
||||
const localeFiles = import.meta.glob<Record<string, unknown>>("./locales/*/*.json", {
|
||||
import: "default",
|
||||
});
|
||||
const lazyLocales: BackendModule = {
|
||||
type: "backend",
|
||||
init() {},
|
||||
read(lng, ns, cb) {
|
||||
const load = localeFiles[`./locales/${lng}/${ns}.json`];
|
||||
if (!load) return cb(null, {});
|
||||
load().then(
|
||||
(data) => cb(null, data as ResourceKey),
|
||||
(err) => cb(err, false)
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
/** Keep `<html lang>` on the active language, so a screen reader speaks the
|
||||
* page with the right voice and the browser hyphenates/translates correctly.
|
||||
@@ -105,50 +86,13 @@ export function syncDocumentLang(): void {
|
||||
}
|
||||
i18n.on("languageChanged", syncDocumentLang);
|
||||
|
||||
i18n
|
||||
/** Resolves once the detected language's namespaces are loaded; `main.tsx`
|
||||
* awaits it before the first render. */
|
||||
export const i18nReady = i18n
|
||||
.use(lazyLocales)
|
||||
.use(LanguageDetector)
|
||||
.use(initReactI18next)
|
||||
.init({
|
||||
resources: {
|
||||
en: {
|
||||
common: common_en,
|
||||
nav: nav_en,
|
||||
dashboard: dashboard_en,
|
||||
sessions: sessions_en,
|
||||
activity: activity_en,
|
||||
analytics: analytics_en,
|
||||
workflows: workflows_en,
|
||||
settings: settings_en,
|
||||
kanban: kanban_en,
|
||||
errors: errors_en,
|
||||
updates: updates_en,
|
||||
ccConfig: ccConfig_en,
|
||||
codexConfig: codexConfig_en,
|
||||
run: run_en,
|
||||
alerts: alerts_en,
|
||||
splash: splash_en,
|
||||
lanes: lanes_en,
|
||||
},
|
||||
vi: {
|
||||
common: common_vi,
|
||||
nav: nav_vi,
|
||||
dashboard: dashboard_vi,
|
||||
sessions: sessions_vi,
|
||||
activity: activity_vi,
|
||||
analytics: analytics_vi,
|
||||
workflows: workflows_vi,
|
||||
settings: settings_vi,
|
||||
kanban: kanban_vi,
|
||||
errors: errors_vi,
|
||||
updates: updates_vi,
|
||||
ccConfig: ccConfig_vi,
|
||||
codexConfig: codexConfig_vi,
|
||||
run: run_vi,
|
||||
alerts: alerts_vi,
|
||||
splash: splash_vi,
|
||||
lanes: lanes_vi,
|
||||
},
|
||||
},
|
||||
supportedLngs: ["en", "vi"],
|
||||
nonExplicitSupportedLngs: true,
|
||||
fallbackLng: "en",
|
||||
@@ -182,5 +126,5 @@ i18n
|
||||
|
||||
syncDocumentLang();
|
||||
|
||||
/** Configured i18next instance — import side effects run {@link init}. */
|
||||
/** Configured i18next instance — import side effects start {@link init}. */
|
||||
export default i18n;
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* @file laneChange.test.ts
|
||||
* @description Tests for `laneChangeMatcher`: a lane_update fires only when the
|
||||
* chosen key changed or a lane was removed, and each matcher remembers alone.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { laneChangeMatcher, runKeyOf } from "../laneChange";
|
||||
import type { Lane, WSMessage } from "../types";
|
||||
|
||||
const upd = (lane: Partial<Lane>): WSMessage => ({
|
||||
type: "lane_update",
|
||||
data: { lane: { id: 1, run_id: null, status: "idle", session_id: null, ...lane } as Lane },
|
||||
timestamp: "t",
|
||||
});
|
||||
|
||||
describe("laneChangeMatcher", () => {
|
||||
it("fires on a changed run key, a removal, and nothing else", () => {
|
||||
const m = laneChangeMatcher(runKeyOf);
|
||||
expect(m(upd({}))).toBe(true); // first sight
|
||||
expect(m(upd({ last_event_at: "x" } as Partial<Lane>))).toBe(false);
|
||||
expect(m(upd({ status: "running" }))).toBe(true);
|
||||
expect(m(upd({ status: "running" }))).toBe(false);
|
||||
expect(m({ type: "lane_update", data: { removed: 1 }, timestamp: "t" })).toBe(true);
|
||||
expect(m({ type: "new_event", data: {}, timestamp: "t" } as WSMessage)).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps a separate memory per matcher", () => {
|
||||
const a = laneChangeMatcher(runKeyOf);
|
||||
const b = laneChangeMatcher(runKeyOf);
|
||||
expect(a(upd({}))).toBe(true);
|
||||
expect(b(upd({}))).toBe(true);
|
||||
});
|
||||
});
|
||||
+21
-1
@@ -529,7 +529,27 @@ function ccQuery(scope?: CcScope, cwd?: string): string {
|
||||
* that needs to branch on which error this was should check `.code`, never
|
||||
* guess at substrings of the human-readable `.message`.
|
||||
*/
|
||||
async function request<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
/** GETs in flight, by path: concurrent callers of the same read (several
|
||||
* components mounting, a WS event fanning out to many listeners) share one
|
||||
* fetch and one parsed result. Deleted as soon as it settles, so this is
|
||||
* dedupe, never a cache. Callers must treat the result as read-only. */
|
||||
const inflight = new Map<string, Promise<unknown>>();
|
||||
|
||||
function request<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
// Only a plain GET: a body, headers or an AbortSignal belongs to one caller.
|
||||
const plainGet =
|
||||
!options ||
|
||||
(Object.keys(options).every((k) => k === "method") &&
|
||||
(options.method ?? "GET").toUpperCase() === "GET");
|
||||
if (!plainGet) return send<T>(path, options);
|
||||
const hit = inflight.get(path);
|
||||
if (hit) return hit as Promise<T>;
|
||||
const p = send<T>(path, options).finally(() => inflight.delete(path));
|
||||
inflight.set(path, p);
|
||||
return p;
|
||||
}
|
||||
|
||||
async function send<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
const token = dashboardToken();
|
||||
// Build the effective header set. Order matters: defaults first so that the
|
||||
// token and any caller headers can override, and caller headers land last.
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* @file laneChange.ts
|
||||
* @description `lane_update` matcher for live-refresh callers that care about
|
||||
* only a few lane columns. A lane is re-broadcast on every hook (last event,
|
||||
* liveness…), so matching the bare message type made every such frame refetch;
|
||||
* this one fires only when the chosen key of a lane actually changed, or when a
|
||||
* lane was removed. Each call keeps its own memory of the keys it has seen.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import type { Lane, WSMessage } from "./types";
|
||||
|
||||
/** The columns a pane starting, ending or learning its session moves. */
|
||||
export const runKeyOf = (l: Lane): string => `${l.run_id}:${l.status}:${l.session_id}`;
|
||||
|
||||
export function laneChangeMatcher(keyOf: (l: Lane) => string): (msg: WSMessage) => boolean {
|
||||
const seen = new Map<number, string>();
|
||||
return (msg) => {
|
||||
if (msg.type !== "lane_update") return false;
|
||||
const d = msg.data as { lane?: Lane; removed?: number };
|
||||
if (d.removed !== undefined) {
|
||||
seen.delete(d.removed);
|
||||
return true;
|
||||
}
|
||||
if (!d.lane) return false;
|
||||
const key = keyOf(d.lane);
|
||||
if (seen.get(d.lane.id) === key) return false;
|
||||
seen.set(d.lane.id, key);
|
||||
return true;
|
||||
};
|
||||
}
|
||||
+18
-9
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* @file main.tsx
|
||||
* @description Vite client entry point. Bootstraps React 18, loads global styles
|
||||
* and i18n, registers the service worker for offline asset caching, and mounts
|
||||
* {@link App} into `#root`.
|
||||
* @description Vite client entry point. Bootstraps React 18, loads global styles,
|
||||
* registers the service worker, prefetches the Workspace chunk on a `/workspace`
|
||||
* deep link, and mounts {@link App} into `#root` once the active locale is loaded.
|
||||
*
|
||||
* ## Fonts
|
||||
* Only Latin subsets of Inter and JetBrains Mono are imported so Vite bundles
|
||||
@@ -63,7 +63,10 @@ import "@fontsource/jetbrains-mono/latin-500.css";
|
||||
import "@fontsource/jetbrains-mono/vietnamese-400.css";
|
||||
import "@fontsource/jetbrains-mono/vietnamese-500.css";
|
||||
import App from "./App";
|
||||
import "./i18n";
|
||||
import { i18nReady } from "./i18n";
|
||||
// Deep link into the Workspace: start its (lazy) chunk now, in parallel with the
|
||||
// locale fetch below, instead of after the first render asks for it.
|
||||
if (location.pathname.startsWith("/workspace")) void import("./pages/Workspace");
|
||||
import "./index.css";
|
||||
|
||||
if ("serviceWorker" in navigator) {
|
||||
@@ -93,8 +96,14 @@ if ("serviceWorker" in navigator) {
|
||||
const root = document.getElementById("root");
|
||||
if (!root) throw new Error("Root element not found");
|
||||
|
||||
createRoot(root).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>
|
||||
);
|
||||
// The active locale is a lazy chunk: render once it is in, so no raw key ever
|
||||
// paints. A failed fetch still renders (i18next falls back to the keys).
|
||||
void i18nReady
|
||||
.catch(() => undefined)
|
||||
.then(() =>
|
||||
createRoot(root).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>
|
||||
)
|
||||
);
|
||||
|
||||
@@ -111,7 +111,7 @@ const PAGE_SIZE = 50;
|
||||
// Throttle live-event refreshes so a burst of hook events (e.g. a stream of
|
||||
// PostToolUse results) triggers one refetch instead of dozens — and a steady
|
||||
// stream still refreshes, which a trailing debounce never did.
|
||||
const REFRESH_THROTTLE_MS = 1000;
|
||||
const REFRESH_THROTTLE_MS = 3000;
|
||||
|
||||
/** The agents on screen not asked about yet, and the sessions to ask for them. */
|
||||
export function agentsToFetch(
|
||||
|
||||
@@ -97,6 +97,7 @@ import { eventBus } from "../lib/eventBus";
|
||||
import { useLiveRefresh } from "../hooks/useLiveRefresh";
|
||||
import { isRemoteDataRefreshMessage } from "../lib/remoteDataEvents";
|
||||
import { useDataScope } from "../lib/dataScope";
|
||||
import { keepIfSame } from "../lib/keepIfSame";
|
||||
import { StatCard } from "../components/StatCard";
|
||||
import { AgentCard } from "../components/AgentCard";
|
||||
import { useContextMenu } from "../components/ContextMenu";
|
||||
@@ -783,8 +784,10 @@ function AnalyticsTab() {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
// Heavy aggregates: event-driven reloads at most every 15 s.
|
||||
useLiveRefresh(load, {
|
||||
intervalMs: 15000,
|
||||
throttleMs: 15000,
|
||||
match: (msg) =>
|
||||
msg.type === "session_created" ||
|
||||
msg.type === "session_updated" ||
|
||||
@@ -2920,7 +2923,9 @@ export function Dashboard() {
|
||||
if (sessionsRes) setSessionsById(new Map(sessionsRes.sessions.map((s) => [s.id, s])));
|
||||
if (workingRes && waitingRes) {
|
||||
const active = [...workingRes.agents, ...waitingRes.agents];
|
||||
setActiveAgents(active);
|
||||
// keepIfSame: an identical poll keeps the arrays, so the memoized cards
|
||||
// do not re-render.
|
||||
setActiveAgents(keepIfSame(active));
|
||||
// Every subagent of the active main agents' sessions, in ONE call.
|
||||
const activeSessionIds = [
|
||||
...new Set(active.filter((a) => a.type === "main").map((a) => a.session_id)),
|
||||
@@ -2929,7 +2934,7 @@ export function Dashboard() {
|
||||
? await soft(api.agents.list({ session_ids: activeSessionIds, limit: 2000 }))
|
||||
: { agents: [] };
|
||||
if (seq !== monitorSeq.current) return;
|
||||
if (subsRes) setAllSubagents(subsRes.agents.filter((a) => a.type === "subagent"));
|
||||
if (subsRes) setAllSubagents(keepIfSame(subsRes.agents.filter((a) => a.type === "subagent")));
|
||||
}
|
||||
setError(failed[0] ?? null);
|
||||
}, [scope]);
|
||||
|
||||
@@ -83,6 +83,7 @@ import {
|
||||
} from "lucide-react";
|
||||
import { api, type RunHandle } from "../lib/api";
|
||||
import { useLiveRefresh } from "../hooks/useLiveRefresh";
|
||||
import { laneChangeMatcher, runKeyOf } from "../lib/laneChange";
|
||||
import { workspaceHref } from "../components/SessionRowMenu";
|
||||
import { downloadText, exportName, toCsv } from "../lib/exportData";
|
||||
import { toast } from "../lib/toast";
|
||||
@@ -140,7 +141,7 @@ const EVENTS_INITIAL_BATCH = 50;
|
||||
const EVENTS_MORE_BATCH = 500;
|
||||
// Live-refresh bounds - see ActivityFeed for rationale.
|
||||
const EVENTS_MAX_REFRESH = 500;
|
||||
const EVENTS_REFRESH_THROTTLE_MS = 1000;
|
||||
const EVENTS_REFRESH_THROTTLE_MS = 3000;
|
||||
const DETAIL_TABS: DetailTab[] = ["agents", "conversation", "timeline"];
|
||||
|
||||
export function SessionDetail() {
|
||||
@@ -249,8 +250,10 @@ export function SessionDetail() {
|
||||
useEffect(() => {
|
||||
probeRuns();
|
||||
}, [probeRuns]);
|
||||
// A pane starting/stopping re-broadcasts its lane (`lane_update`).
|
||||
useLiveRefresh(probeRuns, { intervalMs: 10000, match: (msg) => msg.type === "lane_update" });
|
||||
// A pane starting/stopping re-broadcasts its lane (`lane_update`); a hook's
|
||||
// re-broadcast that moved no run column is ignored.
|
||||
const [runChanged] = useState(() => laneChangeMatcher(runKeyOf));
|
||||
useLiveRefresh(probeRuns, { intervalMs: 10000, match: runChanged });
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!id) return;
|
||||
|
||||
@@ -70,6 +70,7 @@ import {
|
||||
import { api } from "../lib/api";
|
||||
import type { RemoteSource, RunHandle } from "../lib/api";
|
||||
import { useLiveRefresh } from "../hooks/useLiveRefresh";
|
||||
import { laneChangeMatcher, runKeyOf } from "../lib/laneChange";
|
||||
import { useAiTools } from "../hooks/useAiTools";
|
||||
import { useLanes } from "../hooks/useLanes";
|
||||
import { toast } from "../lib/toast";
|
||||
@@ -253,11 +254,13 @@ export function Sessions({ embedded = false }: { embedded?: boolean } = {}) {
|
||||
useEffect(() => {
|
||||
loadDashboardRuns();
|
||||
}, [loadDashboardRuns]);
|
||||
const [runChanged] = useState(() => laneChangeMatcher(runKeyOf));
|
||||
useLiveRefresh(loadDashboardRuns, {
|
||||
intervalMs: 15000,
|
||||
// A pane starting/stopping re-broadcasts its lane (`lane_update`); the
|
||||
// server sends no run_status any more. The 15 s poll covers extra slots.
|
||||
match: (msg) => msg.type === "lane_update",
|
||||
// A pane starting/stopping re-broadcasts its lane (`lane_update`) — only
|
||||
// then, not on every hook's re-broadcast; the server sends no run_status
|
||||
// any more. The 15 s poll covers extra slots.
|
||||
match: runChanged,
|
||||
});
|
||||
|
||||
useLiveRefresh(load, {
|
||||
|
||||
@@ -263,7 +263,8 @@ export function Settings({
|
||||
lastInfoAt.current = Date.now();
|
||||
let timer: number | undefined;
|
||||
const soon = () => {
|
||||
if (timer !== undefined) return;
|
||||
// Hidden tab: no reads; onVis catches up once when it is shown.
|
||||
if (timer !== undefined || document.visibilityState !== "visible") return;
|
||||
const wait = Math.max(0, INFO_MIN_MS - (Date.now() - lastInfoAt.current));
|
||||
timer = window.setTimeout(() => {
|
||||
timer = undefined;
|
||||
@@ -275,6 +276,8 @@ export function Settings({
|
||||
}, wait);
|
||||
};
|
||||
const beat = window.setInterval(soon, 30_000);
|
||||
const onVis = () => soon();
|
||||
document.addEventListener("visibilitychange", onVis);
|
||||
const off = eventBus.subscribe((msg: WSMessage) => {
|
||||
if (
|
||||
msg.type === "session_created" ||
|
||||
@@ -288,6 +291,7 @@ export function Settings({
|
||||
});
|
||||
return () => {
|
||||
off();
|
||||
document.removeEventListener("visibilitychange", onVis);
|
||||
window.clearInterval(beat);
|
||||
window.clearTimeout(timer);
|
||||
};
|
||||
|
||||
@@ -139,9 +139,9 @@ export function Workflows({
|
||||
}, [fetchData]);
|
||||
|
||||
// Auto-refresh on the WebSocket messages that change workflow data, throttled
|
||||
// so a steady stream refreshes every few seconds instead of never.
|
||||
// so a steady stream refreshes every 15 s (heavy aggregates) instead of never.
|
||||
useLiveRefresh(fetchData, {
|
||||
throttleMs: 5000,
|
||||
throttleMs: 15000,
|
||||
match: (msg: WSMessage) =>
|
||||
msg.type === "session_created" ||
|
||||
msg.type === "session_updated" ||
|
||||
|
||||
@@ -775,7 +775,8 @@ export function Workspace() {
|
||||
useEffect(() => {
|
||||
refreshList();
|
||||
const tick = setInterval(() => {
|
||||
refreshList();
|
||||
// Hidden tab: skip; the visibility handler below re-reads on show.
|
||||
if (document.visibilityState === "visible") refreshList();
|
||||
}, 5000);
|
||||
return () => clearInterval(tick);
|
||||
}, [refreshList]);
|
||||
|
||||
@@ -7233,7 +7233,7 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
<p
|
||||
class="text-[10px] text-status-warning/90 mt-1"
|
||||
>
|
||||
UI build v2.5.9 (rebuild client to match)
|
||||
UI build v2.5.10 (rebuild client to match)
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
|
||||
@@ -13,9 +13,14 @@
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { cleanup } from "@testing-library/react";
|
||||
import { afterEach, beforeEach } from "vitest";
|
||||
import "./i18n/index";
|
||||
import { i18nReady } from "./i18n/index";
|
||||
import i18n from "i18next";
|
||||
|
||||
// Locales load lazily in the app; tests get both up front so every
|
||||
// `changeLanguage` (en or vi) switches synchronously, as before.
|
||||
await i18nReady;
|
||||
await i18n.loadLanguages(["en", "vi"]);
|
||||
|
||||
/** jsdom does not implement ResizeObserver — stub it for components that use it. */
|
||||
// @ts-expect-error global stub
|
||||
global.ResizeObserver = class {
|
||||
|
||||
+53
-6
@@ -1,12 +1,13 @@
|
||||
/**
|
||||
* @file vite.config.ts
|
||||
* @description Vite build and dev-server configuration for the dashboard client — React plugin, an API/WebSocket proxy that honours DASHBOARD_PORT, and build-time injection of the project version as `__APP_VERSION__`.
|
||||
* @description Vite build and dev-server configuration for the dashboard client — React plugin, an API/WebSocket proxy that honours DASHBOARD_PORT, build-time injection of the project version as `__APP_VERSION__`, one chunk per UI language, hidden source maps, and pre-compressed `<file>.br`/`<file>.gz` siblings of every text asset ≥ 1 KB (served by the server for `/assets/`).
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { defineConfig } from "vite";
|
||||
import { readdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { join, resolve } from "node:path";
|
||||
import { brotliCompressSync, constants, gzipSync } from "node:zlib";
|
||||
import { defineConfig, type Plugin } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
|
||||
// The dashboard's displayed version is the canonical project version from the
|
||||
@@ -43,8 +44,43 @@ const APP_VERSION = resolveAppVersion();
|
||||
// is what the embedded server in production binds to anyway.
|
||||
const DASHBOARD_PORT = parseInt(process.env.DASHBOARD_PORT || "4820", 10);
|
||||
|
||||
// Writes `<file>.br` (quality 11) and `<file>.gz` (level 9) next to every text
|
||||
// asset of 1 KB or more once the build is on disk, so the server can send the
|
||||
// smallest encoding without compressing per request. node:zlib only.
|
||||
function precompress(): Plugin {
|
||||
let outDir = "dist";
|
||||
const walk = (dir: string): string[] =>
|
||||
readdirSync(dir, { withFileTypes: true }).flatMap((e) =>
|
||||
e.isDirectory() ? walk(join(dir, e.name)) : [join(dir, e.name)]
|
||||
);
|
||||
return {
|
||||
name: "agenthub-precompress",
|
||||
apply: "build",
|
||||
configResolved(c) {
|
||||
outDir = resolve(c.root, c.build.outDir);
|
||||
},
|
||||
closeBundle() {
|
||||
for (const file of walk(outDir)) {
|
||||
if (!/\.(js|css|svg|json|html)$/.test(file)) continue;
|
||||
const buf = readFileSync(file);
|
||||
if (buf.length < 1024) continue;
|
||||
writeFileSync(
|
||||
`${file}.br`,
|
||||
brotliCompressSync(buf, {
|
||||
params: {
|
||||
[constants.BROTLI_PARAM_QUALITY]: 11,
|
||||
[constants.BROTLI_PARAM_SIZE_HINT]: buf.length,
|
||||
},
|
||||
})
|
||||
);
|
||||
writeFileSync(`${file}.gz`, gzipSync(buf, { level: 9 }));
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
plugins: [react(), precompress()],
|
||||
define: {
|
||||
__APP_VERSION__: JSON.stringify(APP_VERSION),
|
||||
},
|
||||
@@ -63,6 +99,17 @@ export default defineConfig({
|
||||
},
|
||||
build: {
|
||||
outDir: "dist",
|
||||
sourcemap: true,
|
||||
// Maps are still written (for debugging a build), but no bundle points at
|
||||
// them, so a browser never downloads them.
|
||||
sourcemap: "hidden",
|
||||
rollupOptions: {
|
||||
output: {
|
||||
// i18n/index.ts loads locale files lazily: one chunk per language.
|
||||
manualChunks(id) {
|
||||
const m = /[\\/]i18n[\\/]locales[\\/](\w+)[\\/]/.exec(id);
|
||||
return m ? `locale-${m[1]}` : undefined;
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
+4
-2
@@ -1152,7 +1152,7 @@ head of `toolFlow.transitions` (one window pass over the events for both).
|
||||
The bundle scans every event, so it is computed in a worker thread on its own
|
||||
read-only connection (`server/lib/read-pool.js`) and never stalls another
|
||||
request, hook or websocket meanwhile. Identical requests in flight share one
|
||||
run. `AGENTHUB_READ_WORKER=0` computes it inline instead.
|
||||
run, and a result is reused for 30 s per distinct query. `AGENTHUB_READ_WORKER=0` computes it inline instead.
|
||||
|
||||
**Status codes:**
|
||||
- **200** — the bundle, or the requested sections of it
|
||||
@@ -1721,7 +1721,7 @@ sequenceDiagram
|
||||
GET /api/events
|
||||
```
|
||||
|
||||
Returns `{ events, limit, offset, total }`, newest first, filtered by `event_type`, `tool_name`, `agent_id`, `session_id` (each comma-separated), `q`, `from`/`to` (on `created_at`) and `sources`. Each row carries its labels, so a list page need not fetch every session and agent to name them: `session_name`, `session_cwd`, `session_lane_id`, `agent_name` and `agent_subagent_type` (each `null` when the session/agent row is missing). These columns are REST-only — the WebSocket `new_event` message is unchanged.
|
||||
Returns `{ events, limit, offset, total }`, newest first, filtered by `event_type`, `tool_name`, `agent_id`, `session_id` (each comma-separated), `q`, `from`/`to` (on `created_at`) and `sources`. Each row carries its labels, so a list page need not fetch every session and agent to name them: `session_name`, `session_cwd`, `session_lane_id`, `agent_name` and `agent_subagent_type` (each `null` when the session/agent row is missing). These columns are REST-only — the WebSocket `new_event` message does not carry them (it carries the row `id`).
|
||||
|
||||
---
|
||||
|
||||
@@ -2048,6 +2048,8 @@ GET /api/analytics?tz_offset=<minutes>&sources=<csv>&tool=<id>&from=<YYYY-MM-DD>
|
||||
|
||||
The Analytics bundle (`tokens`, `total_cost`, `tool_usage`, `daily_events`, `daily_sessions`, `agent_types`, `event_types`, `avg_events_per_session`, `total_subagents`, `overview`, `agents_by_status`, `sessions_by_status`). With `from`/`to` (same rules as above) the shape is unchanged and the numbers narrow: sessions and agents count by `started_at`, events by `created_at`, and `tokens` / `total_cost` come from the cost rows of the days in the range (`token_usage` has no date, so tokens follow the spend-day split). `daily_events` and `daily_sessions` keep their 365-day window.
|
||||
|
||||
The four numbers that scan `events` (`tool_usage`, `daily_events`, `event_types`, `avg_events_per_session`) are computed in the read worker (`server/lib/read-pool.js`) and reused for 10 s per distinct query (scope, range, `tz_offset`), so they may trail a new event by up to that long. A worker job past `AGENTHUB_READ_TIMEOUT_MS` answers **503** `EREADTIMEOUT`.
|
||||
|
||||
#### Spend Budgets
|
||||
|
||||
A budget is an alert rule of type `budget`, created and edited through `/api/alerts/rules`:
|
||||
|
||||
+21
-1
@@ -677,7 +677,7 @@ CREATE INDEX idx_agents_status ON agents(status);
|
||||
-- tens of seconds to sub-second.
|
||||
CREATE INDEX idx_events_agent_type ON events(agent_id, event_type);
|
||||
|
||||
-- A session's events in insert order. NOT a prefix of idx_events_session_type
|
||||
-- A session's events in insert order. NOT a prefix of idx_events_session_type_tool
|
||||
-- (not id-ordered): every hook's duplicate guard reads a session's latest event
|
||||
-- through it. Dropping it (ad6e801) made that read sort the whole session per
|
||||
-- hook and made a correlated "next tool event" query quadratic — minutes on a
|
||||
@@ -687,6 +687,14 @@ CREATE INDEX idx_events_session ON events(session_id, id);
|
||||
-- Per-tool counts (analytics, workflows) and the events filter's tool list
|
||||
-- read this alone instead of every event row (~300 ms -> ~20 ms at 233k rows).
|
||||
CREATE INDEX idx_events_tool ON events(tool_name);
|
||||
|
||||
-- A session's events by type and tool, covering: session stats (per-tool and
|
||||
-- per-type counts), the hook's TurnDuration/APIError dedupe (one read per hook)
|
||||
-- and the import's newest-per-type resume point read no event row
|
||||
-- (1.2 s -> 20 ms on a 29K-event session). Replaces idx_events_session_type
|
||||
-- (session_id, event_type), dropped at startup, so a hook writes no more index
|
||||
-- entries than before.
|
||||
CREATE INDEX idx_events_session_type_tool ON events(session_id, event_type, tool_name, created_at);
|
||||
```
|
||||
|
||||
### tool_executions Indexes
|
||||
@@ -872,8 +880,20 @@ db.pragma("foreign_keys = ON");
|
||||
db.pragma("busy_timeout = 5000"); // two dashboards may share the file
|
||||
db.pragma("synchronous = NORMAL"); // safe with WAL: a power cut loses only the last commits, never the file
|
||||
db.pragma("journal_size_limit = 67108864"); // a checkpoint truncates the WAL back to 64 MB
|
||||
db.pragma("cache_size = -65536"); // 64 MB page cache (default 2 MB)
|
||||
db.pragma("mmap_size = 268435456"); // memory-mapped reads, 256 MB
|
||||
```
|
||||
|
||||
The read worker (`server/lib/read-pool.js`) sets the same `cache_size`/`mmap_size`.
|
||||
|
||||
**Checkpoints.** The running server sets `wal_autocheckpoint = 0` on its main
|
||||
connection and checkpoints every `DASHBOARD_WAL_CHECKPOINT_MS` (default 5000, `0` =
|
||||
SQLite's automatic checkpoint as before) with `wal_checkpoint(PASSIVE)` from the read
|
||||
worker's own writable connection. SQLite's automatic checkpoint runs inside whichever
|
||||
`COMMIT` crosses 1000 WAL pages — a hook's, on the event loop — and measured up to 2.7 s
|
||||
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.
|
||||
|
||||
**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.
|
||||
|
||||
+18
-9
@@ -263,8 +263,9 @@ AGENTHUB_CURSOR_DIR= # where Cursor keeps its data (default ~
|
||||
|
||||
# Pricing and saved settings
|
||||
AGENTHUB_PRICING_SYNC= # 0|false|off disables automatic pricing from LiteLLM (default on)
|
||||
AGENTHUB_READ_WORKER= # 0 runs heavy aggregates (GET /api/workflows) inline instead of in the read worker (default worker)
|
||||
AGENTHUB_READ_WORKER= # 0 runs heavy aggregates (GET /api/workflows, /api/analytics' event scans) inline instead of in the read worker (default worker)
|
||||
AGENTHUB_READ_TIMEOUT_MS=60000 # a read-worker job past this answers 503 EREADTIMEOUT and gets a fresh worker
|
||||
DASHBOARD_WAL_CHECKPOINT_MS=5000 # WAL checkpoint from the read worker instead of inside a hook's COMMIT (0 = SQLite's automatic one)
|
||||
AGENTHUB_SETTINGS_FILE= # where dashboard-saved settings persist (default ~/.config/agenthub/settings.env);
|
||||
# load order: real env > the checkout's .env > this file
|
||||
|
||||
@@ -726,14 +727,22 @@ node --optimize-for-size server/index.js
|
||||
|
||||
### SQLite Tuning
|
||||
|
||||
```javascript
|
||||
// server/db.js - Add these pragmas
|
||||
db.pragma('journal_mode = WAL'); // Write-Ahead Logging
|
||||
db.pragma('synchronous = NORMAL'); // Faster writes
|
||||
db.pragma('cache_size = -64000'); // 64MB cache
|
||||
db.pragma('temp_store = MEMORY'); // Temp tables in memory
|
||||
db.pragma('mmap_size = 30000000000'); // Memory-mapped I/O
|
||||
db.pragma('page_size = 4096'); // Optimal page size
|
||||
`server/db.js` already sets WAL, `synchronous = NORMAL`, a 64 MB `cache_size` and a
|
||||
256 MB `mmap_size`, and the server checkpoints the WAL from its read worker
|
||||
(`DASHBOARD_WAL_CHECKPOINT_MS`) instead of inside a hook's `COMMIT` — see
|
||||
[DATABASE.md § SQLite Pragmas](DATABASE.md#sqlite-pragmas). Nothing to add by hand.
|
||||
|
||||
### Compression
|
||||
|
||||
The client build writes a `.br` and a `.gz` beside every hashed asset, and the
|
||||
server sends the one the browser accepts (`Content-Encoding`, `Vary: Accept-Encoding`)
|
||||
— a first Workspace load is ~75 % smaller with no compression CPU at request time.
|
||||
API responses are not compressed by AgentHub; behind nginx, add:
|
||||
|
||||
```nginx
|
||||
gzip on;
|
||||
gzip_types application/json;
|
||||
gzip_min_length 1024;
|
||||
```
|
||||
|
||||
### Nginx Tuning
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
# Performance pass — 10+ concurrent users, lean local mode
|
||||
|
||||
Audit 2026-10-07 against a copy of the real DB (1.2 GB, 253K events). Baseline,
|
||||
10 simulated browsers + 10 hooks/s for 90 s: event-loop delay p99 1239 ms, request
|
||||
p95 ~10 s, 266 failed. Bench tools: `/tmp/ahperf/tools/` (`clients.js`, `hookload.js`,
|
||||
`bench.js`). Target: ELD p99 < 100 ms, request p95 < 300 ms, 0 failed.
|
||||
|
||||
Dev (4830) and prod (4820) keep sharing one `dashboard.db`.
|
||||
|
||||
## Server
|
||||
- [x] S1 `/api/workflows/skill-usage`: `+event_type` + range instead of LIKE (784 ms → ~5 ms)
|
||||
- [x] S2 `/api/analytics` into `read-pool.js` JOBS + short memo keyed by scope/args
|
||||
- [x] S3 `/api/workflows` result memo (30 s)
|
||||
- [x] S4 `idx_events_session_type_tool` replaces `idx_events_session_type` (partial index skipped: the 30 s workflows memo covers it); `cache_size`/`mmap_size`
|
||||
- [x] S5 WAL: `wal_autocheckpoint=0` on the main connection, PASSIVE checkpoint off-thread, fallback
|
||||
- [x] S6 tmux: 1 s `list-sessions` memo (cleared by this process's new/kill), one `liveSessions()` per `GET /api/lanes`, attach options chained (4 spawns → 2), async `ps` for the watchdog, heal tick skipped when nothing runs
|
||||
- [x] S7 hooks: hoist TurnDuration/APIError statements + watermark; one `listLanes()` per hook; hourly upsert only on change
|
||||
- [x] S8 hooks.js `session_id` rebind skipped for slot 1–9 panes
|
||||
- [x] S9 startup subagent backfill: do not re-parse unstampable files every boot
|
||||
- [x] S10 pty-attach backpressure
|
||||
- [x] S11 serve pre-compressed `.br`/`.gz` assets
|
||||
- [x] S12 broadcasts only after the hook transaction commits
|
||||
- [x] S13 `new_event` carries `id`
|
||||
- [~] S14 codex-usage memo — DROPPED: an in-memory "already read" map survives Clear data and blocks the re-import (caught by codex-usage tests); the pass costs ~5 ms per 15 s
|
||||
- [x] S15 transcript newline scan via `indexOf`
|
||||
|
||||
## Client
|
||||
- [x] C1 no WS-triggered refetch in hidden tabs; hidden-tab pollers paused; drop hourly `/updates/check`
|
||||
- [x] C2 throttle WorkspaceTree / WorkspaceSessionList / `/api/run` refetchers; lazy notification lookup
|
||||
- [x] C3 WS reconnect jitter; terminal retry backoff
|
||||
- [x] C4 heavier throttles for aggregates / detail refetches; Monitor `keepIfSame`; GET in-flight dedupe
|
||||
- [x] C5 build: pre-compress assets, `sourcemap: "hidden"`
|
||||
- [x] C6 load only the active locale; lazy routes/Sagi/modals/xterm
|
||||
- [x] C7 Sagi re-render fixes; service-worker asset cache
|
||||
|
||||
## Verify
|
||||
- [x] `npm run test:server` (2556/2556), `npm run test:client` (1084/1084), `tsc -b`, header check; headless Chrome smoke (en + vi, 4 pages, terminal attach)
|
||||
- [x] re-run the 10-client bench (server side, same old-client simulation) — see Result
|
||||
|
||||
## Result (server, `clients.js 10 90 10`, same simulated old client)
|
||||
|
||||
| | before | after |
|
||||
|---|---|---|
|
||||
| event-loop delay p99 / max | 1239 ms / 2.0 s | 31.8 ms / 94 ms |
|
||||
| failed requests | 266 | 0 |
|
||||
| requests served | 74/s | 111/s |
|
||||
| hook p95 / p99 (10/s) | — | 7.6 / 28.8 ms |
|
||||
| RSS | 633 MB | 346 MB |
|
||||
|
||||
Biggest single cause after the first round: 2,247 synchronous `tmux list-sessions`
|
||||
from `GET /api/run` = 60 s of a 90 s run blocked (fork of a 600 MB process); the 1 s
|
||||
memo removed it. The client fixes (C1–C4) cut the request rate itself on top.
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
openapi: 3.0.3
|
||||
info:
|
||||
title: Agent Dashboard for Claude Code API
|
||||
version: 2.5.9
|
||||
version: 2.5.10
|
||||
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ĩ
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "agenthub",
|
||||
"version": "2.5.9",
|
||||
"version": "2.5.10",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "agenthub",
|
||||
"version": "2.5.9",
|
||||
"version": "2.5.10",
|
||||
"hasInstallScript": true,
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "agenthub",
|
||||
"version": "2.5.9",
|
||||
"version": "2.5.10",
|
||||
"bin": {
|
||||
"agenthub": "bin/agenthub.js"
|
||||
},
|
||||
|
||||
@@ -2652,6 +2652,22 @@ async function scanAndImportSubagents(dbModule, sessionId, transcriptPath, opts
|
||||
return { imported: subFiles.length, created, reparented };
|
||||
}
|
||||
|
||||
/** Count, total size and newest mtime of a session's subagent files. */
|
||||
function subagentFilesFingerprint(files) {
|
||||
let size = 0;
|
||||
let newest = 0;
|
||||
for (const f of files) {
|
||||
try {
|
||||
const st = fs.statSync(f);
|
||||
size += st.size;
|
||||
newest = Math.max(newest, st.mtimeMs);
|
||||
} catch {
|
||||
/* vanished between listing and stat */
|
||||
}
|
||||
}
|
||||
return `${files.length}:${size}:${Math.round(newest)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Backfill metadata.tokens onto existing subagent rows that predate per-agent
|
||||
* cost tracking. New imports and live SubagentStop scans stamp each subagent's
|
||||
@@ -2667,7 +2683,11 @@ async function scanAndImportSubagents(dbModule, sessionId, transcriptPath, opts
|
||||
* completely untouched; only the per-agent breakdown is filled in.
|
||||
*
|
||||
* Idempotent and self-limiting: once a row has a tokens key it drops out of the
|
||||
* driving query, so steady-state startups do near-zero work.
|
||||
* driving query, so steady-state startups do near-zero work. A row that can
|
||||
* never be stamped (its file holds no usage) would keep its session in the
|
||||
* query forever, so a session's subagent files are fingerprinted (count, size,
|
||||
* newest mtime) into `metadata.subagent_tokens_checked` after a pass and are
|
||||
* not parsed again until they change — measured 2–5 s of every boot before.
|
||||
*/
|
||||
async function backfillSubagentTokenMetadata(dbModule) {
|
||||
const { db } = dbModule;
|
||||
@@ -2721,6 +2741,14 @@ async function backfillSubagentTokenMetadata(dbModule) {
|
||||
continue;
|
||||
}
|
||||
if (!subFiles || subFiles.length === 0) continue;
|
||||
const fingerprint = subagentFilesFingerprint(subFiles);
|
||||
let checked = null;
|
||||
try {
|
||||
checked = s.meta ? JSON.parse(s.meta).subagent_tokens_checked : null;
|
||||
} catch {
|
||||
/* unreadable metadata: treat as never checked */
|
||||
}
|
||||
if (checked === fingerprint) continue; // nothing changed since the last pass
|
||||
scanned++;
|
||||
const mainAgentId = `${s.session_id}-main`;
|
||||
for (const file of subFiles) {
|
||||
@@ -2733,6 +2761,14 @@ async function backfillSubagentTokenMetadata(dbModule) {
|
||||
/* non-fatal — partial or unrelated files are common */
|
||||
}
|
||||
}
|
||||
try {
|
||||
db.prepare(
|
||||
`UPDATE sessions SET metadata = json_set(COALESCE(metadata, '{}'), '$.subagent_tokens_checked', ?)
|
||||
WHERE id = ? AND json_valid(COALESCE(metadata, '{}'))`
|
||||
).run(fingerprint, s.session_id);
|
||||
} catch {
|
||||
/* the next boot simply checks this session again */
|
||||
}
|
||||
}
|
||||
return { sessions: scanned, stamped };
|
||||
}
|
||||
|
||||
+17
-1
@@ -14,7 +14,9 @@
|
||||
* ones kept there are what the dormant stage/detection code is tested against.
|
||||
* `AGENTHUB_SETTINGS_FILE` goes to the same temp dir, so a suite that saves a
|
||||
* setting never writes the developer's real `~/.config/agenthub/settings.env`,
|
||||
* and `AGENTHUB_PRICING_SYNC=0` keeps every suite off the network.
|
||||
* and `AGENTHUB_PRICING_SYNC=0` keeps every suite off the network. The
|
||||
* `GIT_DIR`-family variables a git hook exports are dropped too, so a test's
|
||||
* own `git init`/`commit` can never land in the real repository.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
@@ -44,6 +46,20 @@ const env = {
|
||||
};
|
||||
delete env.TMUX;
|
||||
delete env.TMUX_PANE;
|
||||
// Git exports these to a hook it runs from a linked worktree (the pre-commit
|
||||
// hook runs this suite): inherited, every `git init`/`commit` a test makes in
|
||||
// its temp folder went to the REAL repository instead — commits on the
|
||||
// worktree's HEAD and `core.bare = true` in the shared config.
|
||||
for (const k of [
|
||||
"GIT_DIR",
|
||||
"GIT_INDEX_FILE",
|
||||
"GIT_WORK_TREE",
|
||||
"GIT_COMMON_DIR",
|
||||
"GIT_PREFIX",
|
||||
"GIT_OBJECT_DIRECTORY",
|
||||
]) {
|
||||
delete env[k];
|
||||
}
|
||||
|
||||
const result = spawnSync(process.execPath, ["--test", ...args, ...(args.length ? [] : files)], {
|
||||
stdio: "inherit",
|
||||
|
||||
@@ -1813,11 +1813,13 @@ describe("Database Integrity", () => {
|
||||
|
||||
assert.ok(indexes.includes("idx_agents_session"));
|
||||
assert.ok(indexes.includes("idx_agents_status"));
|
||||
// (session_id, id) is NOT a prefix of idx_events_session_type: the hook
|
||||
// (session_id, id) is NOT a prefix of idx_events_session_type_tool: the hook
|
||||
// duplicate guard reads a session's latest event by id through it.
|
||||
assert.ok(indexes.includes("idx_events_session_created"));
|
||||
assert.ok(indexes.includes("idx_events_session"));
|
||||
assert.ok(indexes.includes("idx_events_type"));
|
||||
assert.ok(indexes.includes("idx_events_session_type_tool"));
|
||||
assert.ok(!indexes.includes("idx_events_session_type"));
|
||||
assert.ok(indexes.includes("idx_events_created"));
|
||||
assert.ok(indexes.includes("idx_sessions_status"));
|
||||
assert.ok(indexes.includes("idx_sessions_started"));
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
* @file Tests the DASHBOARD_CLIENT_DIST override in server/index.js. A plugin
|
||||
* install runs the server from a read-only plugin cache directory, so the
|
||||
* client bundle is served from the writable runtime dir instead of the
|
||||
* checkout's client/dist. Also asserts the API still answers when the
|
||||
* checkout's client/dist, with a hashed asset's pre-compressed `.br`/`.gz`
|
||||
* sibling sent to a browser that accepts it. Also asserts the API still answers when the
|
||||
* configured bundle directory does not exist yet (the normal state before
|
||||
* /agenthub-open builds it).
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
@@ -19,6 +20,16 @@ const TMP = fs.mkdtempSync(path.join(os.tmpdir(), "agenthub-clientdist-"));
|
||||
const DIST = path.join(TMP, "client-dist");
|
||||
fs.mkdirSync(DIST);
|
||||
fs.writeFileSync(path.join(DIST, "index.html"), "<!doctype html><title>from-runtime</title>");
|
||||
// A hashed bundle with the pre-compressed siblings the client build writes.
|
||||
fs.mkdirSync(path.join(DIST, "assets"));
|
||||
const BUNDLE = "console.log('plain bundle');".repeat(50);
|
||||
fs.writeFileSync(path.join(DIST, "assets", "app-abc123.js"), BUNDLE);
|
||||
fs.writeFileSync(
|
||||
path.join(DIST, "assets", "app-abc123.js.br"),
|
||||
require("zlib").brotliCompressSync(BUNDLE)
|
||||
);
|
||||
fs.writeFileSync(path.join(DIST, "assets", "app-abc123.js.gz"), require("zlib").gzipSync(BUNDLE));
|
||||
fs.writeFileSync(path.join(DIST, "assets", "only-plain.css"), "body{}");
|
||||
|
||||
// Must be set BEFORE requiring the server: the data dir, discovery file and
|
||||
// the static mount are all resolved at startup. NODE_ENV=production is the
|
||||
@@ -38,12 +49,15 @@ const { db } = require("../db");
|
||||
let server;
|
||||
let BASE;
|
||||
|
||||
function get(urlPath) {
|
||||
function get(urlPath, headers = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = http.get(new URL(urlPath, BASE), (res) => {
|
||||
let body = "";
|
||||
res.on("data", (c) => (body += c));
|
||||
res.on("end", () => resolve({ status: res.statusCode, body }));
|
||||
const req = http.get(new URL(urlPath, BASE), { headers }, (res) => {
|
||||
const chunks = [];
|
||||
res.on("data", (c) => chunks.push(c));
|
||||
res.on("end", () => {
|
||||
const raw = Buffer.concat(chunks);
|
||||
resolve({ status: res.statusCode, body: raw.toString(), raw, headers: res.headers });
|
||||
});
|
||||
});
|
||||
req.on("error", reject);
|
||||
});
|
||||
@@ -68,6 +82,33 @@ describe("DASHBOARD_CLIENT_DIST override", () => {
|
||||
assert.match(res.body, /from-runtime/);
|
||||
});
|
||||
|
||||
it("serves a hashed asset's pre-compressed sibling to a browser that takes it", async () => {
|
||||
const zlib = require("zlib");
|
||||
const br = await get("/assets/app-abc123.js", { "accept-encoding": "gzip, deflate, br" });
|
||||
assert.equal(br.status, 200);
|
||||
assert.equal(br.headers["content-encoding"], "br");
|
||||
assert.match(br.headers["content-type"], /javascript/);
|
||||
assert.match(br.headers.vary, /Accept-Encoding/i);
|
||||
assert.match(br.headers["cache-control"], /immutable/);
|
||||
assert.equal(zlib.brotliDecompressSync(br.raw).toString(), BUNDLE);
|
||||
|
||||
const gz = await get("/assets/app-abc123.js", { "accept-encoding": "gzip" });
|
||||
assert.equal(gz.headers["content-encoding"], "gzip");
|
||||
assert.equal(zlib.gunzipSync(gz.raw).toString(), BUNDLE);
|
||||
|
||||
const plain = await get("/assets/app-abc123.js", { "accept-encoding": "identity" });
|
||||
assert.equal(plain.headers["content-encoding"], undefined);
|
||||
assert.equal(plain.body, BUNDLE);
|
||||
|
||||
// No sibling on disk: the plain file, as before.
|
||||
const css = await get("/assets/only-plain.css", { "accept-encoding": "br" });
|
||||
assert.equal(css.headers["content-encoding"], undefined);
|
||||
assert.equal(css.body, "body{}");
|
||||
// A name that is not a flat file name never reaches the disk lookup.
|
||||
const walk = await get("/assets/..%2findex.html", { "accept-encoding": "br" });
|
||||
assert.equal(walk.headers["content-encoding"], undefined);
|
||||
});
|
||||
|
||||
it("keeps the API working alongside the override", async () => {
|
||||
const res = await get("/api/health");
|
||||
assert.equal(res.status, 200);
|
||||
|
||||
@@ -541,6 +541,30 @@ describe("hook → lane binding", () => {
|
||||
assert.equal((await request("GET", "/api/lanes")).body.lanes.length, before);
|
||||
});
|
||||
|
||||
it("keeps the lane's session when a split pane (slot 1–9) of the workspace sends hooks", async () => {
|
||||
const created = await request("POST", "/api/lanes", { cwd: "/tmp/lane-split-pane" });
|
||||
const id = created.body.lane.id;
|
||||
const hook = (session_id, run_id) =>
|
||||
request("POST", "/api/hooks/event", {
|
||||
hook_type: "PostToolUse",
|
||||
run_id,
|
||||
data: {
|
||||
session_id,
|
||||
cwd: "/tmp/lane-split-pane",
|
||||
tool_name: "Read",
|
||||
tool_use_id: session_id,
|
||||
},
|
||||
});
|
||||
await hook("sess-main", `agenthub-lane-${id}`);
|
||||
assert.equal((await request("GET", `/api/lanes/${id}`)).body.lane.session_id, "sess-main");
|
||||
// A split pane's session never takes the lane over…
|
||||
await hook("sess-split", `agenthub-lane-${id}-2`);
|
||||
assert.equal((await request("GET", `/api/lanes/${id}`)).body.lane.session_id, "sess-main");
|
||||
// …while a session outside the dashboard still does, as before.
|
||||
await hook("sess-outside", undefined);
|
||||
assert.equal((await request("GET", `/api/lanes/${id}`)).body.lane.session_id, "sess-outside");
|
||||
});
|
||||
|
||||
it("clears needs_action only from the session that raised it, not from cross-session rebinds", async () => {
|
||||
const created = await request("POST", "/api/lanes", {
|
||||
cwd: "/tmp/lane-cross-session",
|
||||
|
||||
@@ -68,7 +68,13 @@ describe("pty-attach", () => {
|
||||
return "";
|
||||
});
|
||||
ptyAttach.attach(makeFakeWs(), "agenthub-lane-1", { cols: 80, rows: 24 });
|
||||
assert.deepEqual(calls[0], ["set-option", "-t", "=agenthub-lane-1:", "mouse", "on"]);
|
||||
assert.deepEqual(calls[0].slice(0, 5), [
|
||||
"set-option",
|
||||
"-t",
|
||||
"=agenthub-lane-1:",
|
||||
"mouse",
|
||||
"on",
|
||||
]);
|
||||
});
|
||||
|
||||
it("attaches with the RUNNING tmux server's own binary, not the one on PATH", () => {
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
/**
|
||||
* @file Tests server/lib/read-pool.js: a read job runs in the worker on its own
|
||||
* connection, identical calls in flight share one run, a job over the timeout
|
||||
* is refused with EREADTIMEOUT and the next one gets a fresh worker, and
|
||||
* AGENTHUB_READ_WORKER=0 runs the job inline.
|
||||
* is refused with EREADTIMEOUT and the next one gets a fresh worker,
|
||||
* AGENTHUB_READ_WORKER=0 runs the job inline, `maxAgeMs` reuses a young result,
|
||||
* the analytics events job matches the main connection, and the WAL checkpoint
|
||||
* runs on the worker's writable connection.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
@@ -63,6 +65,41 @@ describe("read-pool", () => {
|
||||
assert.equal(data.stats.totalSessions, 1);
|
||||
});
|
||||
|
||||
it("reuses a result younger than maxAgeMs, and only for the same args", async () => {
|
||||
const first = await runRead(
|
||||
"workflows",
|
||||
{ sections: ["stats"], tag: "memo" },
|
||||
{ maxAgeMs: 60_000 }
|
||||
);
|
||||
db.prepare("INSERT INTO sessions (id, status) VALUES ('rp-2', 'completed')").run();
|
||||
const again = await runRead(
|
||||
"workflows",
|
||||
{ sections: ["stats"], tag: "memo" },
|
||||
{ maxAgeMs: 60_000 }
|
||||
);
|
||||
assert.equal(again, first); // the cached object, not a new run
|
||||
const fresh = await runRead("workflows", { sections: ["stats"], tag: "memo" });
|
||||
assert.equal(fresh.stats.totalSessions, first.stats.totalSessions + 1);
|
||||
db.prepare("DELETE FROM sessions WHERE id = 'rp-2'").run();
|
||||
});
|
||||
|
||||
it("computes the analytics events numbers in the worker like the main connection", async () => {
|
||||
const { eventAggregates } = require("../lib/scoped-stats");
|
||||
const args = { scope: null, range: null, tzModifier: "+0 minutes" };
|
||||
const inWorker = await runRead("analyticsEvents", args);
|
||||
assert.deepEqual(inWorker, eventAggregates(db, null, null, "+0 minutes"));
|
||||
assert.deepEqual(inWorker.toolUsage.map((r) => [r.tool_name, r.count]).sort(), [
|
||||
["Edit", 2],
|
||||
["Read", 2],
|
||||
]);
|
||||
});
|
||||
|
||||
it("checkpoints the WAL from the worker", async () => {
|
||||
const [row] = await runRead("walCheckpoint");
|
||||
assert.equal(row.busy, 0);
|
||||
assert.ok(row.log >= row.checkpointed);
|
||||
});
|
||||
|
||||
it("runs inline with AGENTHUB_READ_WORKER=0, and rejects an unknown job", async () => {
|
||||
process.env.AGENTHUB_READ_WORKER = "0";
|
||||
const data = await runRead("workflows", { sections: ["stats"], tag: "inline" });
|
||||
|
||||
@@ -401,8 +401,14 @@ describe("watchdog liveness reap", () => {
|
||||
const cwd = "/tmp/liveness-watchdog";
|
||||
await seedSession(sid, cwd);
|
||||
|
||||
liveness.probeLiveCwds = () => ({ available: true, cwds: new Set() });
|
||||
hooksRouter.watchdogCheck();
|
||||
// The watchdog's beat probes asynchronously (`ps` off the event loop).
|
||||
const realAsync = liveness.probeLiveCwdsAsync;
|
||||
liveness.probeLiveCwdsAsync = async () => ({ available: true, cwds: new Set() });
|
||||
try {
|
||||
await hooksRouter.watchdogCheck();
|
||||
} finally {
|
||||
liveness.probeLiveCwdsAsync = realAsync;
|
||||
}
|
||||
|
||||
assert.equal(stmts.getSession.get(sid).status, "completed");
|
||||
});
|
||||
|
||||
@@ -143,4 +143,26 @@ describe("subagent token backfill", () => {
|
||||
// a tokens key), so no session is re-scanned.
|
||||
assert.equal(res.sessions, 0);
|
||||
});
|
||||
|
||||
it("parses a row it can never stamp once, until its files change", async () => {
|
||||
// A subagent row whose transcript holds no usage stays tokens-less forever,
|
||||
// which used to re-parse its whole session tree on every boot.
|
||||
stmts.insertAgent.run(
|
||||
`${SESSION}-jsonl-ghost`,
|
||||
SESSION,
|
||||
"ghost",
|
||||
"subagent",
|
||||
"general-purpose",
|
||||
"completed",
|
||||
null,
|
||||
MAIN,
|
||||
JSON.stringify({ imported: true, source: "jsonl" })
|
||||
);
|
||||
fs.writeFileSync(path.join(tmpDir, SESSION, "subagents", "agent-ghost.jsonl"), "");
|
||||
assert.equal((await importHistory.backfillSubagentTokenMetadata(dbModule)).sessions, 1);
|
||||
assert.equal((await importHistory.backfillSubagentTokenMetadata(dbModule)).sessions, 0);
|
||||
// A new subagent file appears: the session is looked at again.
|
||||
fs.writeFileSync(path.join(tmpDir, SESSION, "subagents", "agent-new.jsonl"), "");
|
||||
assert.equal((await importHistory.backfillSubagentTokenMetadata(dbModule)).sessions, 1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -28,6 +28,35 @@ describe("tmux wrapper", () => {
|
||||
assert.equal(tmux.hasSession("agenthub-lane-1"), false);
|
||||
});
|
||||
|
||||
it("liveSessions answers every live name with ONE list-sessions call", () => {
|
||||
const calls = [];
|
||||
tmux.__setExecImpl((args) => {
|
||||
calls.push(args[0]);
|
||||
return "agenthub-lane-1\nagenthub-lane-12\nmain\n";
|
||||
});
|
||||
assert.deepEqual([...tmux.liveSessions()], ["agenthub-lane-1", "agenthub-lane-12", "main"]);
|
||||
assert.deepEqual(calls, ["list-sessions"]);
|
||||
});
|
||||
|
||||
it("liveSessions is empty when tmux answers that no server runs (or is not installed)", () => {
|
||||
tmux.__setExecImpl(() => {
|
||||
throw Object.assign(new Error("no server running"), { status: 1 });
|
||||
});
|
||||
assert.equal(tmux.liveSessions().size, 0);
|
||||
tmux.__setExecImpl(() => {
|
||||
throw Object.assign(new Error("spawn tmux ENOENT"), { code: "ENOENT" });
|
||||
});
|
||||
assert.equal(tmux.liveSessions().size, 0);
|
||||
});
|
||||
|
||||
it("liveSessions is null when tmux could not be asked — not 'every pane is gone'", () => {
|
||||
// Out of memory/processes: the panes are fine, the question failed.
|
||||
tmux.__setExecImpl(() => {
|
||||
throw Object.assign(new Error("spawnSync tmux EAGAIN"), { code: "EAGAIN" });
|
||||
});
|
||||
assert.equal(tmux.liveSessions(), null);
|
||||
});
|
||||
|
||||
it("newSession names a command that exited at once instead of tmux's set-option error", () => {
|
||||
tmux.__setExecImpl((args) => {
|
||||
if (args[0] === "new-session") return "";
|
||||
@@ -79,6 +108,22 @@ describe("tmux wrapper", () => {
|
||||
calls = fake(true);
|
||||
tmux.enableMouse("agenthub-lane-1");
|
||||
assert.ok(calls.some((c) => c[0] === "set-option" && c[2] === "=agenthub-lane-1:"));
|
||||
// tmux chains the four options into two spawns; psmux above got four.
|
||||
const sets = calls.filter((c) => c[0] === "set-option");
|
||||
assert.equal(sets.length, 2);
|
||||
assert.deepEqual(sets[0], [
|
||||
"set-option",
|
||||
"-t",
|
||||
"=agenthub-lane-1:",
|
||||
"mouse",
|
||||
"on",
|
||||
";",
|
||||
"set-option",
|
||||
"-t",
|
||||
"=agenthub-lane-1:",
|
||||
"status",
|
||||
"off",
|
||||
]);
|
||||
});
|
||||
|
||||
it("newSession builds the correct argv", () => {
|
||||
@@ -104,16 +149,18 @@ describe("tmux wrapper", () => {
|
||||
"--model",
|
||||
"opus",
|
||||
]);
|
||||
assert.deepEqual(calls[1], ["set-option", "-t", "=agenthub-lane-1:", "mouse", "on"]);
|
||||
assert.deepEqual(calls[2], ["set-option", "-t", "=agenthub-lane-1:", "status", "off"]);
|
||||
assert.deepEqual(calls[3], ["set-option", "-t", "=agenthub-lane-1:", "pane-scrollbars", "on"]);
|
||||
assert.deepEqual(calls[4], [
|
||||
"set-option",
|
||||
"-t",
|
||||
"=agenthub-lane-1:",
|
||||
"pane-scrollbars-style",
|
||||
// One tmux call per `;`-chained group: the options every tmux knows, then
|
||||
// the 3.7+ scrollbar pair (allowed to fail on its own).
|
||||
assert.deepEqual(calls[1], [
|
||||
...["set-option", "-t", "=agenthub-lane-1:", "mouse", "on", ";"],
|
||||
...["set-option", "-t", "=agenthub-lane-1:", "status", "off"],
|
||||
]);
|
||||
assert.deepEqual(calls[2], [
|
||||
...["set-option", "-t", "=agenthub-lane-1:", "pane-scrollbars", "on", ";"],
|
||||
...["set-option", "-t", "=agenthub-lane-1:", "pane-scrollbars-style"],
|
||||
"fg=brightwhite,bg=black,width=1,pad=0",
|
||||
]);
|
||||
assert.equal(calls.length, 3);
|
||||
});
|
||||
|
||||
it("newSession still succeeds on a tmux older than 3.7 (no pane-scrollbars)", () => {
|
||||
@@ -171,6 +218,22 @@ describe("tmux wrapper", () => {
|
||||
assert.deepEqual(tmux.listSessions("agenthub-lane-"), ["agenthub-lane-1", "agenthub-lane-2"]);
|
||||
});
|
||||
|
||||
it("shares one list-sessions answer for a second, until this process creates or kills one", () => {
|
||||
const calls = [];
|
||||
let names = "agenthub-lane-1\n";
|
||||
tmux.__setExecImpl((args) => {
|
||||
calls.push(args[0]);
|
||||
return args[0] === "list-sessions" ? names : "";
|
||||
});
|
||||
assert.deepEqual(tmux.listSessions("agenthub-lane-"), ["agenthub-lane-1"]);
|
||||
assert.deepEqual([...tmux.liveSessions()], ["agenthub-lane-1"]);
|
||||
assert.equal(calls.filter((c) => c === "list-sessions").length, 1);
|
||||
tmux.killSession("agenthub-lane-1");
|
||||
names = "";
|
||||
assert.deepEqual(tmux.listSessions("agenthub-lane-"), []);
|
||||
assert.equal(calls.filter((c) => c === "list-sessions").length, 2);
|
||||
});
|
||||
|
||||
it("listSessions returns [] when tmux has no sessions at all (exit 1)", () => {
|
||||
tmux.__setExecImpl(() => {
|
||||
const e = new Error("no server running");
|
||||
|
||||
+26
-28
@@ -151,6 +151,11 @@ db.pragma("synchronous = NORMAL");
|
||||
// (an import, a cleanup) left a WAL of hundreds of MB that never shrank while
|
||||
// any dashboard kept the database open. See also `maintainDatabase`.
|
||||
db.pragma("journal_size_limit = 67108864");
|
||||
// A 64 MB page cache (default 2 MB) and memory-mapped reads: the aggregates
|
||||
// re-read the same index pages, 5–45 % faster on a large DB. Both are per
|
||||
// connection and cost address space, not a fixed allocation.
|
||||
db.pragma("cache_size = -65536");
|
||||
db.pragma("mmap_size = 268435456");
|
||||
// Every event insert stores its payload through `trim_event_data(?)`
|
||||
// (`server/lib/event-payload.js`): whole-file mirrors and long output stay in
|
||||
// the transcript, not in `events.data`.
|
||||
@@ -322,7 +327,7 @@ db.exec(`
|
||||
-- read walked the rows' overflow chains (created_at sits after data).
|
||||
CREATE INDEX IF NOT EXISTS idx_events_session_created ON events(session_id, created_at);
|
||||
-- (session_id, id): a session's events in insert order, NOT a prefix of
|
||||
-- idx_events_session_type (that one is not id-ordered). Every hook's
|
||||
-- idx_events_session_type_tool (that one is not id-ordered). Every hook's
|
||||
-- duplicate guard reads a session's latest event through it; dropped, that
|
||||
-- read sorted the whole session per hook.
|
||||
CREATE INDEX IF NOT EXISTS idx_events_session ON events(session_id, id);
|
||||
@@ -335,7 +340,14 @@ db.exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_started ON sessions(started_at DESC);
|
||||
|
||||
-- Composite indexes for frequent query patterns (columns that exist at table creation time)
|
||||
CREATE INDEX IF NOT EXISTS idx_events_session_type ON events(session_id, event_type);
|
||||
-- (session_id, event_type, tool_name, created_at) covers a session's per-type,
|
||||
-- per-tool and newest-per-type reads (session stats, the import's resume
|
||||
-- point) without touching the rows: 1.2 s → 20 ms on a 29K-event session. It
|
||||
-- replaces the (session_id, event_type) index it extends, so a hook still
|
||||
-- writes the same number of index entries.
|
||||
CREATE INDEX IF NOT EXISTS idx_events_session_type_tool
|
||||
ON events(session_id, event_type, tool_name, created_at);
|
||||
DROP INDEX IF EXISTS idx_events_session_type;
|
||||
-- Subagent JSONL import dedups each tool event with
|
||||
-- "WHERE agent_id = ? AND event_type = ? AND data LIKE '%tool_use_id%'".
|
||||
-- Without an agent_id index that is a full events-table scan per tool event;
|
||||
@@ -1963,6 +1975,16 @@ const stmts = {
|
||||
web_search_requests = MAX(web_search_requests, excluded.web_search_requests),
|
||||
web_fetch_requests = MAX(web_fetch_requests, excluded.web_fetch_requests),
|
||||
code_execution_requests = MAX(code_execution_requests, excluded.code_execution_requests)
|
||||
-- Every hook re-sends every hour of the transcript; most rows did not grow.
|
||||
-- Skipping those leaves the values identical (every SET is a MAX) and
|
||||
-- writes no page, which keeps the WAL — and its checkpoints — small.
|
||||
WHERE excluded.input_tokens > input_tokens OR excluded.output_tokens > output_tokens
|
||||
OR excluded.cache_read_tokens > cache_read_tokens
|
||||
OR excluded.cache_write_tokens > cache_write_tokens
|
||||
OR excluded.cache_write_1h_tokens > cache_write_1h_tokens
|
||||
OR excluded.web_search_requests > web_search_requests
|
||||
OR excluded.web_fetch_requests > web_fetch_requests
|
||||
OR excluded.code_execution_requests > code_execution_requests
|
||||
`),
|
||||
getTokenTotals: db.prepare(`
|
||||
SELECT
|
||||
@@ -2035,22 +2057,8 @@ const stmts = {
|
||||
matchPricing: db.prepare(
|
||||
"SELECT * FROM model_pricing WHERE ? LIKE model_pattern ORDER BY LENGTH(model_pattern) DESC LIMIT 1"
|
||||
),
|
||||
toolUsageCounts: db.prepare(`
|
||||
SELECT tool_name, COUNT(*) as count
|
||||
FROM events
|
||||
WHERE tool_name IS NOT NULL
|
||||
GROUP BY tool_name
|
||||
ORDER BY count DESC
|
||||
LIMIT 20
|
||||
`),
|
||||
// Accept a timezone modifier (e.g. '-420 minutes') so GROUP BY uses local dates
|
||||
dailyEventCounts: db.prepare(`
|
||||
SELECT DATE(created_at, ?) as date, COUNT(*) as count
|
||||
FROM events
|
||||
WHERE created_at >= DATE('now', '-365 days')
|
||||
GROUP BY 1
|
||||
ORDER BY date ASC
|
||||
`),
|
||||
// Accept a timezone modifier (e.g. '-420 minutes') so GROUP BY uses local dates.
|
||||
// The events-table analytics live in scoped-stats.js's eventAggregates (read worker).
|
||||
dailySessionCounts: db.prepare(`
|
||||
SELECT DATE(started_at, ?) as date, COUNT(*) as count
|
||||
FROM sessions
|
||||
@@ -2066,16 +2074,6 @@ const stmts = {
|
||||
ORDER BY count DESC
|
||||
`),
|
||||
totalSubagentCount: db.prepare("SELECT COUNT(*) as count FROM agents WHERE type = 'subagent'"),
|
||||
eventTypeCounts: db.prepare(`
|
||||
SELECT event_type, COUNT(*) as count
|
||||
FROM events
|
||||
GROUP BY event_type
|
||||
ORDER BY count DESC
|
||||
`),
|
||||
avgEventsPerSession: db.prepare(`
|
||||
SELECT ROUND(CAST(COUNT(*) AS REAL) / MAX(1, (SELECT COUNT(*) FROM sessions)), 1) as avg
|
||||
FROM events
|
||||
`),
|
||||
|
||||
// Per-session aggregations powering the SessionOverview panel.
|
||||
sessionEventCount: db.prepare("SELECT COUNT(*) as count FROM events WHERE session_id = ?"),
|
||||
|
||||
+61
-5
@@ -51,6 +51,7 @@ if (require.main === module) require("./lib/claude-home").migrateLegacyDataDir()
|
||||
|
||||
const express = require("express");
|
||||
const cors = require("cors");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const http = require("http");
|
||||
const swaggerUi = require("swagger-ui-express");
|
||||
@@ -216,6 +217,30 @@ function startServer(app, port) {
|
||||
// so they must revalidate every load — without this the browser's
|
||||
// heuristic cache happily serves a stale index.html that references
|
||||
// asset hashes that no longer exist on disk.
|
||||
//
|
||||
// A hashed asset's `.br`/`.gz` sibling (written by the client build) goes
|
||||
// to a browser that accepts it: ~75 % fewer bytes over a network, and no
|
||||
// compression CPU here. Only a flat file name is looked up.
|
||||
const assetsDir = path.join(clientDist, "assets");
|
||||
const ENCODINGS = [
|
||||
["br", ".br", /\bbr\b/],
|
||||
["gzip", ".gz", /\bgzip\b/],
|
||||
];
|
||||
app.use("/assets", (req, res, next) => {
|
||||
res.setHeader("Vary", "Accept-Encoding");
|
||||
if (req.method !== "GET" && req.method !== "HEAD") return next();
|
||||
const name = req.path.slice(1);
|
||||
if (!/^[\w.-]+$/.test(name) || name.startsWith(".")) return next();
|
||||
const accept = String(req.headers["accept-encoding"] || "");
|
||||
for (const [encoding, ext, re] of ENCODINGS) {
|
||||
if (!re.test(accept) || !fs.existsSync(path.join(assetsDir, name + ext))) continue;
|
||||
res.setHeader("Content-Encoding", encoding);
|
||||
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
|
||||
res.type(path.extname(name)); // the original's type, not the sibling's
|
||||
return res.sendFile(name + ext, { root: assetsDir }, (err) => err && next(err));
|
||||
}
|
||||
next();
|
||||
});
|
||||
app.use(
|
||||
express.static(clientDist, {
|
||||
etag: true,
|
||||
@@ -377,6 +402,29 @@ function startBackgroundServices() {
|
||||
}
|
||||
}
|
||||
|
||||
// WAL checkpoints off the event loop. SQLite's automatic checkpoint runs
|
||||
// inside whichever COMMIT crosses 1000 pages — a hook's, on this thread —
|
||||
// and measured up to 2.7 s per commit under load. This process stops doing
|
||||
// that and checkpoints every few seconds from the read worker instead; a
|
||||
// failed checkpoint puts the automatic one back. Other processes on the same
|
||||
// file (a second dashboard, the CLI) keep their own setting. Off with
|
||||
// DASHBOARD_WAL_CHECKPOINT_MS=0.
|
||||
{
|
||||
const every = Number(process.env.DASHBOARD_WAL_CHECKPOINT_MS ?? 5000);
|
||||
if (every > 0) {
|
||||
const { db } = require("./db");
|
||||
const { runRead } = require("./lib/read-pool");
|
||||
db.pragma("wal_autocheckpoint = 0");
|
||||
const t = setInterval(() => {
|
||||
runRead("walCheckpoint").catch(() => {
|
||||
db.pragma("wal_autocheckpoint = 1000");
|
||||
clearInterval(t);
|
||||
});
|
||||
}, every);
|
||||
if (t.unref) t.unref();
|
||||
}
|
||||
}
|
||||
|
||||
// Scheduled reports (Settings → Reports). Off with DASHBOARD_REPORTS_MS=0.
|
||||
require("./lib/reports").startReportScheduler();
|
||||
|
||||
@@ -619,18 +667,26 @@ function startBackgroundServices() {
|
||||
}
|
||||
}
|
||||
// A codex/antigravity pane that exits fires no hook, so release its lane on
|
||||
// a beat instead (one `tmux has-session` per lane with a run), and end the
|
||||
// run record of any pane that is gone. Off with DASHBOARD_RUN_HEAL_MS=0.
|
||||
// a beat instead (ONE `tmux list-sessions` per beat — each tmux call is
|
||||
// synchronous and stalls every terminal's keystrokes), and end the run
|
||||
// record of any pane that is gone. Off with DASHBOARD_RUN_HEAL_MS=0.
|
||||
const HEAL_MS = Number(process.env.DASHBOARD_RUN_HEAL_MS ?? 10_000);
|
||||
if (Number.isFinite(HEAL_MS) && HEAL_MS > 0) {
|
||||
const { healAllRunIds } = require("./routes/lanes");
|
||||
const { reconcileOrphans } = require("./lib/dashboard-runs");
|
||||
const { hasSession } = require("./lib/tmux");
|
||||
const { liveSessions } = require("./lib/tmux");
|
||||
const anyRun = require("./db").db.prepare(
|
||||
`SELECT EXISTS (SELECT 1 FROM lanes WHERE run_id IS NOT NULL)
|
||||
OR EXISTS (SELECT 1 FROM dashboard_runs WHERE status IN ('running', 'spawning')) AS any`
|
||||
);
|
||||
const healTimer = setInterval(() => {
|
||||
try {
|
||||
healAllRunIds();
|
||||
if (!anyRun.get().any) return; // nothing to heal: no tmux spawn at all
|
||||
const live = liveSessions();
|
||||
if (!live) return; // tmux could not be asked: skip, never end every run
|
||||
healAllRunIds(live);
|
||||
// A pane that quit (Ctrl+C, `exit`) ends its run record too.
|
||||
reconcileOrphans(hasSession);
|
||||
reconcileOrphans((id) => live.has(id));
|
||||
} catch (err) {
|
||||
console.warn("run heal failed:", err.message);
|
||||
}
|
||||
|
||||
@@ -12,8 +12,8 @@ const TranscriptCache = require("./transcript-cache");
|
||||
|
||||
/** Write every hour of one transcript parse (MAX per hour, see the statement). */
|
||||
function writeHourly(sessionId, tokensByHour) {
|
||||
// ponytail: rewrites every hour of the session on each hook — ~1 row per
|
||||
// active hour per model, cheap; write only the newest hours if it ever shows.
|
||||
// Runs every hour of the session on each hook — ~1 row per active hour per
|
||||
// model; the statement leaves a row that did not grow untouched (no write).
|
||||
for (const t of Object.values(tokensByHour || {})) {
|
||||
stmts.upsertHourlyUsage.run(
|
||||
sessionId,
|
||||
|
||||
+8
-6
@@ -601,14 +601,15 @@ function recoverInterruptedProvisioning() {
|
||||
* and a `codex` lane (see `idx_lanes_cwd_tool`). Omitted, it matches any tool,
|
||||
* which stays correct for callers that already know they hold the lane's own
|
||||
* cwd (there's only ever one match for that exact path per tool, and this
|
||||
* caller shape doesn't care which).
|
||||
* caller shape doesn't care which). `lanes` lets a caller that resolves several
|
||||
* paths (a hook) read the lane table once.
|
||||
*/
|
||||
function resolveLaneByCwd(cwd, tool) {
|
||||
function resolveLaneByCwd(cwd, tool, lanes = null) {
|
||||
if (!cwd || typeof cwd !== "string") return null;
|
||||
// A Windows cwd ends in and nests under `\`.
|
||||
const target = cwd.replace(/[\\/]+$/, "");
|
||||
let best = null;
|
||||
for (const lane of listLanes()) {
|
||||
for (const lane of lanes || listLanes()) {
|
||||
if (tool && lane.tool !== tool) continue;
|
||||
const base = lane.cwd.replace(/[\\/]+$/, "");
|
||||
if (target === base || target.startsWith(`${base}/`) || target.startsWith(base + path.sep)) {
|
||||
@@ -654,13 +655,14 @@ function absolutePathsIn(toolInput) {
|
||||
* has no equivalent hook mechanism here) — so both lookups are pinned to the
|
||||
* `claude` lane at each path, never the `codex` one that might share it.
|
||||
*/
|
||||
function resolveLaneForWork(sessionCwd, toolInput) {
|
||||
function resolveLaneForWork(sessionCwd, toolInput, lanes = null) {
|
||||
const all = lanes || listLanes();
|
||||
let best = null;
|
||||
for (const candidate of absolutePathsIn(toolInput)) {
|
||||
const lane = resolveLaneByCwd(candidate, "claude");
|
||||
const lane = resolveLaneByCwd(candidate, "claude", all);
|
||||
if (lane && (!best || lane.cwd.length > best.cwd.length)) best = lane;
|
||||
}
|
||||
return best || resolveLaneByCwd(sessionCwd, "claude");
|
||||
return best || resolveLaneByCwd(sessionCwd, "claude", all);
|
||||
}
|
||||
|
||||
function classifyLiveness({ status, stage, ageSec }, deadSec = DEAD_SEC) {
|
||||
|
||||
@@ -81,9 +81,24 @@ function attach(ws, runId, { cols, rows }) {
|
||||
rows: rows || 24,
|
||||
});
|
||||
|
||||
// Backpressure: a slow viewer (a remote browser on a thin link) must not
|
||||
// queue a chatty pane's output in this process without bound. Past 1 MB
|
||||
// unsent the pty is paused — tmux holds the pane and redraws — and resumed
|
||||
// once the socket drains below 256 KB.
|
||||
let paused = false;
|
||||
const drained = () => {
|
||||
if (paused && ws.bufferedAmount < 256 * 1024) {
|
||||
paused = false;
|
||||
pty.resume?.();
|
||||
}
|
||||
};
|
||||
pty.onData((data) => {
|
||||
try {
|
||||
ws.send(data, { binary: true });
|
||||
ws.send(data, { binary: true }, drained);
|
||||
if (!paused && ws.bufferedAmount > 1024 * 1024) {
|
||||
paused = true;
|
||||
pty.pause?.();
|
||||
}
|
||||
} catch {
|
||||
/* client gone between data event and send — safe to ignore */
|
||||
}
|
||||
|
||||
+45
-16
@@ -2,10 +2,11 @@
|
||||
* @file Runs the dashboard's heavy read-only aggregations in a worker thread
|
||||
* on its own SQLite connection, so a slow one never blocks the event loop that
|
||||
* serves every other page, hook and websocket. Identical requests in flight are
|
||||
* shared, a job over `AGENTHUB_READ_TIMEOUT_MS` (default 60 s) is answered with
|
||||
* `EREADTIMEOUT` and its worker replaced, and `AGENTHUB_READ_WORKER=0` — or a
|
||||
* worker that cannot start — runs the job inline as before. This file is also
|
||||
* the worker's entry point.
|
||||
* shared (and, when the caller asks, reused for a short window), a job over
|
||||
* `AGENTHUB_READ_TIMEOUT_MS` (default 60 s) is answered with `EREADTIMEOUT` and
|
||||
* its worker replaced, and `AGENTHUB_READ_WORKER=0` — or a worker that cannot
|
||||
* start — runs the job inline as before. The server's periodic WAL checkpoint
|
||||
* also runs here (`walCheckpoint`). This file is also the worker's entry point.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
@@ -19,6 +20,11 @@ const JOBS = {
|
||||
{ status: a.status || null, tool: a.tool || null, range: a.range || null },
|
||||
a.sections || null
|
||||
),
|
||||
// Not a read: the worker runs it on its own writable connection (below), so
|
||||
// the checkpoint's copy into the database file never blocks the event loop.
|
||||
walCheckpoint: (conn) => conn.pragma("wal_checkpoint(PASSIVE)", { simple: false }),
|
||||
analyticsEvents: (conn, a) =>
|
||||
require("./scoped-stats").eventAggregates(conn, a.scope, a.range, a.tzModifier),
|
||||
};
|
||||
|
||||
function timeoutMs() {
|
||||
@@ -35,6 +41,7 @@ let worker = null;
|
||||
let seq = 0;
|
||||
const pending = new Map(); // id → { resolve, reject, timer, w }
|
||||
const inflight = new Map(); // job+args → Promise
|
||||
const recent = new Map(); // job+args → { at, result } for callers passing maxAgeMs
|
||||
|
||||
function spawn(dbPath) {
|
||||
const w = new Worker(__filename, { workerData: { agenthubReadWorker: true, dbPath } });
|
||||
@@ -93,37 +100,59 @@ function dispatch(job, args) {
|
||||
|
||||
/**
|
||||
* Run a named read job off the event loop. Concurrent calls with the same job
|
||||
* and args share one run.
|
||||
* and args share one run; with `maxAgeMs`, a result that young is reused too,
|
||||
* so N open dashboards cost one query per window instead of N. Args are part
|
||||
* of the key, so a result is only reused for the very same query.
|
||||
*
|
||||
* @param {keyof JOBS} job
|
||||
* @param {object} [args] structured-cloneable
|
||||
* @param {{maxAgeMs?: number}} [opts]
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
function runRead(job, args = {}) {
|
||||
function runRead(job, args = {}, { maxAgeMs = 0 } = {}) {
|
||||
if (!JOBS[job]) return Promise.reject(codedError(`unknown read job ${job}`, "EBADJOB"));
|
||||
const key = `${job}:${JSON.stringify(args)}`;
|
||||
const now = Date.now();
|
||||
const fresh = recent.get(key);
|
||||
if (fresh && now - fresh.at < maxAgeMs) return Promise.resolve(fresh.result);
|
||||
const hit = inflight.get(key);
|
||||
if (hit) return hit;
|
||||
const p = dispatch(job, args).finally(() => inflight.delete(key));
|
||||
const p = dispatch(job, args)
|
||||
.then((result) => {
|
||||
if (maxAgeMs > 0) {
|
||||
// ponytail: drop-expired-on-write keeps this bounded by the keys used
|
||||
// within one window; an LRU if a caller ever varies args per request.
|
||||
for (const [k, v] of recent) if (now - v.at > 60_000) recent.delete(k);
|
||||
recent.set(key, { at: Date.now(), result });
|
||||
}
|
||||
return result;
|
||||
})
|
||||
.finally(() => inflight.delete(key));
|
||||
inflight.set(key, p);
|
||||
return p;
|
||||
}
|
||||
|
||||
if (!isMainThread && workerData?.agenthubReadWorker) {
|
||||
// Same driver order as server/db.js: better-sqlite3, else node:sqlite.
|
||||
let conn;
|
||||
try {
|
||||
const Database = require("better-sqlite3");
|
||||
conn = new Database(workerData.dbPath);
|
||||
} catch {
|
||||
const Database = require("../compat-sqlite");
|
||||
conn = new Database(workerData.dbPath);
|
||||
}
|
||||
const open = () => {
|
||||
try {
|
||||
const Database = require("better-sqlite3");
|
||||
return new Database(workerData.dbPath);
|
||||
} catch {
|
||||
const Database = require("../compat-sqlite");
|
||||
return new Database(workerData.dbPath);
|
||||
}
|
||||
};
|
||||
const conn = open();
|
||||
let writer = null; // walCheckpoint's connection, opened on first use
|
||||
conn.pragma("busy_timeout = 5000");
|
||||
conn.pragma("query_only = ON"); // this connection can never write
|
||||
conn.pragma("cache_size = -65536"); // same read tuning as server/db.js
|
||||
conn.pragma("mmap_size = 268435456");
|
||||
parentPort.on("message", ({ id, job, args }) => {
|
||||
try {
|
||||
parentPort.postMessage({ id, result: JOBS[job](conn, args) });
|
||||
const c = job === "walCheckpoint" ? (writer ??= open()) : conn;
|
||||
parentPort.postMessage({ id, result: JOBS[job](c, args) });
|
||||
} catch (err) {
|
||||
parentPort.postMessage({ id, error: { message: err.message, code: err.code } });
|
||||
}
|
||||
|
||||
@@ -197,7 +197,49 @@ function avgEventsPerSession(db, scope, range) {
|
||||
.get(...scope.params, ...s.params, ...scope.params, ...e.params);
|
||||
}
|
||||
|
||||
/**
|
||||
* The analytics numbers that scan `events` (tool usage, daily events, event
|
||||
* types, events per session) for a scope or none. Takes the connection as an
|
||||
* argument so the read worker can run it (`analyticsEvents` in read-pool.js).
|
||||
*/
|
||||
function eventAggregates(db, scope, range, tzModifier) {
|
||||
if (scope) {
|
||||
return {
|
||||
toolUsage: toolUsageCounts(db, scope, range),
|
||||
dailyEvents: dailyEventCounts(db, scope, tzModifier),
|
||||
eventTypes: eventTypeCounts(db, scope, range),
|
||||
avgEvents: avgEventsPerSession(db, scope, range),
|
||||
};
|
||||
}
|
||||
return {
|
||||
toolUsage: db
|
||||
.prepare(
|
||||
`SELECT tool_name, COUNT(*) as count FROM events WHERE tool_name IS NOT NULL
|
||||
GROUP BY tool_name ORDER BY count DESC LIMIT 20`
|
||||
)
|
||||
.all(),
|
||||
dailyEvents: db
|
||||
.prepare(
|
||||
`SELECT DATE(created_at, ?) as date, COUNT(*) as count FROM events
|
||||
WHERE created_at >= DATE('now', '-365 days') GROUP BY 1 ORDER BY date ASC`
|
||||
)
|
||||
.all(tzModifier),
|
||||
eventTypes: db
|
||||
.prepare(
|
||||
"SELECT event_type, COUNT(*) as count FROM events GROUP BY event_type ORDER BY count DESC"
|
||||
)
|
||||
.all(),
|
||||
avgEvents: db
|
||||
.prepare(
|
||||
`SELECT ROUND(CAST(COUNT(*) AS REAL) / MAX(1, (SELECT COUNT(*) FROM sessions)), 1) as avg
|
||||
FROM events`
|
||||
)
|
||||
.get(),
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
eventAggregates,
|
||||
statsOverview,
|
||||
agentStatusCounts,
|
||||
sessionStatusCounts,
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const { execFileSync } = require("node:child_process");
|
||||
const { execFile, execFileSync } = require("node:child_process");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const { isInsideContainer } = require("../../scripts/install-hooks");
|
||||
@@ -63,21 +63,45 @@ function probeDisabledByEnv() {
|
||||
* with an empty set genuinely means no claude process is running.
|
||||
*/
|
||||
function probeLiveCwds() {
|
||||
if (probeDisabledByEnv()) return UNAVAILABLE();
|
||||
if (process.platform === "win32") return UNAVAILABLE();
|
||||
if (isInsideContainer()) return UNAVAILABLE();
|
||||
|
||||
if (probeBlocked()) return UNAVAILABLE();
|
||||
let psOut;
|
||||
try {
|
||||
psOut = execImpl("ps", ["-Ao", "pid=,args="], {
|
||||
encoding: "utf8",
|
||||
timeout: 5_000,
|
||||
maxBuffer: 16 * 1024 * 1024,
|
||||
});
|
||||
psOut = execImpl("ps", PS_ARGS, PS_OPTS);
|
||||
} catch {
|
||||
return UNAVAILABLE();
|
||||
}
|
||||
return cwdsFromPs(psOut);
|
||||
}
|
||||
|
||||
/**
|
||||
* `probeLiveCwds` with `ps` run asynchronously — what the watchdog's 15 s
|
||||
* beat uses, so the spawn (24–300 ms inside a large server process) never
|
||||
* blocks the event loop. Same answer shape; resolves, never rejects.
|
||||
*
|
||||
* @returns {Promise<{ available: boolean, cwds: Set<string> }>}
|
||||
*/
|
||||
function probeLiveCwdsAsync() {
|
||||
if (probeBlocked()) return Promise.resolve(UNAVAILABLE());
|
||||
return new Promise((resolve) => {
|
||||
execFile("ps", PS_ARGS, PS_OPTS, (err, out) => {
|
||||
try {
|
||||
resolve(err ? UNAVAILABLE() : cwdsFromPs(out));
|
||||
} catch {
|
||||
resolve(UNAVAILABLE());
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const PS_ARGS = ["-Ao", "pid=,args="];
|
||||
const PS_OPTS = { encoding: "utf8", timeout: 5_000, maxBuffer: 16 * 1024 * 1024 };
|
||||
|
||||
function probeBlocked() {
|
||||
return probeDisabledByEnv() || process.platform === "win32" || isInsideContainer();
|
||||
}
|
||||
|
||||
/** The cwds of the `claude` processes in a `ps -Ao pid=,args=` listing. */
|
||||
function cwdsFromPs(psOut) {
|
||||
const pids = [];
|
||||
for (const line of psOut.split("\n")) {
|
||||
const m = line.match(/^\s*(\d+)\s+(.*)$/);
|
||||
@@ -120,4 +144,4 @@ function probeLiveCwds() {
|
||||
return { available: true, cwds };
|
||||
}
|
||||
|
||||
module.exports = { probeLiveCwds, isClaudeCommand, __setExecImpl };
|
||||
module.exports = { probeLiveCwds, probeLiveCwdsAsync, isClaudeCommand, __setExecImpl };
|
||||
|
||||
+77
-16
@@ -34,10 +34,35 @@ let exactTargets = null;
|
||||
function __setExecImpl(fn, { exact = true } = {}) {
|
||||
execImpl = fn;
|
||||
exactTargets = exact;
|
||||
listed = null;
|
||||
}
|
||||
function __reset() {
|
||||
execImpl = (args) => execFileSync("tmux", args, EXEC_OPTS);
|
||||
exactTargets = null;
|
||||
listed = null;
|
||||
}
|
||||
|
||||
// The `list-sessions` answer, shared for LIST_TTL_MS. Every open dashboard
|
||||
// polls GET /api/run, and each synchronous spawn forks this whole process —
|
||||
// measured 2,247 calls, 60 s of a 90 s run blocked, at 10 browsers. A session
|
||||
// this process creates or kills clears it, so only a pane that exits on its
|
||||
// own can read as live for up to a second. "No server" (exit 1) is an answer
|
||||
// too and is shared; any other failure is not.
|
||||
const LIST_TTL_MS = 1000;
|
||||
let listed = null; // { at, out } | { at, err }
|
||||
function listOutput() {
|
||||
if (listed && Date.now() - listed.at < LIST_TTL_MS) {
|
||||
if (listed.err) throw listed.err;
|
||||
return listed.out;
|
||||
}
|
||||
try {
|
||||
const out = String(execImpl(["list-sessions", "-F", "#{session_name}"]));
|
||||
listed = { at: Date.now(), out };
|
||||
return out;
|
||||
} catch (err) {
|
||||
listed = err.status === 1 || err.code === "ENOENT" ? { at: Date.now(), err } : null;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -117,6 +142,7 @@ function envFlags(env) {
|
||||
function newSession({ name, cwd, argv, env }) {
|
||||
// No argv = tmux's own default shell (a Windows Terminal pane).
|
||||
const cmd = argv.length ? ["--", ...argv] : [];
|
||||
listed = null;
|
||||
execImpl(["new-session", "-d", "-s", name, "-c", cwd, ...envFlags(env), ...cmd]);
|
||||
try {
|
||||
enableMouse(name);
|
||||
@@ -144,25 +170,37 @@ function newSession({ name, cwd, argv, env }) {
|
||||
// The status bar goes off here too: the dashboard's tab bar already names the
|
||||
// pane, and tmux's green line only eats a row of the terminal.
|
||||
function enableMouse(name) {
|
||||
execImpl(["set-option", "-t", pane(name), "mouse", "on"]);
|
||||
execImpl(["set-option", "-t", pane(name), "status", "off"]);
|
||||
// tmux runs `;`-separated commands from ONE argv (each tmux call is a
|
||||
// synchronous spawn on the event loop), stopping at the first that fails —
|
||||
// so the options every tmux knows go first, in their own call. psmux (no
|
||||
// `=name` targets) is not known to chain, so it gets one call per option.
|
||||
const run = (...cmds) => {
|
||||
if (exact()) return execImpl(cmds.flatMap((c, i) => (i ? [";", ...c] : c)));
|
||||
for (const c of cmds) execImpl(c);
|
||||
};
|
||||
run(
|
||||
["set-option", "-t", pane(name), "mouse", "on"],
|
||||
["set-option", "-t", pane(name), "status", "off"]
|
||||
);
|
||||
// A draggable scrollbar beside the pane (mouse mode makes it drag). Only a
|
||||
// tmux SERVER of 3.7+ knows the option; an older one refuses it, which is
|
||||
// fine — the pane just has none (`/agenthub-doctor` says how to upgrade).
|
||||
try {
|
||||
execImpl(["set-option", "-t", pane(name), "pane-scrollbars", "on"]);
|
||||
// tmux's default (`fg=white,bg=black,width=1`) is a one-column track in
|
||||
// ANSI black — the terminal theme's border colour, almost the background —
|
||||
// so it reads as no scrollbar at all. Bright slider. ONE column: tmux 3.7c
|
||||
// reserves `width` columns but paints only the first, so a second one is
|
||||
// never cleared and shows stale cells — a ghost second scrollbar.
|
||||
execImpl([
|
||||
"set-option",
|
||||
"-t",
|
||||
pane(name),
|
||||
"pane-scrollbars-style",
|
||||
"fg=brightwhite,bg=black,width=1,pad=0",
|
||||
]);
|
||||
run(
|
||||
["set-option", "-t", pane(name), "pane-scrollbars", "on"],
|
||||
// tmux's default (`fg=white,bg=black,width=1`) is a one-column track in
|
||||
// ANSI black — the terminal theme's border colour, almost the background —
|
||||
// so it reads as no scrollbar at all. Bright slider. ONE column: tmux 3.7c
|
||||
// reserves `width` columns but paints only the first, so a second one is
|
||||
// never cleared and shows stale cells — a ghost second scrollbar.
|
||||
[
|
||||
"set-option",
|
||||
"-t",
|
||||
pane(name),
|
||||
"pane-scrollbars-style",
|
||||
"fg=brightwhite,bg=black,width=1,pad=0",
|
||||
]
|
||||
);
|
||||
} catch {
|
||||
/* tmux < 3.7 */
|
||||
}
|
||||
@@ -239,6 +277,7 @@ function pasteText(name, text) {
|
||||
|
||||
/** Idempotent — a session that's already gone is not an error. */
|
||||
function killSession(name) {
|
||||
listed = null;
|
||||
try {
|
||||
execImpl(["kill-session", "-t", session(name)]);
|
||||
} catch {
|
||||
@@ -250,7 +289,7 @@ function killSession(name) {
|
||||
function listSessions(prefix) {
|
||||
let out;
|
||||
try {
|
||||
out = execImpl(["list-sessions", "-F", "#{session_name}"]);
|
||||
out = listOutput();
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
@@ -260,6 +299,27 @@ function listSessions(prefix) {
|
||||
.filter((s) => s && s.startsWith(prefix));
|
||||
}
|
||||
|
||||
/**
|
||||
* Every live session name from ONE `list-sessions` — what a poll asks instead
|
||||
* of a synchronous has-session per name, each of which blocks the event loop
|
||||
* (and so every terminal keystroke) for a whole tmux spawn. Empty when no
|
||||
* server runs (tmux exits 1) or tmux is not installed; null when the call
|
||||
* itself failed (EAGAIN/ENOMEM under memory pressure), which proves nothing
|
||||
* about the panes — a caller must not read that as "every pane is gone".
|
||||
*/
|
||||
function liveSessions() {
|
||||
try {
|
||||
return new Set(
|
||||
listOutput()
|
||||
.split("\n")
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
);
|
||||
} catch (err) {
|
||||
return err.status === 1 || err.code === "ENOENT" ? new Set() : null;
|
||||
}
|
||||
}
|
||||
|
||||
function isTmuxAvailable() {
|
||||
return clientVersion() !== null;
|
||||
}
|
||||
@@ -297,6 +357,7 @@ module.exports = {
|
||||
pasteText,
|
||||
killSession,
|
||||
listSessions,
|
||||
liveSessions,
|
||||
isTmuxAvailable,
|
||||
clientVersion,
|
||||
serverVersion,
|
||||
|
||||
@@ -312,9 +312,10 @@ class TranscriptCache {
|
||||
pos += got;
|
||||
|
||||
let lineStart = 0;
|
||||
for (let i = 0; i < got; i++) {
|
||||
if (buf[i] !== 0x0a) continue;
|
||||
|
||||
// indexOf finds each newline natively — a JS byte loop was ~100 ms of
|
||||
// a 76 MB transcript's cold read on the event loop.
|
||||
const view = buf.subarray(0, got);
|
||||
for (let i = view.indexOf(0x0a); i !== -1; i = view.indexOf(0x0a, i + 1)) {
|
||||
let line;
|
||||
if (pendingLen) {
|
||||
const need = pendingLen + (i - lineStart);
|
||||
|
||||
+20
-10
@@ -14,6 +14,7 @@ const {
|
||||
BAD_RANGE,
|
||||
} = require("../lib/source-filter");
|
||||
const scoped = require("../lib/scoped-stats");
|
||||
const { runRead } = require("../lib/read-pool");
|
||||
|
||||
const { calculateCost, dailyTokenRows, costWhere } = require("./pricing");
|
||||
|
||||
@@ -34,12 +35,12 @@ const USAGE_TOKEN_COLS = {
|
||||
* With a range, counts follow it and tokens/cost come from the cost rows of the
|
||||
* days in it (`token_usage` has no date); the daily charts keep 365 days.
|
||||
*/
|
||||
function computeAnalytics({ scope = null, range = null, tzModifier = "+0 minutes" } = {}) {
|
||||
function computeAnalytics(
|
||||
{ scope = null, range = null, tzModifier = "+0 minutes" } = {},
|
||||
events = scoped.eventAggregates(db, scope || (range ? ALL : null), range, tzModifier)
|
||||
) {
|
||||
const sc = scope || (range ? ALL : null);
|
||||
const toolUsage = sc ? scoped.toolUsageCounts(db, sc, range) : stmts.toolUsageCounts.all();
|
||||
const dailyEvents = sc
|
||||
? scoped.dailyEventCounts(db, sc, tzModifier)
|
||||
: stmts.dailyEventCounts.all(tzModifier);
|
||||
const { toolUsage, dailyEvents, eventTypes, avgEvents } = events;
|
||||
const dailySessions = sc
|
||||
? scoped.dailySessionCounts(db, sc, tzModifier)
|
||||
: stmts.dailySessionCounts.all(tzModifier);
|
||||
@@ -56,10 +57,6 @@ function computeAnalytics({ scope = null, range = null, tzModifier = "+0 minutes
|
||||
const totalSubagents = sc
|
||||
? scoped.totalSubagentCount(db, sc, range)
|
||||
: stmts.totalSubagentCount.get();
|
||||
const eventTypes = sc ? scoped.eventTypeCounts(db, sc, range) : stmts.eventTypeCounts.all();
|
||||
const avgEvents = sc
|
||||
? scoped.avgEventsPerSession(db, sc, range)
|
||||
: stmts.avgEventsPerSession.get();
|
||||
|
||||
// Total cost exactly as GET /api/pricing/cost computes it (baselines, the
|
||||
// per-day rate, the same scope and range), so the two numbers always agree.
|
||||
@@ -108,7 +105,20 @@ router.get("/", (req, res) => {
|
||||
if (parseTool(req) === false) return res.status(400).json(BAD_TOOL);
|
||||
const range = parseRange(req);
|
||||
if (range === false) return res.status(400).json(BAD_RANGE);
|
||||
res.json(computeAnalytics({ scope: parseScope(req), range, tzModifier }));
|
||||
const scope = parseScope(req);
|
||||
// The events scans run in the read worker (a 365-day daily count is ~0.5 s
|
||||
// on a large DB), and a 10 s memo lets every open dashboard share one run.
|
||||
runRead(
|
||||
"analyticsEvents",
|
||||
{ scope: scope || (range ? ALL : null), range, tzModifier },
|
||||
{ maxAgeMs: 10_000 }
|
||||
)
|
||||
.then((events) => res.json(computeAnalytics({ scope, range, tzModifier }, events)))
|
||||
.catch((err) =>
|
||||
res
|
||||
.status(err.code === "EREADTIMEOUT" ? 503 : 500)
|
||||
.json({ error: { code: err.code, message: err.message } })
|
||||
);
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
+110
-40
@@ -7,7 +7,15 @@ const { Router } = require("express");
|
||||
const { v4: uuidv4 } = require("uuid");
|
||||
const dbModule = require("../db");
|
||||
const { stmts, db } = dbModule;
|
||||
const { broadcast } = require("../websocket");
|
||||
const { broadcast: sendNow } = require("../websocket");
|
||||
|
||||
// Frames emitted while a hook's transaction is open wait in `held` for its
|
||||
// commit (see processEvent); everywhere else they go out at once.
|
||||
let held = null;
|
||||
function broadcast(type, data) {
|
||||
if (held) held.push([type, data]);
|
||||
else sendNow(type, data);
|
||||
}
|
||||
const TranscriptCache = require("../lib/transcript-cache");
|
||||
const { writeHourly } = require("../lib/hourly-usage");
|
||||
const { scanAndImportSubagents } = require("../../scripts/import-history");
|
||||
@@ -173,13 +181,16 @@ const LANE_DONE_HOOKS = new Set(["Stop", "SessionEnd"]);
|
||||
* running/idle, so without this an adopted lane read "idle" for the entire
|
||||
* time Claude was working in it.
|
||||
*/
|
||||
function touchLaneFromHook(hookType, data, tool = "claude") {
|
||||
function touchLaneFromHook(hookType, data, tool = "claude", runId = null) {
|
||||
try {
|
||||
if (!data || !data.cwd) return;
|
||||
// One read of the lane table for every path this hook resolves.
|
||||
// ponytail: a scan per hook — fine at dozens of lanes; index by cwd prefix if lane counts grow.
|
||||
const allLanes = lanesLib.listLanes();
|
||||
// Pin to the lane of the CLI that sent the hook — a Claude hook never
|
||||
// touches the codex lane sharing its directory, nor a Codex hook the
|
||||
// claude one.
|
||||
const lane = lanesLib.resolveLaneByCwd(data.cwd, tool);
|
||||
const lane = lanesLib.resolveLaneByCwd(data.cwd, tool, allLanes);
|
||||
if (!lane) return;
|
||||
|
||||
// Infer the lane's stage from this one tool event, best-effort. A real
|
||||
@@ -203,7 +214,7 @@ function touchLaneFromHook(hookType, data, tool = "claude") {
|
||||
// Credit the lane whose files/directory the tool actually touched, which
|
||||
// is not always the session's lane - see resolveLaneForWork. Bookkeeping
|
||||
// below still uses `lane`, the session's own.
|
||||
const workLane = lanesLib.resolveLaneForWork(data.cwd, data.tool_input) || lane;
|
||||
const workLane = lanesLib.resolveLaneForWork(data.cwd, data.tool_input, allLanes) || lane;
|
||||
const detection = detect(getPipeline(workLane.pipeline), {
|
||||
tool_name: data.tool_name,
|
||||
tool_input: data.tool_input,
|
||||
@@ -222,7 +233,14 @@ function touchLaneFromHook(hookType, data, tool = "claude") {
|
||||
// resuming, so it neither clears needs_action nor moves the lane.
|
||||
const childEvent = tool === "codex" && data._codexChild === true;
|
||||
const idleNudge = hookType === "Notification" && IDLE_NUDGE_RE.test(data.message || "");
|
||||
if (data.session_id && lane.session_id !== data.session_id) patch.session_id = data.session_id;
|
||||
// The lane's session follows its slot-0 pane (or a session outside the
|
||||
// dashboard), never a split pane's: only slot 0 is the lane's run, and two
|
||||
// panes of one workspace would otherwise flip session_id — and broadcast
|
||||
// the lane to every browser — on every hook.
|
||||
const splitPane = typeof runId === "string" && /^agenthub-lane-\d+-[1-9]$/.test(runId);
|
||||
if (data.session_id && lane.session_id !== data.session_id && !splitPane) {
|
||||
patch.session_id = data.session_id;
|
||||
}
|
||||
if (hookType === "Notification" && !idleNudge) {
|
||||
patch.needs_action = data.message || "needs you";
|
||||
patch.needs_action_session = data.session_id || null;
|
||||
@@ -260,6 +278,14 @@ function touchLaneFromHook(hookType, data, tool = "claude") {
|
||||
}
|
||||
|
||||
const setSessionTool = db.prepare("UPDATE sessions SET tool = ? WHERE id = ?");
|
||||
// What processEvent dedupes the transcript's API errors and turn durations
|
||||
// against — one read per hook, not one per transcript entry.
|
||||
const apiErrorSummariesStmt = db.prepare(
|
||||
"SELECT summary FROM events WHERE session_id = ? AND event_type = 'APIError'"
|
||||
);
|
||||
const turnDurationStampsStmt = db.prepare(
|
||||
"SELECT created_at FROM events WHERE session_id = ? AND event_type = 'TurnDuration'"
|
||||
);
|
||||
|
||||
/** The session's `<id>-main` agent, created and broadcast. */
|
||||
function createMainAgent(session) {
|
||||
@@ -448,7 +474,7 @@ function applyFirstUserDescriptor(sessionId, result) {
|
||||
if (refreshedAgent) broadcast("agent_updated", refreshedAgent);
|
||||
}
|
||||
|
||||
const processEvent = db.transaction((hookType, data, tool = "claude") => {
|
||||
const processEventTx = db.transaction((hookType, data, tool = "claude") => {
|
||||
const sessionId = data.session_id;
|
||||
if (!sessionId) return null;
|
||||
|
||||
@@ -1017,16 +1043,13 @@ const processEvent = db.transaction((hookType, data, tool = "claude") => {
|
||||
// Register API errors from transcript (quota limits, rate limits, overloaded, etc.)
|
||||
if (result.errors) {
|
||||
let newErrorRecorded = false;
|
||||
// Deduplicate against the errors already recorded, read ONCE per hook:
|
||||
// `result.errors` is the transcript's whole history, not just new ones.
|
||||
const recorded = new Set(apiErrorSummariesStmt.all(sessionId).map((r) => r.summary));
|
||||
for (const apiErr of result.errors) {
|
||||
// Deduplicate: check if we already recorded this error (same type+message+timestamp)
|
||||
const errKey = `${apiErr.type}:${apiErr.timestamp || ""}`;
|
||||
const existing = db
|
||||
.prepare(
|
||||
`SELECT 1 FROM events WHERE session_id = ? AND event_type = 'APIError'
|
||||
AND summary = ? LIMIT 1`
|
||||
)
|
||||
.get(sessionId, `${apiErr.type}: ${apiErr.message}`);
|
||||
if (existing) continue;
|
||||
const errSummary = `${apiErr.type}: ${apiErr.message}`;
|
||||
if (recorded.has(errSummary)) continue;
|
||||
recorded.add(errSummary);
|
||||
|
||||
stmts.insertEvent.run(
|
||||
sessionId,
|
||||
@@ -1096,15 +1119,15 @@ const processEvent = db.transaction((hookType, data, tool = "claude") => {
|
||||
|
||||
// Register turn duration events from transcript
|
||||
if (result.turnDurations) {
|
||||
// `turnDurations` is every turn in the transcript (up to 1000), on
|
||||
// every hook: dedupe against ONE read of the recorded timestamps (a
|
||||
// covering-index scan) instead of a query per turn — 23 ms per hook on
|
||||
// a 763-turn session before.
|
||||
const recorded = new Set(turnDurationStampsStmt.all(sessionId).map((r) => r.created_at));
|
||||
for (const td of result.turnDurations) {
|
||||
const tdTs = td.timestamp || new Date().toISOString();
|
||||
// Deduplicate by checking if we already have this turn duration event
|
||||
const existing = db
|
||||
.prepare(
|
||||
"SELECT 1 FROM events WHERE session_id = ? AND event_type = 'TurnDuration' AND created_at = ? LIMIT 1"
|
||||
)
|
||||
.get(sessionId, tdTs);
|
||||
if (existing) continue;
|
||||
if (recorded.has(tdTs)) continue;
|
||||
recorded.add(tdTs);
|
||||
|
||||
const tdSummary = `Turn completed in ${(td.durationMs / 1000).toFixed(1)}s`;
|
||||
// Stamped with the TRANSCRIPT's timestamp, not NOW — that is what the
|
||||
@@ -1168,7 +1191,7 @@ const processEvent = db.transaction((hookType, data, tool = "claude") => {
|
||||
// Bump session updated_at on every event
|
||||
stmts.touchSession.run(sessionId);
|
||||
|
||||
stmts.insertEvent.run(
|
||||
const inserted = stmts.insertEvent.run(
|
||||
sessionId,
|
||||
agentId,
|
||||
eventType,
|
||||
@@ -1179,6 +1202,8 @@ const processEvent = db.transaction((hookType, data, tool = "claude") => {
|
||||
);
|
||||
|
||||
const event = {
|
||||
// The row id (additive): lets a client drop a frame it already holds.
|
||||
id: Number(inserted.lastInsertRowid),
|
||||
session_id: sessionId,
|
||||
agent_id: agentId,
|
||||
event_type: eventType,
|
||||
@@ -1190,6 +1215,31 @@ const processEvent = db.transaction((hookType, data, tool = "claude") => {
|
||||
return event;
|
||||
});
|
||||
|
||||
/**
|
||||
* One hook's writes in one transaction, its WebSocket frames sent only once
|
||||
* that transaction COMMITTED — in order, in the same tick. A frame sent from
|
||||
* inside it described a row a later throw could still roll back.
|
||||
*/
|
||||
function processEvent(hookType, data, tool) {
|
||||
return holdFrames(() => processEventTx(hookType, data, tool));
|
||||
}
|
||||
|
||||
/** Run `fn` with frames held, then send them if it returned (nested: the
|
||||
* outermost call sends). A throw drops them. */
|
||||
function holdFrames(fn) {
|
||||
if (held) return fn();
|
||||
held = [];
|
||||
let frames = null;
|
||||
try {
|
||||
const out = fn();
|
||||
frames = held;
|
||||
return out;
|
||||
} finally {
|
||||
held = null;
|
||||
if (frames) for (const [type, payload] of frames) sendNow(type, payload);
|
||||
}
|
||||
}
|
||||
|
||||
// A Codex sub-agent thread's own lifecycle is not the user's session's: its
|
||||
// Stop is not the end of the user's turn, nor its SessionStart a new session.
|
||||
const CODEX_CHILD_DROPPED = new Set([
|
||||
@@ -1414,26 +1464,38 @@ function ingestHook(body, pushSource = null) {
|
||||
transcriptCache.extract(data.transcript_path);
|
||||
}
|
||||
|
||||
const result = processEvent(hook_type, data, tool);
|
||||
// The hook's frames also wait for bindRunSession: in server mode a member
|
||||
// is sent only frames of sessions they own (broadcastAudience), and a new
|
||||
// Codex/agy session has no workspace — no owner — until that stamp. They are
|
||||
// dropped only when processEvent threw (nothing was committed).
|
||||
held = [];
|
||||
let result = null;
|
||||
try {
|
||||
result = processEvent(hook_type, data, tool);
|
||||
if (result) {
|
||||
if (pushSource) {
|
||||
// Tagged in the same tick processEvent created it, so no local liveness
|
||||
// sweep ever sees it as this machine's.
|
||||
if (pushedNew) {
|
||||
stmts.setSessionSource.run(pushSource, data.session_id);
|
||||
broadcast("session_updated", stmts.getSession.get(data.session_id));
|
||||
}
|
||||
} else {
|
||||
touchLaneFromHook(hook_type, data, tool, body.run_id);
|
||||
bindRunSession(body.run_id, data.session_id, hook_type, data.source, tool);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
const frames = held;
|
||||
held = null;
|
||||
if (result) for (const [type, payload] of frames) sendNow(type, payload);
|
||||
}
|
||||
if (!result) {
|
||||
return {
|
||||
status: 400,
|
||||
body: { error: { code: "MISSING_SESSION", message: "session_id is required in data" } },
|
||||
};
|
||||
}
|
||||
|
||||
if (pushSource) {
|
||||
// Tagged in the same tick processEvent created it, so no local liveness
|
||||
// sweep ever sees it as this machine's.
|
||||
if (pushedNew) {
|
||||
stmts.setSessionSource.run(pushSource, data.session_id);
|
||||
broadcast("session_updated", stmts.getSession.get(data.session_id));
|
||||
}
|
||||
} else {
|
||||
// ponytail: full lane scan per hook — fine at dozens of lanes; index by cwd prefix if lane counts grow.
|
||||
touchLaneFromHook(hook_type, data, tool);
|
||||
bindRunSession(body.run_id, data.session_id, hook_type, data.source, tool);
|
||||
}
|
||||
return { status: 200, body: { ok: true, event: result }, result, hook_type, data, tool };
|
||||
}
|
||||
|
||||
@@ -1880,7 +1942,8 @@ function watchdogCheck() {
|
||||
// sessions never flicker out on a transient mismatch. A false
|
||||
// completion self-heals anyway: the next hook event reactivates the
|
||||
// session via the existing needsReactivation path.
|
||||
livenessReap();
|
||||
// The probe's `ps` runs asynchronously here (not on the event loop).
|
||||
return livenessReap({ asyncProbe: true });
|
||||
} catch (err) {
|
||||
// Watchdog is best-effort — log but never crash the server
|
||||
console.warn("[WATCHDOG] Error during check:", err?.message || err);
|
||||
@@ -1901,7 +1964,7 @@ function watchdogCheck() {
|
||||
* existing reactivation path. Watchdog ticks keep the gate, where it still
|
||||
* guards long-running steady-state work against transient probe misses.
|
||||
*/
|
||||
function livenessReap({ ignoreIdleGate = false } = {}) {
|
||||
function livenessReap({ ignoreIdleGate = false, asyncProbe = false, probe = null } = {}) {
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
@@ -1924,7 +1987,14 @@ function livenessReap({ ignoreIdleGate = false } = {}) {
|
||||
.all();
|
||||
if (activeSessions.length === 0) return; // nothing to check — skip the ps/lsof cost
|
||||
|
||||
const probe = liveness.probeLiveCwds();
|
||||
if (asyncProbe) {
|
||||
// Re-enters with the answer; the session list is read again then, fresh.
|
||||
return liveness
|
||||
.probeLiveCwdsAsync()
|
||||
.then((p) => livenessReap({ ignoreIdleGate, probe: p }))
|
||||
.catch((err) => console.warn("[WATCHDOG] Liveness reap failed:", err?.message || err));
|
||||
}
|
||||
if (!probe) probe = liveness.probeLiveCwds();
|
||||
if (!probe.available) return;
|
||||
const now = Date.now();
|
||||
for (const sess of activeSessions) {
|
||||
|
||||
+19
-9
@@ -28,6 +28,7 @@ const laneFeatures = require("../lib/lane-features");
|
||||
const proofLib = require("../lib/proof");
|
||||
const { broadcast } = require("../websocket");
|
||||
const runs = require("../lib/pty-run");
|
||||
const tmux = require("../lib/tmux");
|
||||
const { resumeProxy } = require("../lib/proxy-apply");
|
||||
const { sameOriginGuard } = require("./run");
|
||||
const { writeLaneFile } = require("../lib/lane-file-write");
|
||||
@@ -115,10 +116,14 @@ function lastEventAge(lane) {
|
||||
* it, exactly like the old push-based handler did, just pulled instead of
|
||||
* pushed.
|
||||
*/
|
||||
function healRunId(lane) {
|
||||
function healRunId(lane, live = null) {
|
||||
if (!lane.run_id) return lane;
|
||||
const run = runs.getRun(lane.run_id);
|
||||
if (run && run.status === "running") return lane;
|
||||
if (live) {
|
||||
if (live.has(lane.run_id)) return lane;
|
||||
} else {
|
||||
const run = runs.getRun(lane.run_id);
|
||||
if (run && run.status === "running") return lane;
|
||||
}
|
||||
lanesLib.updateLane(lane.id, { run_id: null, status: "idle" });
|
||||
broadcastLane(lane.id);
|
||||
return lanesLib.getLane(lane.id);
|
||||
@@ -128,10 +133,11 @@ function healRunId(lane) {
|
||||
* Heal every lane at once. A claude pane that exits fires a hook, which
|
||||
* broadcasts the lane and so re-reads it; a codex or antigravity pane fires
|
||||
* nothing, so without this sweep its lane read "running" until something
|
||||
* else happened to fetch it.
|
||||
* else happened to fetch it. `live` (a `tmux.liveSessions()` set) answers
|
||||
* every lane from one tmux call instead of a has-session per lane.
|
||||
*/
|
||||
function healAllRunIds() {
|
||||
for (const lane of lanesLib.listLanes()) if (lane.run_id) healRunId(lane);
|
||||
function healAllRunIds(live = null) {
|
||||
for (const lane of lanesLib.listLanes()) if (lane.run_id) healRunId(lane, live);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -171,8 +177,8 @@ function broadcastForeignLaneChanges() {
|
||||
return out;
|
||||
}
|
||||
|
||||
function payload(lane) {
|
||||
const healed = healRunId(lane);
|
||||
function payload(lane, live = null) {
|
||||
const healed = healRunId(lane, live);
|
||||
return lanesLib.lanePayload(healed, lastEventAge(healed));
|
||||
}
|
||||
|
||||
@@ -195,7 +201,11 @@ function broadcastLane(id) {
|
||||
}
|
||||
|
||||
router.get("/", (_req, res) => {
|
||||
const lanes = lanesLib.listLanes().map(payload);
|
||||
const rows = lanesLib.listLanes();
|
||||
// ONE list-sessions answers every lane's run, instead of a synchronous
|
||||
// has-session per lane (null when tmux could not be asked: per-lane then).
|
||||
const live = rows.some((l) => l.run_id) ? tmux.liveSessions() : null;
|
||||
const lanes = rows.map((l) => payload(l, live));
|
||||
res.json({
|
||||
lanes,
|
||||
counts: {
|
||||
|
||||
@@ -37,7 +37,14 @@ router.get("/", async (req, res) => {
|
||||
}
|
||||
}
|
||||
try {
|
||||
res.json(await runRead("workflows", { status: statusFilter, tool, range, sections }));
|
||||
res.json(
|
||||
await runRead(
|
||||
"workflows",
|
||||
{ status: statusFilter, tool, range, sections },
|
||||
// Every open Workflows page shares one run (~1.5 s on a large DB).
|
||||
{ maxAgeMs: 30_000 }
|
||||
)
|
||||
);
|
||||
} catch (err) {
|
||||
if (err.code === "EREADTIMEOUT") {
|
||||
return res.status(503).json({ error: { code: err.code, message: err.message } });
|
||||
@@ -73,7 +80,7 @@ router.get("/skill-usage", (req, res) => {
|
||||
COUNT(*) AS count,
|
||||
COUNT(DISTINCT session_id) AS sessions
|
||||
FROM events
|
||||
WHERE tool_name = 'Skill' AND event_type = 'PreToolUse'
|
||||
WHERE tool_name = 'Skill' AND +event_type = 'PreToolUse'
|
||||
AND json_extract(data, '$.tool_input.skill') IS NOT NULL${sf.clause}
|
||||
GROUP BY name ORDER BY count DESC LIMIT 30`
|
||||
)
|
||||
@@ -83,11 +90,14 @@ router.get("/skill-usage", (req, res) => {
|
||||
return { ...r, plugin: i > 0 ? r.name.slice(0, i) : null };
|
||||
});
|
||||
|
||||
// A range on tool_name ("`" sorts right after "_") instead of LIKE, and
|
||||
// `+event_type` to keep the planner off idx_events_type: both make the
|
||||
// query use idx_events_tool (784 ms → a few ms on 253K events).
|
||||
const mcpCalls = db
|
||||
.prepare(
|
||||
`SELECT tool_name, COUNT(*) AS count FROM events
|
||||
WHERE tool_name LIKE 'mcp__plugin\\_%' ESCAPE '\\'
|
||||
AND event_type = 'PreToolUse'${sf.clause}
|
||||
WHERE tool_name >= 'mcp__plugin_' AND tool_name < 'mcp__plugin\`'
|
||||
AND +event_type = 'PreToolUse'${sf.clause}
|
||||
GROUP BY tool_name`
|
||||
)
|
||||
.all(...sf.params);
|
||||
|
||||
Reference in New Issue
Block a user