/** * @file RouteErrorBoundary.tsx * @description Route-level error boundary around the lazily loaded pages. After * a self-update an open tab still asks for the OLD `/assets/-.js`, * which the SPA fallback answers with index.html, so the dynamic import * rejects: that case reloads the page once (a sessionStorage guard stops a * reload loop). Any other render error — or a second chunk failure — shows a * themed "Something went wrong — Reload" panel instead of a blank app, until the * route changes (`resetKey`): the lazy routes share one boundary instance, so * an error on one page would otherwise stay on every other. * `reloadOnce` is also used by App's `vite:preloadError` listener. * @author Nguyễn Ngọc Trí Vĩ */ import { Component, type ReactNode } from "react"; import i18n from "../i18n"; const RELOAD_KEY = "agenthub.chunkReloadAt"; /** A second chunk failure within this window means the reload did not help. */ const RELOAD_WINDOW_MS = 30_000; /** A failed dynamic `import()` (Chrome, Firefox, Safari wordings) or a ChunkLoadError. */ export function isChunkLoadError(err: unknown): boolean { if (!(err instanceof Error)) return false; return ( err.name === "ChunkLoadError" || /dynamically imported module|Importing a module script failed|error loading dynamically imported module|Unable to preload CSS/i.test( err.message ) ); } /** Reload the page unless this tab already did so in the last 30 s. */ export function reloadOnce(reload: () => void = () => window.location.reload()): boolean { try { const last = Number(sessionStorage.getItem(RELOAD_KEY) || 0); if (Date.now() - last < RELOAD_WINDOW_MS) return false; sessionStorage.setItem(RELOAD_KEY, String(Date.now())); } catch { return false; // no sessionStorage: no loop guard, so never auto-reload } reload(); return true; } interface Props { children: ReactNode; /** Injected in tests; defaults to `window.location.reload`. */ reload?: () => void; /** A change (the route's path) clears a caught error. */ resetKey?: string; } export class RouteErrorBoundary extends Component { state = { error: null as Error | null }; static getDerivedStateFromError(error: Error) { return { error }; } componentDidCatch(error: Error) { if (isChunkLoadError(error)) reloadOnce(this.props.reload); } componentDidUpdate(prev: Props) { if (this.state.error && prev.resetKey !== this.props.resetKey) this.setState({ error: null }); } render() { if (!this.state.error) return this.props.children; const reload = this.props.reload ?? (() => window.location.reload()); return (

{i18n.t("dashboard:errorBoundary.title")}

{i18n.t("dashboard:errorBoundary.body")}

); } }