Files
AgentHub/client/src/App.tsx
T
nntrivi2001 daf5b7be92 feat: edit in the Changes panel, git graph history, plan quota (v2.3.0)
- Changes panel: a working file opens in a CodeMirror editor with its diff
  inline (DiffEditor.tsx, @codemirror/merge, lazy-loaded); Changes folds the
  unchanged lines, Whole file shows them; side by side at 50/50 and full
  width; a Revert per block; original from HEAD or the branch's merge base
  (`mergeBase` on GET /git/changes?range=branch)
- Every diff: green = line added whole, red = removed whole, blue = edited
  in place (--diff-mod)
- History drawn as a commit graph (#58: `parents` on GET /git/log,
  --date-order; lib/commitGraph.ts)
- Per-workspace never-stage list, drawn orange in the Files tree (--kept);
  closed Terminal rows past three deleted
- Status bar plan quota for Claude (per account) and Codex
  (GET /api/pricing/quota, server/lib/quota.js); compact hover panel that
  stays open, Refresh button with a spinner
- Settings → Appearance holds language, theme and pet; Ctrl+Shift+C copies;
  compact sidebar navigation and short session times
2026-10-06 15:38:25 +07:00

195 lines
7.4 KiB
TypeScript

/**
* @file App.tsx
* @description Top-level React tree for the AgentHub dashboard.
* Wires together routing, real-time WebSocket ingestion, browser notifications,
* and the splash screen shown on cold load.
*
* ## Data flow
* 1. {@link useWebSocket} connects to the server's `/ws` endpoint.
* 2. Each inbound {@link WSMessage} is published on the in-memory
* {@link eventBus} so any page can subscribe without prop drilling.
* 3. {@link useNotifications} listens for alert-worthy events and surfaces OS
* notifications when permitted.
*
* ## Routing
* All feature pages nest under {@link Layout}, which owns the sidebar and
* passes `wsConnected` for the connection badge. Unknown paths fall through to
* {@link NotFound}.
*
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
/* =============================================================================
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
* =============================================================================
* **Purpose:** Dashboard module consumed by the React client, MCP tools, or desktop shell depending on deployment mode.
*
* ## Design constraints
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
*
* ## Remote data & SSH
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
*
* ## Internal dependencies
* - `./components/Layout`
* - `./components/SplashScreen`
* - `./pages/Dashboard`
* - `./pages/History`
* - `./pages/SessionDetail` (lazy)
* - `./pages/SettingsHub` (lazy)
* - `./pages/Workspace` (lazy)
*
* ## Testing pointers
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
* - Server contract changes require `npm run test:server` and OpenAPI sync.
*
* ## Related docs
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
* - `docs/API.md` — REST reference.
* - `skills/file-headers/` — mandatory `@author` header policy.
* ============================================================================= */
import { BrowserRouter, Routes, Route, Navigate, useParams, useLocation } from "react-router-dom";
import { lazy, Suspense, useCallback, useEffect, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Layout } from "./components/Layout";
import { DocumentTitle } from "./components/DocumentTitle";
import { SplashScreen } from "./components/SplashScreen";
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";
import { eventBus } from "./lib/eventBus";
import { copyOnCtrlShiftC } from "./lib/keys";
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.
const Workspace = lazy(() => import("./pages/Workspace").then((m) => ({ default: m.Workspace })));
const SettingsHub = lazy(() =>
import("./pages/SettingsHub").then((m) => ({ default: m.SettingsHub }))
);
const SessionDetail = lazy(() =>
import("./pages/SessionDetail").then((m) => ({ default: m.SessionDetail }))
);
function PageFallback() {
const { t } = useTranslation();
return (
<div role="status" className="flex items-center justify-center py-20 text-sm text-fg-muted">
{t("common:loading")}
</div>
);
}
function Page({ children }: { children: ReactNode }) {
const { pathname } = useLocation();
return (
<RouteErrorBoundary resetKey={pathname}>
<Suspense fallback={<PageFallback />}>{children}</Suspense>
</RouteErrorBoundary>
);
}
/** Keyed by the id so moving to another session starts from fresh state. */
function SessionDetailRoute() {
const { id } = useParams();
return <SessionDetail key={id} />;
}
/**
* Application root component mounted by {@link main.tsx}.
* @returns Routed dashboard UI inside `BrowserRouter`.
*/
export default function App() {
const onMessage = useCallback((msg: WSMessage) => {
eventBus.publish(msg);
}, []);
const { connected } = useWebSocket(onMessage);
useNotifications();
// A self-update replaced the hashed assets this tab still references: Vite
// reports the failed preload here; reload once (guarded against loops).
useEffect(() => {
const onPreloadError = (e: Event) => {
if (reloadOnce()) e.preventDefault();
};
window.addEventListener("vite:preloadError", onPreloadError);
return () => window.removeEventListener("vite:preloadError", onPreloadError);
}, []);
// Ctrl+Shift+C is copy here (Linux terminal habit), not the browser's inspector.
useEffect(() => {
window.addEventListener("keydown", copyOnCtrlShiftC, true);
return () => window.removeEventListener("keydown", copyOnCtrlShiftC, true);
}, []);
return (
<>
<SplashScreen />
{/* One renderer gives every `title` in the app the designed bubble —
see components/Tooltip.tsx for why it is not a wrapper component. */}
<GlobalTooltip />
{/* App-wide toasts and promise-based confirms: lib/toast.ts, lib/confirm.ts. */}
<Toaster />
<ConfirmHost />
<BrowserRouter>
<DocumentTitle />
<Routes>
<Route element={<Layout wsConnected={connected} />}>
<Route index element={<Dashboard />} />
<Route path="sessions" element={<History />} />
<Route
path="sessions/:id"
element={
<Page>
<SessionDetailRoute />
</Page>
}
/>
<Route path="activity" element={<Navigate to="/sessions?view=events" replace />} />
<Route
path="workflows"
element={<Navigate to="/?tab=analytics&sub=workflow" replace />}
/>
<Route path="lanes" element={<Navigate to="/workspace" replace />} />
<Route
path="cc-config"
element={<Navigate to="/settings/agents/claude-code" replace />}
/>
<Route path="run" element={<Navigate to="/workspace" replace />} />
<Route
path="workspace"
element={
<Page>
<Workspace />
</Page>
}
/>
<Route
path="settings/*"
element={
<Page>
<SettingsHub />
</Page>
}
/>
<Route path="*" element={<NotFound />} />
</Route>
</Routes>
</BrowserRouter>
</>
);
}