import { useLocale } from "../../hooks/useLocale"; import { t } from "../../i18n/translate"; import { lazy, Suspense, useCallback, useId, useMemo, useState, type ReactNode, type RefObject, type SetStateAction, } from "react"; import { Link, useLocation } from "react-router-dom"; import type { SessionDetailPhase } from "../../hooks/useSessionDetail"; import type { AgentCatalog } from "../../lib/agents"; import type { DashboardFilters } from "../../lib/api"; import type { AgentInfo, AppConfig, ApiProjectGroup, SessionHead } from "@codesesh/contract"; import { getSessionRouteKey, type IndexedSession } from "../../lib/session-indexes"; import type { TimeWindowPreset } from "../../lib/time-window"; import type { ViewState } from "../../lib/view-state"; import type { LandingAgentItem } from "../DetailLanding"; import { ErrorBoundary } from "../ErrorBoundary"; import { OverviewSkeleton } from "../overview/OverviewSkeleton"; import { RenderProfiler } from "../RenderProfiler"; import { SessionDetailSkeleton } from "../SessionDetailSkeleton"; import type { SearchFilterState, SearchLoadState, SearchProjectOption } from "./types"; import { SearchControls, type SearchControlsHandle } from "./SearchControls"; import { BUTTON_PRIMARY_CLASS } from "../ui/dialog-styles"; import { EmptyState } from "../ui/empty-state"; import { Funnel, RefreshCw, XCircle } from "../ui/icons"; const loadDetailLanding = () => import("../DetailLanding"); const loadOverviewScreen = () => import("../overview/OverviewScreen"); const loadProjects = () => import("../Projects"); const loadSessionDetail = () => import("../SessionDetail"); const loadSearchResultsPanel = () => import("./SearchResultsPanel"); export function preloadRouteChunk(pathname: string): void { if (pathname === "/" || pathname === "") { void loadOverviewScreen(); } else if (pathname.startsWith("/projects")) { void loadProjects(); } else if (pathname.startsWith("/sessions/")) { void loadSessionDetail(); } } const DetailLanding = lazy(() => loadDetailLanding().then((module) => ({ default: module.DetailLanding })), ); const OverviewScreen = lazy(() => loadOverviewScreen().then((module) => ({ default: module.OverviewScreen })), ); const ProjectsOverview = lazy(() => loadProjects().then((module) => ({ default: module.ProjectsOverview })), ); const ProjectDashboardView = lazy(() => loadProjects().then((module) => ({ default: module.ProjectDashboardView })), ); const SessionDetailView = lazy(() => loadSessionDetail().then((module) => ({ default: module.SessionDetailRoute })), ); const SearchResultsPanel = lazy(() => loadSearchResultsPanel().then((module) => ({ default: module.SearchResultsPanel })), ); function LazySurface({ fallback = , children, }: { fallback?: ReactNode; children: ReactNode; }) { useLocale(); const location = useLocation(); return ( {children} ); } interface LoadModel { loading: boolean; error: string | null; retry: () => void; } interface SessionDetailModel { phase: SessionDetailPhase; retry: () => void; } interface OverviewModel { window: AppConfig["window"] | null; rangePreset: TimeWindowPreset; unmatchedModelCount?: number; onOpenPricing?: () => void; } interface ProjectAgentFilterModel { selectedAgent?: string; onChangeAgent: (agent?: string) => void; } interface SearchContentModel { active: boolean; query: string; state: SearchLoadState; agentNameMap: ReadonlyMap; agents: AgentInfo[]; projectOptions: SearchProjectOption[]; projectDisplayNames?: ReadonlyMap; filters: SearchFilterState; onChangeFilters: (next: SetStateAction, draftQuery?: string) => void; onClose: () => void; onRetry: () => void; selectedIndex: number; onSelectIndex?: (index: number) => void; registerResultRef: (key: string, node: HTMLAnchorElement | null) => void; controls: RefObject; onSubmit: (query: string) => void; } interface BookmarkContentModel { isBookmarked: (agentKey: string, sessionId: string, sourceNodeId?: string) => boolean; toggleSessionBookmark: (session: SessionHead, agentKey: string) => void; } interface LandingRouteModel { agents: AgentInfo[]; agentCatalog: AgentCatalog; sessions: IndexedSession[]; bookmarks: BookmarkContentModel; } type RootRouteModel = Extract & { agentCatalog: AgentCatalog; projectCount: number; overview: OverviewModel; }; type ProjectsRouteModel = Extract & { agentCatalog: AgentCatalog; projectsLoad: LoadModel; window: AppConfig["window"] | null; }; type ProjectRouteModel = Extract & { agentCatalog: AgentCatalog; project: ApiProjectGroup | null; projectLoad: LoadModel; sessions: IndexedSession[]; agentFilter: ProjectAgentFilterModel; overview: OverviewModel; }; type AgentRouteModel = Extract & LandingRouteModel; type SessionRouteModel = Extract & LandingRouteModel & { detail: SessionDetailModel; detailHighlightQuery: string; onClearDetailHighlight?: () => void; childSessionsByParentRouteKey: ReadonlyMap; }; type MissingAgentRouteModel = Extract & LandingRouteModel; export type AppRouteModel = | RootRouteModel | ProjectsRouteModel | ProjectRouteModel | AgentRouteModel | SessionRouteModel | MissingAgentRouteModel | Extract; interface AppRouteContentProps { load: LoadModel; search: SearchContentModel; route: AppRouteModel; } function landingAgentItems(agents: AgentInfo[]): LandingAgentItem[] { return agents.map((agent) => ({ key: agent.name.toLowerCase(), name: agent.displayName, icon: agent.icon, iconColored: agent.iconColored, count: agent.count, })); } function SearchRouteContent({ search, controlsRef, }: { search: SearchContentModel; controlsRef: RefObject; }) { useLocale(); const filtersId = useId(); const activeFilters = Object.values(search.filters).filter(Boolean).length; const [filtersOpen, setFiltersOpen] = useState(activeFilters > 0); const [hadActiveFilters, setHadActiveFilters] = useState(activeFilters > 0); if (activeFilters > 0 && !hadActiveFilters) { setHadActiveFilters(true); setFiltersOpen(true); } else if (activeFilters === 0 && hadActiveFilters) { setHadActiveFilters(false); } const onChangeFilters = search.onChangeFilters; const handleChangeFilters = useCallback( (next: SetStateAction) => { const draftQuery = controlsRef.current?.getValue(); onChangeFilters(next, draftQuery); }, [controlsRef, onChangeFilters], ); const resultCount = search.state.status === "loaded" ? search.state.results.length : 0; return ( setFiltersOpen((open) => !open)} className="inline-flex h-9 items-center gap-1.5 rounded-lg border border-[var(--console-border-strong)] bg-[var(--console-surface)] px-3 text-xs font-medium text-[var(--console-text)] shadow-[var(--shadow-raised)] motion-hover hover:bg-[var(--console-surface-muted)] focus-visible:ring-2 focus-visible:ring-[var(--brand)] focus-visible:outline-none" > {t("Filters")} {activeFilters > 0 ? ( {activeFilters} ) : null} ); } function LoadError({ load }: { load: LoadModel }) { useLocale(); return ( } title={load.error} className="mx-auto max-w-4xl" > {t("Retry")} ); } function RootRouteContent({ route, onSelectModel, }: { route: RootRouteModel; onSelectModel: (model: string, scope: DashboardFilters) => void; }) { useLocale(); return ( ); } function ProjectsRouteContent({ route }: { route: ProjectsRouteModel }) { useLocale(); return ( ); } function ProjectRouteContent({ route, onSelectModel, }: { route: ProjectRouteModel; onSelectModel: (model: string, scope: DashboardFilters) => void; }) { useLocale(); return ( ); } function AgentRouteContent({ route }: { route: AgentRouteModel }) { useLocale(); const agentItems = useMemo(() => landingAgentItems(route.agents), [route.agents]); const toggleSessionBookmark = route.bookmarks.toggleSessionBookmark; const toggleBookmark = useCallback( (session: IndexedSession) => toggleSessionBookmark(session, session.reference.agentName), [toggleSessionBookmark], ); return ( ); } function SessionRouteContent({ route }: { route: SessionRouteModel }) { useLocale(); const agentItems = useMemo(() => landingAgentItems(route.agents), [route.agents]); const { phase } = route.detail; const currentSession = phase.kind === "ready" ? phase.session : null; const currentSessionAgentName = currentSession?.reference.agentName; const currentSessionId = currentSession?.reference.sessionId; const currentSessionSourceNodeId = currentSession?.reference.sourceNodeId; const childSessions = useMemo(() => { if (!currentSessionAgentName || !currentSessionId) return []; return ( route.childSessionsByParentRouteKey.get( getSessionRouteKey(currentSessionAgentName, currentSessionId, currentSessionSourceNodeId), ) ?? [] ); }, [ route.childSessionsByParentRouteKey, currentSessionAgentName, currentSessionId, currentSessionSourceNodeId, ]); const toggleSessionBookmark = route.bookmarks.toggleSessionBookmark; const toggleBookmark = useCallback( (session: IndexedSession) => toggleSessionBookmark(session, session.reference.agentName), [toggleSessionBookmark], ); if (phase.kind === "loading") return ; if (phase.kind === "missing") { return ( ); } if (phase.kind === "load-failed") { return ( ); } return ( }> ); } function MissingAgentRouteContent({ route }: { route: MissingAgentRouteModel }) { useLocale(); const agentItems = useMemo(() => landingAgentItems(route.agents), [route.agents]); return ( route.bookmarks.toggleSessionBookmark(session, session.reference.agentName) } /> ); } function InvalidRouteContent() { useLocale(); return ( {t("Page not found")} {t("This address does not match any dashboard, agent, or session route.")} {t("Back to dashboard")} ); } function RouteContent({ route, onSelectModel, }: { route: AppRouteModel; onSelectModel: (model: string, scope: DashboardFilters) => void; }) { useLocale(); switch (route.mode) { case "root": return ; case "projects": return ; case "project": return ; case "agent": return ; case "session": return ; case "missingAgent": return ; case "invalidRoute": return ; } } export function AppRouteContent({ load, search, route }: AppRouteContentProps) { useLocale(); const { onChangeFilters } = search; const handleSelectModel = useCallback( (model: string, scope: DashboardFilters) => { onChangeFilters( { ...(scope.project ? { project: scope.project } : {}), ...(scope.agent ? { agent: scope.agent } : {}), ...(scope.sourceNodeId ? { sourceNodeId: scope.sourceNodeId } : {}), }, `model:"${model}"`, ); }, [onChangeFilters], ); if (load.loading) { return route.mode === "session" ? : ; } if (search.active) return ; if (load.error) return ; return ; }
{t("This address does not match any dashboard, agent, or session route.")}