A modern and elegant dashboard for network traffic visualization and analysis.
fix(web): backend-switch cache isolation, error surfaces and dark-mode fixes
luolei9826c94b1926
diff --git a/apps/collector/src/modules/websocket/websocket.server.ts b/apps/collector/src/modules/websocket/websocket.server.tsindex 491faba..56f2ed4 100644--- a/apps/collector/src/modules/websocket/websocket.server.ts+++ b/apps/collector/src/modules/websocket/websocket.server.ts@@ -1191,6 +1191,7 @@ export class StatsWebSocketServer {const message: WebSocketMessage = {type: 'stats',+ backendId: this.resolveBackendId(clientInfo.backendId) ?? clientInfo.backendId ?? undefined,summaryFields: clientInfo.includeSummary? this.buildSummaryFieldList(clientInfo.summaryFields): undefined,@@ -1293,6 +1294,7 @@ export class StatsWebSocketServer {stats? JSON.stringify({type: 'stats',+ backendId: resolvedBackendId,summaryFields: clientInfo.includeSummary? this.buildSummaryFieldList(clientInfo.summaryFields): undefined,diff --git a/apps/web/app/[locale]/dashboard/components/header/index.tsx b/apps/web/app/[locale]/dashboard/components/header/index.tsxindex 7e2b309..75c9ede 100644--- a/apps/web/app/[locale]/dashboard/components/header/index.tsx+++ b/apps/web/app/[locale]/dashboard/components/header/index.tsx@@ -233,7 +233,7 @@ export function Header({variant="secondary"className={cn("text-[10px] h-5 gap-1",- isUnhealthy && "bg-red-100 text-red-600 border-red-200"+ isUnhealthy && "bg-red-100 text-red-600 border-red-200 dark:bg-red-500/15 dark:text-red-400 dark:border-red-500/25")}><Radio className={cn("w-2 h-2", isUnhealthy && "text-red-500")} />diff --git a/apps/web/app/[locale]/error.tsx b/apps/web/app/[locale]/error.tsxnew file mode 100644index 0000000..4c98b8a--- /dev/null+++ b/apps/web/app/[locale]/error.tsx@@ -0,0 +1,42 @@+"use client";++import { useEffect } from "react";+import { AlertTriangle, RotateCcw } from "lucide-react";+import { Button } from "@/components/ui/button";++// Route-level error boundary. Deliberately avoids next-intl / app providers:+// if those are what crashed, this must still render.+export default function LocaleError({+ error,+ reset,+}: {+ error: Error & { digest?: string };+ reset: () => void;+}) {+ useEffect(() => {+ console.error("[ErrorBoundary]", error);+ }, [error]);++ return (+ <div className="min-h-[60vh] flex items-center justify-center p-6">+ <div className="flex flex-col items-center gap-4 text-center max-w-md">+ <div className="w-12 h-12 rounded-2xl bg-red-50 dark:bg-red-500/15 flex items-center justify-center">+ <AlertTriangle className="w-6 h-6 text-red-500 dark:text-red-400" />+ </div>+ <div className="space-y-1">+ <h2 className="text-lg font-semibold">Something went wrong</h2>+ <p className="text-sm text-muted-foreground">+ 页面渲染出错了,请重试。如果问题持续,请刷新页面或查看控制台日志。+ </p>+ {error.digest && (+ <p className="text-xs text-muted-foreground/70 font-mono">digest: {error.digest}</p>+ )}+ </div>+ <Button variant="outline" size="sm" className="gap-1.5" onClick={reset}>+ <RotateCcw className="w-3.5 h-3.5" />+ Retry / 重试+ </Button>+ </div>+ </div>+ );+}diff --git a/apps/web/app/global-error.tsx b/apps/web/app/global-error.tsxnew file mode 100644index 0000000..d3d31f3--- /dev/null+++ b/apps/web/app/global-error.tsx@@ -0,0 +1,55 @@+"use client";++// Root-level error boundary — replaces the entire document when the locale+// layout itself throws, so it must render its own <html>/<body> and use no+// app providers or theme context.+export default function GlobalError({+ error,+ reset,+}: {+ error: Error & { digest?: string };+ reset: () => void;+}) {+ return (+ <html lang="en">+ <body+ style={{+ margin: 0,+ minHeight: "100vh",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ fontFamily:+ "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",+ background: "#0b0f19",+ color: "#e2e8f0",+ }}>+ <div style={{ textAlign: "center", maxWidth: 420, padding: 24 }}>+ <h2 style={{ fontSize: 18, marginBottom: 8 }}>Something went wrong</h2>+ <p style={{ fontSize: 14, color: "#94a3b8", marginBottom: 4 }}>+ 应用出现了未处理的错误,请重试。+ </p>+ {error.digest && (+ <p style={{ fontSize: 12, color: "#64748b", fontFamily: "monospace" }}>+ digest: {error.digest}+ </p>+ )}+ <button+ onClick={reset}+ style={{+ marginTop: 16,+ padding: "8px 20px",+ borderRadius: 9999,+ border: "1px solid #334155",+ background: "transparent",+ color: "#e2e8f0",+ fontSize: 13,+ cursor: "pointer",+ }}>+ Retry / 重试+ </button>+ </div>+ </body>+ </html>+ );+}diff --git a/apps/web/components/features/backend/backend-config-dialog.tsx b/apps/web/components/features/backend/backend-config-dialog.tsxindex f069922..88b5520 100644--- a/apps/web/components/features/backend/backend-config-dialog.tsx+++ b/apps/web/components/features/backend/backend-config-dialog.tsx@@ -1761,8 +1761,8 @@ export function BackendConfigDialog({size="icon"className={cn("h-8 w-8",- backend.health?.status === 'healthy' && "text-green-600 hover:text-green-700 hover:bg-green-50",- backend.health?.status === 'unhealthy' && "text-red-500 hover:text-red-600 hover:bg-red-50",+ backend.health?.status === 'healthy' && "text-green-600 hover:text-green-700 hover:bg-green-50 dark:text-green-400 dark:hover:text-green-300 dark:hover:bg-green-500/10",+ backend.health?.status === 'unhealthy' && "text-red-500 hover:text-red-600 hover:bg-red-50 dark:text-red-400 dark:hover:text-red-300 dark:hover:bg-red-500/10",!backend.health && "text-gray-400")}onClick={() => handleTest(backend)}diff --git a/apps/web/components/features/countries/world-traffic-map.tsx b/apps/web/components/features/countries/world-traffic-map.tsxindex 0bc8d13..734e8bc 100644--- a/apps/web/components/features/countries/world-traffic-map.tsx+++ b/apps/web/components/features/countries/world-traffic-map.tsx@@ -10,6 +10,7 @@ import {import { scaleLinear } from "d3-scale";import { Globe, Info } from "lucide-react";import { useTranslations } from "next-intl";+import { useTheme } from "next-themes";import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";import { formatBytes, formatNumber } from "@/lib/utils";import { useCountryName } from "@/lib/i18n-country";@@ -46,8 +47,26 @@ const COUNTRY_NAME_MAPPING: Record<string, string> = {// Add more mappings as needed};+// Map colors are inline SVG values, so both themes are defined here instead+// of Tailwind classes. Dark ramps from deep indigo to bright indigo so high+// traffic pops on the dark background.+const MAP_THEME = {+ light: {+ noData: "#f1f5f9",+ stroke: "#cbd5e1",+ scale: ["#e0e7ff", "#818cf8", "#6366f1", "#4f46e5"],+ },+ dark: {+ noData: "#1e2536",+ stroke: "rgba(148, 163, 184, 0.18)",+ scale: ["#312e81", "#4f46e5", "#818cf8", "#c7d2fe"],+ },+} as const;+export function WorldTrafficMap({ data }: WorldTrafficMapProps) {const t = useTranslations("map");+ const { resolvedTheme } = useTheme();+ const mapTheme = resolvedTheme === "dark" ? MAP_THEME.dark : MAP_THEME.light;const countryName = useCountryName();const [hoveredCountry, setHoveredCountry] = useState<string | null>(null);const [tooltipData, setTooltipData] = useState<{@@ -66,12 +85,12 @@ export function WorldTrafficMap({ data }: WorldTrafficMapProps) {return Math.max(...data.map((d) => d.totalDownload + d.totalUpload));}, [data]);- // Create color scale (light blue to deep purple)+ // Create color scale (theme-aware)const colorScale = useMemo(() => {return scaleLinear<string>().domain([0, maxTraffic * 0.1, maxTraffic * 0.5, maxTraffic])- .range(["#e0e7ff", "#818cf8", "#6366f1", "#4f46e5"]);- }, [maxTraffic]);+ .range([...mapTheme.scale]);+ }, [maxTraffic, mapTheme]);// Create country lookup mapconst countryMap = useMemo(() => {@@ -109,7 +128,7 @@ export function WorldTrafficMap({ data }: WorldTrafficMapProps) {}// Default color for countries with no data- return "#f1f5f9";+ return mapTheme.noData;};// Handle mouse enter@@ -184,7 +203,7 @@ export function WorldTrafficMap({ data }: WorldTrafficMapProps) {key={geo.rsmKey}geography={geo}fill={getFillColor(geo)}- stroke="#cbd5e1"+ stroke={mapTheme.stroke}strokeWidth={0.5}style={{default: {@@ -264,22 +283,9 @@ export function WorldTrafficMap({ data }: WorldTrafficMapProps) {<div className="flex items-center gap-1"><span className="text-xs">{t("low")}</span><div className="flex">- <div- className="w-6 h-3"- style={{ backgroundColor: "#e0e7ff" }}- />- <div- className="w-6 h-3"- style={{ backgroundColor: "#818cf8" }}- />- <div- className="w-6 h-3"- style={{ backgroundColor: "#6366f1" }}- />- <div- className="w-6 h-3"- style={{ backgroundColor: "#4f46e5" }}- />+ {mapTheme.scale.map((color) => (+ <div key={color} className="w-6 h-3" style={{ backgroundColor: color }} />+ ))}</div><span className="text-xs">{t("high")}</span></div>diff --git a/apps/web/components/features/rules/interactive-rule-stats.tsx b/apps/web/components/features/rules/interactive-rule-stats.tsxindex 9f47a26..f65e69f 100644--- a/apps/web/components/features/rules/interactive-rule-stats.tsx+++ b/apps/web/components/features/rules/interactive-rule-stats.tsx@@ -534,7 +534,7 @@ export function InteractiveRuleStats({<div className="flex items-center justify-between text-xs text-muted-foreground"><div className="flex flex-wrap items-center gap-x-2 gap-y-0.5"><span className="text-blue-500 dark:text-blue-400 whitespace-nowrap">↓ {formatBytes(item.download)}</span>- <span className="text-purple-500 dark:text-blue-400 whitespace-nowrap">↑ {formatBytes(item.upload)}</span>+ <span className="text-purple-500 dark:text-purple-400 whitespace-nowrap">↑ {formatBytes(item.upload)}</span><span className="flex items-center gap-1 tabular-nums"><Link2 className="w-3 h-3" />{formatNumber(item.connections)}diff --git a/apps/web/components/features/rules/rule-chain-flow.tsx b/apps/web/components/features/rules/rule-chain-flow.tsxindex 81c0799..468509c 100644--- a/apps/web/components/features/rules/rule-chain-flow.tsx+++ b/apps/web/components/features/rules/rule-chain-flow.tsx@@ -926,6 +926,7 @@ function UnifiedRuleChainFlowInner({const [data, setData] = useState<AllChainFlowData | null>(null);const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);+ const [retryNonce, setRetryNonce] = useState(0);const [showAll, setShowAll] = useState(false);const [activePolicyOnly, setActivePolicyOnly] = useState(false);const prevRuleRef = useRef(selectedRule);@@ -1100,7 +1101,7 @@ function UnifiedRuleChainFlowInner({return () => {cancelled = true;};- }, [activeBackendId, stableRange, useHttpFallback, commitChainFlowData]);+ }, [activeBackendId, stableRange, useHttpFallback, commitChainFlowData, retryNonce]);useEffect(() => {if (!wsEnabled) {@@ -1501,7 +1502,30 @@ function UnifiedRuleChainFlowInner({);}- if (error || !renderData || renderData.nodes.length <= 1) {+ if (error) {+ return (+ <Card className="mb-4">+ <CardContent className="py-8">+ <div className="flex flex-col items-center justify-center gap-3">+ <span className="text-sm text-muted-foreground">{t("chainFlowError")}</span>+ <Button+ variant="outline"+ size="sm"+ className="h-7 px-3 text-xs rounded-full"+ onClick={() => {+ setError(null);+ setLoading(true);+ setRetryNonce((n) => n + 1);+ }}>+ {t("chainFlowRetry")}+ </Button>+ </div>+ </CardContent>+ </Card>+ );+ }++ if (!renderData || renderData.nodes.length <= 1) {return null;}@@ -1598,7 +1622,8 @@ export const UnifiedRuleChainFlow = memo(prev.activeBackendId === next.activeBackendId &&prev.autoRefresh === next.autoRefresh &&prev.timeRange?.start === next.timeRange?.start &&- prev.timeRange?.end === next.timeRange?.end,+ prev.timeRange?.end === next.timeRange?.end &&+ prev.visibleRuleNames === next.visibleRuleNames,);// Backward-compatible aliasdiff --git a/apps/web/lib/websocket.ts b/apps/web/lib/websocket.tsindex 87170d7..71d15fc 100644--- a/apps/web/lib/websocket.ts+++ b/apps/web/lib/websocket.ts@@ -250,6 +250,7 @@ export function useStatsWebSocket(options: UseStatsWebSocketOptions = {}) {const trackLastMessageRef = useRef(trackLastMessage);const summaryFieldsKeyRef = useRef(summaryFieldsDependencyKey);const hasSummaryFieldsFilterRef = useRef(!!normalizedSummaryFields);+ const backendIdRef = useRef(backendId);onMessageRef.current = options.onMessage;onConnectRef.current = options.onConnect;onDisconnectRef.current = options.onDisconnect;@@ -257,6 +258,7 @@ export function useStatsWebSocket(options: UseStatsWebSocketOptions = {}) {trackLastMessageRef.current = trackLastMessage;summaryFieldsKeyRef.current = summaryFieldsDependencyKey;hasSummaryFieldsFilterRef.current = !!normalizedSummaryFields;+ backendIdRef.current = backendId;const cleanup = useCallback(() => {if (reconnectTimerRef.current) {@@ -326,6 +328,17 @@ export function useStatsWebSocket(options: UseStatsWebSocketOptions = {}) {const message = JSON.parse(event.data) as WebSocketMessage;if (message.type === 'stats' && message.data) {+ // Drop in-flight pushes from a previously subscribed backend —+ // without this a backend switch briefly writes the old backend's+ // data into the new backend's caches.+ if (+ message.backendId !== undefined &&+ backendIdRef.current !== undefined &&+ message.backendId !== backendIdRef.current+ ) {+ return;+ }+if (hasSummaryFieldsFilterRef.current) {const incomingSummaryFieldsKey = summaryFieldsKey(message.summaryFields);if (diff --git a/apps/web/messages/en.json b/apps/web/messages/en.jsonindex 416da13..9277456 100644--- a/apps/web/messages/en.json+++ b/apps/web/messages/en.json@@ -263,6 +263,8 @@"upload": "Upload","chainFlow": "Rule Chain Flow","loadingChainFlow": "Loading chain flow...",+ "chainFlowError": "Failed to load chain flow",+ "chainFlowRetry": "Retry","showAll": "Panorama","activePolicy": "All Policies","noTrafficRecord": "No traffic record",diff --git a/apps/web/messages/zh.json b/apps/web/messages/zh.jsonindex 9bd959f..99a5f04 100644--- a/apps/web/messages/zh.json+++ b/apps/web/messages/zh.json@@ -262,6 +262,8 @@"upload": "上传","chainFlow": "规则链路流向","loadingChainFlow": "加载链路流向...",+ "chainFlowError": "链路流向加载失败",+ "chainFlowRetry": "重试","showAll": "全景展示","activePolicy": "全部策略","noTrafficRecord": "暂无流量记录",