feat: Claude Code Monitor — lanes, pipelines and a merged workspace

Internal SmartGift build of a Claude Code monitoring dashboard.

Lanes: a durable unit of parallel agent work, one per working directory,
tracked across session restarts. Managed lanes are git worktrees the
dashboard provisions and can reset or remove behind a three-check destroy
guard and a counted preflight; adopted lanes are directories you already
own and are never destroyable.

Pipelines: a lane moves through pipeline stages. A stage the agent declares
with evidence renders green; a stage inferred from the tool-event stream
renders dashed amber and never counts as done. Detection is forward-only
within a 30-minute window, and never writes the declared stage.

Workspace: one page at /run with a lane grid, the selected lane's pipeline,
and a full Claude console behind a disclosure.
This commit is contained in:
2026-07-29 17:07:45 +07:00
commit 57dc91585d
783 changed files with 221743 additions and 0 deletions
@@ -0,0 +1,174 @@
/**
* @file useRunStream.test.tsx
* @description Covers `useRunStream`, the hook that owns the Run page's live
* envelope state: it subscribes to the event bus and folds `run_stream`
* envelopes into an array, forwards `run_status` / `run_input_ack` for the
* subscribed run id to the caller's callbacks, fires the id-agnostic
* `onAnyStatus` for every `run_status`, and disposes its subscription on
* unmount. `eventBus` is exercised for real (it is a plain in-memory pub/sub)
* with only its `subscribe` spied on, so the disposer assertion pins the real
* lifecycle rather than a mock's.
*
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
import { act, renderHook } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { eventBus } from "../../lib/eventBus";
import type { WSMessage } from "../../lib/types";
import { useRunStream, type Envelope } from "../useRunStream";
/** `run_stream` frame carrying one envelope for `id`. */
function streamMsg(id: string, envelope: unknown): WSMessage {
return { type: "run_stream", data: { id, envelope } } as WSMessage;
}
function statusMsg(id: string, status: string): WSMessage {
return { type: "run_status", data: { id, status, at: 1 } } as WSMessage;
}
const noopOpts = { onStatus: () => {}, onInputAck: () => {}, onAnyStatus: () => {} };
afterEach(() => {
vi.restoreAllMocks();
});
describe("useRunStream", () => {
it("merges envelopes for the subscribed run id in arrival order", () => {
const { result } = renderHook(() => useRunStream("run-1", noopOpts));
act(() => {
eventBus.publish(streamMsg("run-1", { type: "system", subtype: "init" }));
eventBus.publish(streamMsg("run-1", { type: "result", subtype: "success" }));
});
expect(result.current.envelopes.map((e) => (e as { type: string }).type)).toEqual([
"system",
"result",
]);
});
it("ignores an envelope for a different run id", () => {
const { result } = renderHook(() => useRunStream("run-1", noopOpts));
act(() => {
eventBus.publish(streamMsg("run-2", { type: "result" }));
});
expect(result.current.envelopes).toEqual([]);
});
it("updates a streaming assistant envelope in place instead of appending", () => {
const { result } = renderHook(() => useRunStream("run-1", noopOpts));
act(() => {
// message_start seeds the kept envelope + a streaming placeholder.
eventBus.publish(
streamMsg("run-1", {
type: "stream_event",
event: { type: "message_start", message: { id: "m1" } },
})
);
});
expect(result.current.envelopes).toHaveLength(2);
act(() => {
eventBus.publish(
streamMsg("run-1", {
type: "stream_event",
event: {
type: "content_block_start",
index: 0,
message: { id: "m1" },
content_block: { type: "text", text: "" },
},
})
);
eventBus.publish(
streamMsg("run-1", {
type: "stream_event",
event: {
type: "content_block_delta",
index: 0,
message: { id: "m1" },
delta: { type: "text_delta", text: "hi" },
},
})
);
});
// Still 2 envelopes: the deltas mutated the placeholder, they did not append.
expect(result.current.envelopes).toHaveLength(2);
const placeholder = result.current.envelopes[1] as {
message: { content: { text?: string }[]; _streaming?: boolean };
};
expect(placeholder.message.content[0]?.text).toBe("hi");
expect(placeholder.message._streaming).toBe(true);
});
it("invokes onStatus only for the subscribed run id, onAnyStatus for every run_status", () => {
const onStatus = vi.fn();
const onAnyStatus = vi.fn();
renderHook(() => useRunStream("run-1", { ...noopOpts, onStatus, onAnyStatus }));
act(() => {
eventBus.publish(statusMsg("run-1", "completed"));
eventBus.publish(statusMsg("run-2", "completed"));
});
expect(onStatus).toHaveBeenCalledTimes(1);
expect(onStatus.mock.calls[0]?.[0]).toMatchObject({ id: "run-1", status: "completed" });
expect(onAnyStatus).toHaveBeenCalledTimes(2);
});
it("invokes onInputAck only for the subscribed run id", () => {
const onInputAck = vi.fn();
renderHook(() => useRunStream("run-1", { ...noopOpts, onInputAck }));
act(() => {
eventBus.publish({ type: "run_input_ack", data: { id: "run-2" } } as WSMessage);
eventBus.publish({ type: "run_input_ack", data: { id: "run-1" } } as WSMessage);
});
expect(onInputAck).toHaveBeenCalledTimes(1);
});
it("ignores every frame while the run id is null", () => {
const onAnyStatus = vi.fn();
const { result } = renderHook(() => useRunStream(null, { ...noopOpts, onAnyStatus }));
act(() => {
eventBus.publish(streamMsg("run-1", { type: "result" }));
eventBus.publish(statusMsg("run-1", "completed"));
});
expect(result.current.envelopes).toEqual([]);
expect(onAnyStatus).toHaveBeenCalledTimes(1); // id-agnostic by design
});
it("disposes the event bus subscription on unmount", () => {
const dispose = vi.fn();
const subscribe = vi.spyOn(eventBus, "subscribe").mockReturnValue(dispose);
const { unmount } = renderHook(() => useRunStream("run-1", noopOpts));
expect(subscribe).toHaveBeenCalledTimes(1);
expect(dispose).not.toHaveBeenCalled();
unmount();
expect(dispose).toHaveBeenCalledTimes(1);
});
it("exposes setEnvelopes so the page can seed and clear the list", () => {
const { result } = renderHook(() => useRunStream("run-1", noopOpts));
act(() => {
result.current.setEnvelopes([{ type: "user", message: { content: "hello" } } as Envelope]);
});
expect(result.current.envelopes).toHaveLength(1);
act(() => {
result.current.setEnvelopes([]);
});
expect(result.current.envelopes).toEqual([]);
});
});
+25
View File
@@ -0,0 +1,25 @@
/**
* @file useDocumentTitle.ts
* @description Sets `document.title` for the current route/page and restores the
* previous title on unmount so browser tabs stay distinguishable.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
import { useEffect } from "react";
const APP_SUFFIX = "Claude Code Agent Monitor";
/**
* Update the browser tab title while this component is mounted.
* @param title Page-specific title segment (without the app suffix), or null to skip.
*/
export function useDocumentTitle(title: string | null | undefined): void {
useEffect(() => {
if (!title) return;
const previous = document.title;
document.title = `${title} · ${APP_SUFFIX}`;
return () => {
document.title = previous;
};
}, [title]);
}
+213
View File
@@ -0,0 +1,213 @@
/**
* @file useNotifications.ts
* @description Defines a custom React hook for managing browser notifications in the agent dashboard application. The hook subscribes to the event bus to listen for specific events such as new sessions, session errors, session completions, and subagent spawns. Based on user preferences stored in localStorage, it triggers browser notifications to keep users informed of important updates without needing to actively monitor the dashboard. The hook should be called once at the root level of the application to ensure notifications are handled globally.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
/* =============================================================================
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
* =============================================================================
* **Purpose:** React hook: isolates side effects and subscription wiring so presentational components stay declarative.
*
* ## Design constraints
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
*
* ## Remote data & SSH
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
*
* ## Observability
* Prometheus scrapes `GET /api/metrics` (see `monitoring/`). Grafana ships four
* provisioned boards (overview, sessions, tools, alerts). Native npm scripts and
* Docker Compose profiles are documented in `monitoring/README.md`.
*
* ## Internal dependencies
* - `../i18n`
* - `../lib/eventBus`
* - `../lib/push`
* - `../lib/types`
*
* ## Public surface
* - `useNotifications` — exported API; see TSDoc on the symbol for behavior.
*
* ## Testing pointers
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
* - Server contract changes require `npm run test:server` and OpenAPI sync.
* - MCP edits: `npm run mcp:typecheck` and `npm run mcp:build`.
*
* ## Related docs
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
* - `docs/API.md` — REST reference.
* - `.claude/skills/file-headers/` — mandatory `@author` header policy.
* ============================================================================= */
/* -----------------------------------------------------------------------------
* EXPORT CATALOG — quick index of symbols defined below (documentation only).
* -----------------------------------------------------------------------------
* **useNotifications**
* Part of this module's public contract. Downstream imports should treat
* the signature and return type as stable unless release notes say otherwise.
* When behavior changes, update the `@file` overview and relevant tests.
*
* ----------------------------------------------------------------------------- */
import { useEffect } from "react";
import i18n from "../i18n";
import { eventBus } from "../lib/eventBus";
import { subscribeToPush } from "../lib/push";
import type { WSMessage, Session, Agent, DashboardEvent } from "../lib/types";
const NOTIF_KEY = "agent-monitor-notifications";
/** User's browser-notification preferences, persisted to `localStorage` under
* {@link NOTIF_KEY} (written by the Settings page's notifications panel). */
interface NotifPrefs {
/** Master switch; when false, no notification types fire regardless of the
* per-event flags below. */
enabled: boolean;
onNewSession: boolean;
onSessionError: boolean;
onSessionComplete: boolean;
onSubagentSpawn: boolean;
}
/** Reads {@link NotifPrefs} from `localStorage`, merging over safe defaults so
* a partial/older saved object (or none at all) still yields a valid result.
* `enabled` defaults to false (opt-in) even in the "no saved value" branch,
* while individual event toggles default to a sensible starting mix. */
function loadPrefs(): NotifPrefs {
try {
const raw = localStorage.getItem(NOTIF_KEY);
if (!raw)
return {
enabled: false,
onNewSession: true,
onSessionError: true,
onSessionComplete: false,
onSubagentSpawn: false,
};
return {
enabled: false,
onNewSession: true,
onSessionError: true,
onSessionComplete: false,
onSubagentSpawn: false,
...JSON.parse(raw),
};
} catch {
return {
enabled: false,
onNewSession: true,
onSessionError: true,
onSessionComplete: false,
onSubagentSpawn: false,
};
}
}
/**
* Shows a browser notification, preferring a server-relayed push (so it can
* arrive even if this tab isn't the active one, or the browser is backgrounded)
* and falling back to a local service-worker/`Notification` call if the
* server is unreachable. No-ops when the user hasn't granted permission.
* @param title Notification title.
* @param body Notification body text.
*/
async function notify(title: string, body: string) {
if (!("Notification" in window) || Notification.permission !== "granted") return;
try {
await fetch("/api/push/send", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title, body }),
});
} catch {
// Server unreachable - fall back to local notification
try {
if ("serviceWorker" in navigator) {
const registration = await navigator.serviceWorker.ready;
await registration.showNotification(title, { body, icon: "/favicon.ico", silent: false });
} else {
new Notification(title, { body, icon: "/favicon.ico" });
}
} catch {
// Silently ignore
}
}
}
/**
* Wires the dashboard's {@link eventBus} up to browser notifications, per the
* user's saved {@link NotifPrefs}. Mount once at the app root (it has no
* return value and no props) - it re-reads preferences from `localStorage` on
* every incoming message, so toggling a Settings checkbox takes effect
* immediately without remounting. Also opportunistically (re-)subscribes to
* Web Push on mount when notifications are enabled and permission has
* already been granted, so push delivery survives a page reload.
*/
export function useNotifications() {
useEffect(() => {
const prefs = loadPrefs();
if (prefs.enabled && "Notification" in window && Notification.permission === "granted") {
subscribeToPush().catch(() => {});
}
return eventBus.subscribe((msg: WSMessage) => {
const prefs = loadPrefs();
if (!prefs.enabled) return;
switch (msg.type) {
case "session_created": {
if (!prefs.onNewSession) return;
const s = msg.data as Session;
notify(
i18n.t("errors:notifications.newSession"),
s.name || `${i18n.t("errors:notifications.sessionDefault")}${s.id.slice(0, 8)}`
);
break;
}
case "session_updated": {
const s = msg.data as Session;
if (s.status === "error" && prefs.onSessionError) {
notify(
i18n.t("errors:notifications.sessionError"),
s.name || `${i18n.t("errors:notifications.sessionDefault")}${s.id.slice(0, 8)}`
);
}
break;
}
case "agent_created": {
if (!prefs.onSubagentSpawn) return;
const a = msg.data as Agent;
if (a.type === "subagent") {
notify(i18n.t("errors:notifications.subagentSpawned"), a.name);
}
break;
}
case "new_event": {
const ev = msg.data as DashboardEvent;
if (ev.event_type === "Stop" && prefs.onSessionComplete) {
notify(
i18n.t("errors:notifications.finishedResponding"),
ev.summary || i18n.t("errors:notifications.readyForInput")
);
} else if (ev.event_type === "SessionEnd" && prefs.onSessionComplete) {
notify(
i18n.t("errors:notifications.sessionCompleted"),
ev.summary || i18n.t("errors:notifications.sessionClosed")
);
} else if (ev.event_type === "Notification") {
notify(
i18n.t("errors:notifications.defaultTitle"),
ev.summary || i18n.t("errors:notifications.defaultBody")
);
}
break;
}
}
});
}, []);
}
+489
View File
@@ -0,0 +1,489 @@
/**
* @file useRunStream.ts
* @description Owns the Run page's live stream-json state. Subscribes to the
* WebSocket event bus and folds every `run_stream` envelope for one run id into
* an envelope array (`mergeEnvelope` and friends, moved here verbatim from
* `pages/Run.tsx`), exposes the typewriter-smoothed view of that array, and
* hands `run_status` / `run_input_ack` back to the caller — the page still owns
* the `RunHandle` and the run-list refresh, so those arrive as callbacks.
*
* The stream-json envelope types live here too, since this hook is what
* produces them; the page imports them for rendering.
*
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
import { useEffect, useMemo, useRef, useState } from "react";
import { flushSync } from "react-dom";
import { eventBus } from "../lib/eventBus";
import type {
RunInputAckPayload,
RunStatusPayload,
RunStreamPayload,
WSMessage,
} from "../lib/types";
// ── Stream-json envelope shapes (the bits we render) ──────────────────
export type ContentBlock =
| { type: "text"; text: string }
| { type: "thinking"; thinking?: string }
| { type: "tool_use"; id: string; name: string; input: unknown }
| { type: "tool_result"; tool_use_id: string; content: unknown; is_error?: boolean };
export interface AssistantMessage {
type: "assistant";
message?: {
content?: ContentBlock[] | string;
usage?: {
input_tokens?: number;
output_tokens?: number;
cache_read_input_tokens?: number;
cache_creation_input_tokens?: number;
};
};
}
export interface UserMessage {
type: "user";
message?: { content?: ContentBlock[] | string };
}
export interface SystemInit {
type: "system";
subtype: "init";
session_id?: string;
model?: string;
cwd?: string;
tools?: string[];
permissionMode?: string;
}
export interface ResultEnvelope {
type: "result";
subtype?: string;
is_error?: boolean;
duration_ms?: number;
duration_api_ms?: number;
num_turns?: number;
result?: string;
session_id?: string;
total_cost_usd?: number;
usage?: { input_tokens?: number; output_tokens?: number };
}
export type Envelope =
| AssistantMessage
| UserMessage
| SystemInit
| ResultEnvelope
| { type: string; [k: string]: unknown };
// ── Streaming envelope merge ───────────────────────────────────────────
//
// `claude --output-format stream-json --include-partial-messages` emits two
// kinds of assistant output:
//
// 1. `stream_event` envelopes carrying Anthropic Messages API streaming
// events (`message_start`, `content_block_start`, `content_block_delta`,
// `content_block_stop`, `message_delta`, `message_stop`).
// 2. Eventually, a single complete `assistant` envelope summarising the turn.
//
// To make the chat actually stream character-by-character we accumulate the
// `stream_event` deltas into a synthetic assistant envelope. When the real
// `assistant` envelope arrives, we replace the synthetic one with it (their
// content is identical at that point, but the final envelope has authoritative
// usage / metadata).
interface StreamEventEnvelope {
type: "stream_event";
event?: {
type: string;
index?: number;
delta?: {
type: string;
text?: string;
thinking?: string;
partial_json?: string;
};
content_block?: {
type: string;
text?: string;
thinking?: string;
id?: string;
name?: string;
input?: unknown;
};
message?: { id?: string };
};
}
type StreamingAssistantBlock = ContentBlock & {
_partialJson?: string;
};
interface StreamingAssistantMessage {
type: "assistant";
_streamId?: string;
message: {
id?: string;
content: StreamingAssistantBlock[];
_streaming?: boolean;
};
}
function findLastStreamingAssistant(prev: Envelope[]): number {
for (let i = prev.length - 1; i >= 0; i--) {
const env = prev[i] as { type?: string; message?: { _streaming?: boolean } };
if (env?.type === "assistant" && env.message?._streaming) return i;
}
return -1;
}
function findAssistantByMessageId(prev: Envelope[], id: string | undefined): number {
if (!id) return findLastStreamingAssistant(prev);
for (let i = prev.length - 1; i >= 0; i--) {
const env = prev[i] as { type?: string; message?: { id?: string } };
if (env?.type === "assistant" && env.message?.id === id) return i;
}
return findLastStreamingAssistant(prev);
}
function mutateAssistantAt(
prev: Envelope[],
idx: number,
fn: (m: StreamingAssistantMessage["message"]) => StreamingAssistantMessage["message"]
): Envelope[] {
if (idx < 0) return prev;
const env = prev[idx] as StreamingAssistantMessage;
const next = [...prev];
next[idx] = {
...env,
message: fn(env.message || ({ content: [] } as StreamingAssistantMessage["message"])),
};
return next;
}
function mergeEnvelope(prev: Envelope[], envelope: Envelope): Envelope[] {
if (!envelope || typeof envelope !== "object") return prev;
const env = envelope as { type?: string };
if (env.type === "stream_event") {
const sse = envelope as StreamEventEnvelope;
const evt = sse.event;
if (!evt) return prev;
if (evt.type === "message_start") {
const placeholder: StreamingAssistantMessage = {
type: "assistant",
message: {
id: evt.message?.id,
content: [],
_streaming: true,
},
};
// Keep the message_start envelope itself in the array - its
// `event.message.usage` is the only place we get the initial input /
// cache token counts during live streaming. Without it, the meter is
// stuck at zero until the post-reload replay re-injects the same
// envelopes from the server.
return [...prev, envelope, placeholder as unknown as Envelope];
}
if (evt.type === "content_block_start") {
const idx = findAssistantByMessageId(prev, evt.message?.id);
if (idx < 0) return prev;
const blockIdx = evt.index ?? 0;
return mutateAssistantAt(prev, idx, (msg) => {
const blocks = [...(msg.content || [])];
blocks[blockIdx] = { ...(evt.content_block as ContentBlock) };
return { ...msg, content: blocks };
});
}
if (evt.type === "content_block_delta") {
const idx = findAssistantByMessageId(prev, evt.message?.id);
if (idx < 0) return prev;
const blockIdx = evt.index ?? 0;
return mutateAssistantAt(prev, idx, (msg) => {
const blocks = [...(msg.content || [])];
const block = (blocks[blockIdx] || {}) as StreamingAssistantBlock;
const next = { ...block } as StreamingAssistantBlock;
const delta = evt.delta;
if (delta?.type === "text_delta") {
(next as { text?: string }).text =
((next as { text?: string }).text || "") + (delta.text || "");
if (!next.type) (next as { type: string }).type = "text";
} else if (delta?.type === "thinking_delta") {
(next as { thinking?: string }).thinking =
((next as { thinking?: string }).thinking || "") + (delta.thinking || "");
if (!next.type) (next as { type: string }).type = "thinking";
} else if (delta?.type === "input_json_delta") {
// tool_use input streams as JSON-string fragments; accumulate, parse
// best-effort whenever the buffer is valid JSON.
next._partialJson = (next._partialJson || "") + (delta.partial_json || "");
try {
(next as { input?: unknown }).input = JSON.parse(next._partialJson);
} catch {
/* still incomplete JSON - leave previous parsed value */
}
}
blocks[blockIdx] = next;
return { ...msg, content: blocks };
});
}
if (evt.type === "message_stop") {
const idx = findAssistantByMessageId(prev, evt.message?.id);
if (idx < 0) return prev;
return mutateAssistantAt(prev, idx, (msg) => ({ ...msg, _streaming: false }));
}
if (evt.type === "message_delta") {
// message_delta carries the canonical per-message usage update (the
// running output_tokens for this turn). Keep the envelope so
// computeTokens can read it; otherwise the meter sits at the
// message_start placeholder value (output_tokens=4 etc) for the
// entire response.
return [...prev, envelope];
}
// content_block_start/stop and other stream_event subtypes are mutations
// on the placeholder we already track - no usage info, no need to keep
// the envelope itself.
return prev;
}
if (env.type === "assistant") {
// Claude emits the canonical `assistant` envelope BEFORE `message_stop`,
// so the message is still streaming at this point. Two regressions came
// out of replacing the placeholder wholesale here:
// 1. The `_streaming` flag was dropped, making the typewriter snap to
// full text the moment this envelope arrived.
// 2. The final envelope sometimes ships only the `text` content block
// (the `thinking` block we accumulated from `thinking_delta`s
// disappears), so the thinking section vanished as soon as the
// stream finished.
// Fix: when the placeholder was streaming, keep our delta-accumulated
// content (it's the authoritative record of every block) and only pull
// metadata from the incoming envelope. `message_stop` clears `_streaming`
// and the typewriter then reveals any unrevealed tail instantly.
const finalMsg = envelope as { message?: { id?: string; _streaming?: boolean } };
const idx = findAssistantByMessageId(prev, finalMsg.message?.id);
if (idx >= 0) {
const prevEnv = prev[idx] as StreamingAssistantMessage;
const next = [...prev];
if (prevEnv.message?._streaming) {
const incoming = envelope as { message?: Record<string, unknown> };
const incomingMsg = (incoming.message || {}) as Record<string, unknown>;
const accumulatedContent = prevEnv.message?.content || [];
const incomingContent = (incomingMsg as { content?: ContentBlock[] }).content;
// If the canonical envelope happens to carry MORE blocks (e.g. it
// includes a tool_use we hadn't seen as a stream_event yet), prefer
// it. Otherwise keep our accumulated blocks so we don't lose a
// thinking section the canonical envelope omitted.
const content =
Array.isArray(incomingContent) && incomingContent.length > accumulatedContent.length
? incomingContent
: accumulatedContent;
next[idx] = {
...envelope,
message: { ...incomingMsg, content, _streaming: true },
} as Envelope;
} else {
next[idx] = envelope;
}
return next;
}
return [...prev, envelope];
}
return [...prev, envelope];
}
/**
* Smooth out claude's bursty stream by dripping text/thinking deltas a few
* characters per frame. Without this, short responses (where claude emits
* the entire reply in one or two `text_delta` chunks) appear all-at-once.
* The hook returns a derived envelope list with each actively-streaming
* text/thinking block clamped to a displayed length that grows toward the
* server's target via requestAnimationFrame.
*/
function useTypewriterEnvelopes(envelopes: Envelope[]): Envelope[] {
const lengthsRef = useRef<Map<string, number>>(new Map());
const envRef = useRef<Envelope[]>(envelopes);
envRef.current = envelopes;
const [tick, setTick] = useState(0);
const rafRef = useRef<number | null>(null);
const tickFnRef = useRef<(() => void) | null>(null);
if (!tickFnRef.current) {
tickFnRef.current = function tickFn() {
const envs = envRef.current;
const lengths = lengthsRef.current;
let needsAnother = false;
let mutated = false;
for (let ei = 0; ei < envs.length; ei++) {
const env = envs[ei];
if (!env || (env as { type?: string }).type !== "assistant") continue;
const e = env as StreamingAssistantMessage;
const streaming = !!e.message?._streaming;
const blocks = e.message?.content || [];
for (let bi = 0; bi < blocks.length; bi++) {
const b = blocks[bi];
if (!b) continue;
let key: string;
let target: string;
if (b.type === "text") {
key = `${ei}:${bi}:t`;
target = (b as { text?: string }).text || "";
} else if (b.type === "thinking") {
key = `${ei}:${bi}:th`;
target = (b as { thinking?: string }).thinking || "";
} else {
continue;
}
const cur = lengths.get(key) ?? 0;
if (cur >= target.length) continue;
if (streaming) {
// Catch up to target in roughly 0.4s; bigger gaps drip faster.
const remaining = target.length - cur;
const step = Math.max(2, Math.ceil(remaining / 24));
lengths.set(key, Math.min(target.length, cur + step));
needsAnother = true;
mutated = true;
} else {
// Block is no longer streaming → reveal the rest instantly.
lengths.set(key, target.length);
mutated = true;
}
}
}
if (mutated) setTick((t) => (t + 1) & 0xffff);
rafRef.current = needsAnother
? requestAnimationFrame(tickFnRef.current as FrameRequestCallback)
: null;
};
}
// Single long-lived RAF loop. Reads envelopes via ref so new server data
// is picked up without tearing down and rescheduling the loop on every
// websocket message - a previous version restarted on each envelope
// change which dropped frames between bursts and hid the streaming.
useEffect(() => {
rafRef.current = requestAnimationFrame(tickFnRef.current as FrameRequestCallback);
return () => {
if (rafRef.current != null) cancelAnimationFrame(rafRef.current);
rafRef.current = null;
};
}, []);
// Wake the loop when new envelopes arrive if it's parked (no pending work).
useEffect(() => {
if (rafRef.current == null && envelopes.length > 0) {
rafRef.current = requestAnimationFrame(tickFnRef.current as FrameRequestCallback);
}
}, [envelopes]);
// Reset lengths when envelopes shrink (e.g., the user starts a new run).
useEffect(() => {
if (envelopes.length === 0 && lengthsRef.current.size > 0) {
lengthsRef.current.clear();
}
}, [envelopes.length]);
return useMemo(() => {
const lengths = lengthsRef.current;
return envelopes.map((env, ei) => {
if (!env || (env as { type?: string }).type !== "assistant") return env;
const e = env as StreamingAssistantMessage;
const blocks = e.message?.content || [];
let changed = false;
const nextBlocks = blocks.map((b, bi) => {
if (b.type === "text") {
const full = (b as { text?: string }).text || "";
const len = lengths.get(`${ei}:${bi}:t`) ?? full.length;
if (len < full.length) {
changed = true;
return { ...b, text: full.slice(0, len) };
}
} else if (b.type === "thinking") {
const full = (b as { thinking?: string }).thinking || "";
const len = lengths.get(`${ei}:${bi}:th`) ?? full.length;
if (len < full.length) {
changed = true;
return { ...b, thinking: full.slice(0, len) };
}
}
return b;
});
if (!changed) return env;
return {
...e,
message: { ...e.message, content: nextBlocks },
} as unknown as Envelope;
});
// tick is intentionally a dep so this memo re-runs on each RAF step.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [envelopes, tick]);
}
/**
* Subscribe to the live stream of one run.
*
* `runId` is the id whose frames this hook cares about — `null` while no run is
* attached. `onStatus` and `onInputAck` fire only for a payload matching
* `runId` (mirroring the page's old `handle && p.id === handle.id` guard);
* `onAnyStatus` fires for EVERY `run_status` frame regardless of id, because
* the page's run-list refresh has always been id-agnostic.
*/
export function useRunStream(
runId: string | null,
opts: {
onStatus: (p: RunStatusPayload) => void;
onInputAck: () => void;
onAnyStatus: () => void;
}
): {
envelopes: Envelope[];
setEnvelopes: React.Dispatch<React.SetStateAction<Envelope[]>>;
displayEnvelopes: Envelope[];
} {
const [envelopes, setEnvelopes] = useState<Envelope[]>([]);
const displayEnvelopes = useTypewriterEnvelopes(envelopes);
// Latest callbacks in a ref so the subscription's lifetime depends on the
// run id alone - re-subscribing whenever a caller passes a fresh closure
// would tear down and rebuild the bus handler on every page render.
const optsRef = useRef(opts);
optsRef.current = opts;
// WebSocket subscription - only act on messages for the current run.
useEffect(() => {
return eventBus.subscribe((msg: WSMessage) => {
if (msg.type === "run_stream") {
const p = msg.data as RunStreamPayload;
if (runId && p.id === runId) {
// React 18 auto-batches async setStates, which collapses bursts of
// stream_event deltas (and the final `assistant` envelope that
// follows them) into a single render - visually erasing the
// streaming effect. flushSync forces a commit per envelope so the
// user sees text_delta / thinking_delta chunks paint as they
// arrive instead of all at once.
flushSync(() => {
setEnvelopes((prev) => mergeEnvelope(prev, p.envelope as Envelope));
});
}
} else if (msg.type === "run_status") {
const p = msg.data as RunStatusPayload;
if (runId && p.id === runId) {
optsRef.current.onStatus(p);
}
optsRef.current.onAnyStatus();
} else if (msg.type === "run_input_ack") {
const p = msg.data as RunInputAckPayload;
if (runId && p.id === runId) {
optsRef.current.onInputAck();
}
}
});
}, [runId]);
return { envelopes, setEnvelopes, displayEnvelopes };
}
+200
View File
@@ -0,0 +1,200 @@
/**
* @file useWebSocket.ts
* @description Defines a custom React hook for managing WebSocket connections in the agent dashboard application. The hook establishes a WebSocket connection to the server, handles incoming messages, manages connection status, and implements automatic reconnection logic. It provides a clean interface for components to receive real-time updates from the server and react to changes in connectivity.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
/* =============================================================================
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
* =============================================================================
* **Purpose:** React hook: isolates side effects and subscription wiring so presentational components stay declarative.
*
* ## Design constraints
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
*
* ## Remote data & SSH
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
*
* ## Observability
* Prometheus scrapes `GET /api/metrics` (see `monitoring/`). Grafana ships four
* provisioned boards (overview, sessions, tools, alerts). Native npm scripts and
* Docker Compose profiles are documented in `monitoring/README.md`.
*
* ## Internal dependencies
* - `../lib/types`
* - `../lib/eventBus`
* - `../lib/api`
*
* ## Public surface
* - `useWebSocket` — exported API; see TSDoc on the symbol for behavior.
*
* ## Testing pointers
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
* - Server contract changes require `npm run test:server` and OpenAPI sync.
* - MCP edits: `npm run mcp:typecheck` and `npm run mcp:build`.
*
* ## Related docs
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
* - `docs/API.md` — REST reference.
* - `.claude/skills/file-headers/` — mandatory `@author` header policy.
* ============================================================================= */
/* -----------------------------------------------------------------------------
* EXPORT CATALOG — quick index of symbols defined below (documentation only).
* -----------------------------------------------------------------------------
* **useWebSocket**
* Part of this module's public contract. Downstream imports should treat
* the signature and return type as stable unless release notes say otherwise.
* When behavior changes, update the `@file` overview and relevant tests.
*
* ----------------------------------------------------------------------------- */
import { useEffect, useRef, useCallback, useState } from "react";
import type { WSMessage } from "../lib/types";
import { eventBus } from "../lib/eventBus";
import { dashboardToken } from "../lib/api";
/** Callback invoked with each parsed {@link WSMessage} the socket receives. */
type MessageHandler = (msg: WSMessage) => void;
/**
* Owns the dashboard's single WebSocket connection: connects to `/ws` on the
* current origin (matching the page's http/https scheme to ws/wss and
* attaching the dashboard auth token when one is configured), forwards parsed
* messages to `onMessage` and to the shared {@link eventBus}, and
* auto-reconnects with capped exponential backoff on close - plus an
* immediate reconnect attempt on tab focus/network-online/visibility-change
* so the socket recovers quickly after a server restart or laptop sleep.
* Guards against React 18 StrictMode's mount→cleanup→remount cycle opening a
* duplicate socket (see the inline comment in `connect`).
* @param onMessage Called with every message parsed from the socket; the
* latest reference is used even across reconnects (no stale closures).
* @returns `{ connected }` - the current live connection state, for a status indicator.
*/
export function useWebSocket(onMessage: MessageHandler) {
const wsRef = useRef<WebSocket | null>(null);
const handlersRef = useRef<MessageHandler>(onMessage);
const [connected, setConnected] = useState(false);
const reconnectTimer = useRef<ReturnType<typeof setTimeout>>();
const mountedRef = useRef(true);
const reconnectAttempts = useRef(0);
handlersRef.current = onMessage;
const connect = useCallback(() => {
if (!mountedRef.current) return;
// Don't open a second socket if one is already alive or in flight.
// Without this, React 18 StrictMode (mount → cleanup → remount in dev)
// and the close→reconnect race could leave two sockets connected at the
// same time. Both would receive every server broadcast, producing
// duplicate stream_event deltas (doubled text, duplicate assistant
// bubbles, doubled rate_limit_event rows).
const existing = wsRef.current;
if (
existing &&
(existing.readyState === WebSocket.OPEN || existing.readyState === WebSocket.CONNECTING)
) {
return;
}
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
const host = window.location.host;
// Pass the optional dashboard token (GHSA-gr74-4xfh-6jw9) on the WS upgrade
// when one is configured; omitted entirely for the default loopback bind.
const token = dashboardToken();
const query = token ? `?token=${encodeURIComponent(token)}` : "";
const ws = new WebSocket(`${protocol}//${host}/ws${query}`);
ws.onopen = () => {
if (mountedRef.current) {
setConnected(true);
eventBus.setConnected(true);
reconnectAttempts.current = 0; // Reset on successful connection
}
};
ws.onmessage = (event) => {
try {
const msg = JSON.parse(event.data) as WSMessage;
handlersRef.current(msg);
} catch {
// ignore malformed messages
}
};
ws.onclose = () => {
if (mountedRef.current) {
setConnected(false);
eventBus.setConnected(false);
// Exponential backoff capped low (0.5s, 1s, 2s, 3s max) so a server
// 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);
reconnectAttempts.current++;
reconnectTimer.current = setTimeout(connect, delay);
}
};
ws.onerror = () => {
ws.close();
};
wsRef.current = ws;
}, []);
useEffect(() => {
mountedRef.current = true;
connect();
return () => {
mountedRef.current = false;
clearTimeout(reconnectTimer.current);
const ws = wsRef.current;
if (ws) {
// Detach handlers so a still-closing socket can't deliver a final
// onmessage / onclose into the bus after the component is gone.
ws.onopen = null;
ws.onmessage = null;
ws.onclose = null;
ws.onerror = null;
ws.close();
wsRef.current = null;
}
};
}, [connect]);
// Reconnect *immediately* when the user/network signals the server is likely
// back: tab refocus, regained network, or page becoming visible again. This
// cancels any pending backoff timer and resets the attempt counter so we
// don't sit out a long delay - e.g. after the dashboard server restarts, the
// socket (and the Tabby eyes) recover the moment you look at the tab.
useEffect(() => {
const reconnectNow = () => {
if (!mountedRef.current) return;
const ws = wsRef.current;
if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING)) {
return; // already connected / connecting
}
clearTimeout(reconnectTimer.current);
reconnectAttempts.current = 0;
connect();
};
const onVisible = () => {
if (document.visibilityState === "visible") reconnectNow();
};
window.addEventListener("focus", reconnectNow);
window.addEventListener("online", reconnectNow);
document.addEventListener("visibilitychange", onVisible);
return () => {
window.removeEventListener("focus", reconnectNow);
window.removeEventListener("online", reconnectNow);
document.removeEventListener("visibilitychange", onVisible);
};
}, [connect]);
return { connected };
}