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:
2026-10-07 13:24:15 +07:00
parent 8fdda66893
commit ca821008e2
75 changed files with 1711 additions and 699 deletions
+22 -7
View File
@@ -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={
+3 -3
View File
@@ -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
+8 -1
View File
@@ -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;
+14 -9
View File
@@ -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,
+19 -8
View File
@@ -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>
);
}
});
+29
View File
@@ -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>
);
}
+4 -1
View File
@@ -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);
}, []);
+1 -1
View File
@@ -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({
+2 -18
View File
@@ -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 = () => {
+55 -30
View File
@@ -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;
+8 -2
View File
@@ -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[]>([]);
+327 -260
View File
@@ -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
});
});
+3 -2
View File
@@ -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;
+8 -9
View File
@@ -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
+22
View File
@@ -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;
}
+4 -1
View File
@@ -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
View File
@@ -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
View File
@@ -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.
+31
View File
@@ -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
View File
@@ -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>
)
);
+1 -1
View File
@@ -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(
+7 -2
View File
@@ -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]);
+6 -3
View File
@@ -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;
+6 -3
View File
@@ -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, {
+5 -1
View File
@@ -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);
};
+2 -2
View File
@@ -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" ||
+2 -1
View File
@@ -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
+6 -1
View File
@@ -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 {