/** * @file Layout.tsx * @description Application shell that frames every authenticated route: persistent * sidebar, main content column, the bottom status bar, update notifier, and the * Sagi assistant overlay. The connection details modal's open state lives here * because both the sidebar's rail button and the status bar open it. * The layout is the single parent route in {@link App} — child pages render inside * React Router's `` so navigation never remounts chrome. * * ## Sidebar persistence * Collapsed state is read once from `localStorage` via {@link loadCollapsed} and * written back on every toggle. Failures to access storage are swallowed so a * private-browsing quota error never breaks the UI. * * ## Sidebar width * The expanded sidebar's right edge drags (or takes ←/→) between * {@link SIDEBAR_MIN} and {@link SIDEBAR_MAX} px — never past 40% of the * window — kept in `agenthub.sidebar.width`; a double-click resets it. * * ## Narrow viewports * With no stored preference the sidebar starts collapsed below `lg` (see * {@link loadCollapsed}). Below `md` it leaves the flow entirely: a menu * button in a slim top bar opens it as an off-canvas drawer (a modal dialog — * backdrop, Escape, focus trapped and restored), which closes on navigation. * * ## Sticky descendants * The inner content wrapper uses `overflow-x-clip` (not `hidden`) so horizontal * overflow is clipped without creating a scroll container. That keeps `position: * sticky` elements — e.g. the Settings page table-of-contents — pinned to the * viewport rather than a nested scroll box. * * @author Nguyễn Ngọc Trí Vĩ */ /* ============================================================================= * 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 * - `./Sidebar` * - `./UpdateNotifier` * - `./lanes/InterruptedSessionsPrompt` (the "resume interrupted sessions?" dialog) * - `./Sagi/SagiMount` * * ## Public surface * - `Layout` — exported API; see TSDoc on the symbol for behavior. * * ## Testing pointers * - Prefer colocated `__tests__` with Vitest + Testing Library for UI. * - Server contract changes require `npm run test:server` and OpenAPI sync. * * ## Related docs * - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline. * - `docs/API.md` — REST reference. * - `skills/file-headers/` — mandatory `@author` header policy. * ============================================================================= */ /* ----------------------------------------------------------------------------- * EXPORT CATALOG — quick index of symbols defined below (documentation only). * ----------------------------------------------------------------------------- * **Layout** * 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 { lazy, Suspense, useState, useCallback, useEffect, useSyncExternalStore } from "react"; import { Outlet, useLocation } from "react-router-dom"; import { Menu } from "lucide-react"; import { useTranslation } from "react-i18next"; import { Sidebar, SIDEBAR_STORAGE_KEY, loadCollapsed } from "./Sidebar"; import { UpdateNotifier } from "./UpdateNotifier"; import { InterruptedSessionsPrompt } from "./lanes/InterruptedSessionsPrompt"; import { SagiMount } from "./Sagi/SagiMount"; import { StatusBar } from "./StatusBar"; import { useOnboarding } from "../lib/userPrefs"; import { OnboardingTour } from "./onboarding/OnboardingTour"; // Loaded only for an account that has not finished onboarding: the wizard // carries the appearance, pet and notification settings screens. const OnboardingWizard = lazy(() => import("./onboarding/OnboardingWizard").then((m) => ({ default: m.OnboardingWizard })) ); const WIDTH_KEY = "agenthub.sidebar.width"; /** The default width, and the narrowest the edge drags to. */ export const SIDEBAR_MIN = 240; /** Wide enough for long workspace names on a large screen, no wider. */ export const SIDEBAR_MAX = 480; /** A width inside the bounds, and at most 40% of the window. */ export function clampSidebar(px: number): number { const max = Math.max(SIDEBAR_MIN, Math.min(SIDEBAR_MAX, window.innerWidth * 0.4)); return Math.round(Math.min(max, Math.max(SIDEBAR_MIN, px))); } function loadWidth(): number { try { const n = Number(localStorage.getItem(WIDTH_KEY)); if (n) return clampSidebar(n); } catch {} return SIDEBAR_MIN; } /** Below Tailwind's `md`: the sidebar becomes an off-canvas drawer. */ export const DRAWER_QUERY = "(max-width: 767.98px)"; function useMedia(query: string): boolean { return useSyncExternalStore( (cb) => { const mq = window.matchMedia?.(query); mq?.addEventListener?.("change", cb); return () => mq?.removeEventListener?.("change", cb); }, () => window.matchMedia?.(query).matches ?? false ); } /** Props for {@link Layout}. */ interface LayoutProps { /** Live WebSocket status forwarded to the sidebar connection indicator. */ wsConnected: boolean; } /** * Root layout wrapping all dashboard routes. * @param props See {@link LayoutProps}. */ export function Layout({ wsConnected }: LayoutProps) { const { t } = useTranslation("nav"); const [collapsed, setCollapsed] = useState(loadCollapsed); const [connectionOpen, setConnectionOpen] = useState(false); const onboarding = useOnboarding(); const [updateAvailable, setUpdateAvailable] = useState(false); const drawer = useMedia(DRAWER_QUERY); const [drawerOpen, setDrawerOpen] = useState(false); const closeDrawer = useCallback(() => setDrawerOpen(false), []); const { pathname, search } = useLocation(); const [width, setWidth] = useState(loadWidth); const [resizing, setResizing] = useState(false); const sidebarWidth = drawer ? "0rem" : collapsed ? "4.25rem" : `${width}px`; const saveWidth = useCallback((px: number) => { const next = clampSidebar(px); setWidth(next); try { localStorage.setItem(WIDTH_KEY, String(next)); } catch {} }, []); // A pick in the drawer navigates; the drawer has done its job. useEffect(closeDrawer, [pathname, search, closeDrawer]); useEffect(() => { if (!drawer) setDrawerOpen(false); }, [drawer]); const toggle = useCallback(() => { setCollapsed((prev) => { const next = !prev; try { localStorage.setItem(SIDEBAR_STORAGE_KEY, String(next)); } catch {} return next; }); }, []); return (
{t("skipToContent")} {onboarding.loaded && !onboarding.onboardedAt && ( )} {drawer && drawerOpen && (
)} {!drawer && !collapsed && (
{ e.preventDefault(); e.currentTarget.setPointerCapture?.(e.pointerId); setResizing(true); }} onPointerMove={(e) => { if (resizing) setWidth(clampSidebar(e.clientX)); }} onPointerUp={(e) => { if (!resizing) return; setResizing(false); saveWidth(e.clientX); }} onPointerCancel={() => setResizing(false)} onDoubleClick={() => saveWidth(SIDEBAR_MIN)} onKeyDown={(e) => { if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return; e.preventDefault(); saveWidth(width + (e.key === "ArrowRight" ? 16 : -16)); }} /> )}
{drawer && (
{t("brand")}
)} {/* overflow-x-clip (not -hidden) clips horizontal overflow without creating a scroll container, so descendant `position: sticky` elements (e.g. the Settings page TOC) still pin to the window. */}
setConnectionOpen(true)} updateAvailable={updateAvailable} />
); }