A modern and elegant dashboard for network traffic visualization and analysis.
perf: Conditionally fetch dashboard data based on active tab and refine backend status display.
luoleia4cb44d1c68f
diff --git a/apps/web/app/[locale]/page.tsx b/apps/web/app/[locale]/page.tsxindex 36dbce9..760613f 100644--- a/apps/web/app/[locale]/page.tsx+++ b/apps/web/app/[locale]/page.tsx@@ -59,6 +59,11 @@ import {TooltipProvider,TooltipTrigger,} from "@/components/ui/tooltip";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover";import {api,getPresetTimeRange,@@ -337,7 +342,9 @@ export default function DashboardPage() {const [activeBackend, setActiveBackend] = useState<Backend | null>(null);const [listeningBackends, setListeningBackends] = useState<Backend[]>([]);const initialLoaded = useRef(false);- const lastDataRef = useRef<string>("");+ const lastSummaryRef = useRef<string>("");+ const lastCountriesRef = useRef<string>("");+ const activeBackendId = activeBackend?.id;const backendStatus: BackendStatus = useMemo(() => {if (!activeBackend) return "unknown";@@ -382,31 +389,48 @@ export default function DashboardPage() {try {const queryRange = rangeOverride ?? timeRange;-- // Get active backend ID if available- const activeBackendData = await api.getActiveBackend();-- // If no active backend, skip stats loading- if ("error" in activeBackendData) {- setData(null);- setCountryData([]);- setError(null);- lastDataRef.current = "";- return;+ let backendId = activeBackendId;+ if (!backendId) {+ const activeBackendData = await api.getActiveBackend();+ if ("error" in activeBackendData) {+ setData(null);+ setCountryData([]);+ setError(null);+ lastSummaryRef.current = "";+ lastCountriesRef.current = "";+ return;+ }+ backendId = activeBackendData.id;+ if (!activeBackend || activeBackend.id !== activeBackendData.id) {+ setActiveBackend(activeBackendData);+ }}- const backendId = activeBackendData.id;+ const needsSummary =+ activeTab === "overview" || activeTab === "proxies" || activeTab === "rules";+ const needsCountries = activeTab === "overview" || activeTab === "countries";+const [stats, countries] = await Promise.all([- api.getSummary(backendId, queryRange),- api.getCountries(backendId, 50, queryRange),+ needsSummary ? api.getSummary(backendId, queryRange) : Promise.resolve(null),+ needsCountries ? api.getCountries(backendId, 50, queryRange) : Promise.resolve(null),]);- const nextSignature = JSON.stringify({ stats, countries });- if (nextSignature !== lastDataRef.current) {- lastDataRef.current = nextSignature;- setData(stats);- setCountryData(countries);+ if (stats) {+ const summarySignature = JSON.stringify(stats);+ if (summarySignature !== lastSummaryRef.current) {+ lastSummaryRef.current = summarySignature;+ setData(stats);+ }+ }++ if (countries) {+ const countriesSignature = JSON.stringify(countries);+ if (countriesSignature !== lastCountriesRef.current) {+ lastCountriesRef.current = countriesSignature;+ setCountryData(countries);+ }}+setLastUpdated(new Date());setError(null);} catch (err) {@@ -415,7 +439,7 @@ export default function DashboardPage() {if (showLoading) setIsLoading(false);}},- [timeRange],+ [timeRange, activeBackendId, activeBackend, activeTab],);const refreshNow = useCallback(@@ -494,20 +518,20 @@ export default function DashboardPage() {error={error}timeRange={timeRange}timePreset={timePreset}- activeBackendId={activeBackend?.id}+ activeBackendId={activeBackendId}onNavigate={setActiveTab}backendStatus={backendStatus}/>);case "domains":- return <DomainsContent data={data} activeBackendId={activeBackend?.id} timeRange={timeRange} />;+ return <DomainsContent data={data} activeBackendId={activeBackendId} timeRange={timeRange} />;case "countries":return <CountriesContent countryData={countryData} />;case "proxies":return (<ProxiesContentdata={data}- activeBackendId={activeBackend?.id}+ activeBackendId={activeBackendId}timeRange={timeRange}backendStatus={backendStatus}/>@@ -516,7 +540,7 @@ export default function DashboardPage() {return (<RulesContentdata={data}- activeBackendId={activeBackend?.id}+ activeBackendId={activeBackendId}timeRange={timeRange}backendStatus={backendStatus}/>@@ -524,7 +548,7 @@ export default function DashboardPage() {case "devices":return (<DevicesContent- activeBackendId={activeBackend?.id}+ activeBackendId={activeBackendId}timeRange={timeRange}backendStatus={backendStatus}/>@@ -539,7 +563,7 @@ export default function DashboardPage() {error={error}timeRange={timeRange}timePreset={timePreset}- activeBackendId={activeBackend?.id}+ activeBackendId={activeBackendId}onNavigate={setActiveTab}backendStatus={backendStatus}/>@@ -709,6 +733,42 @@ export default function DashboardPage() {/></div>+ {/* Mobile: Backend warning in top actions */}+ {backendStatus === "unhealthy" && (+ <div className="sm:hidden">+ <Popover>+ <PopoverTrigger asChild>+ <Button+ size="icon"+ variant="ghost"+ aria-label={dashboardT("backendUnavailable")}+ className="relative h-9 w-9 text-rose-500 hover:bg-rose-500/10 hover:text-rose-500"+ >+ <span className="absolute top-1.5 right-1.5 h-1.5 w-1.5 rounded-full bg-rose-500 animate-ping [animation-duration:900ms]" />+ <AlertTriangle className="h-4 w-4" />+ </Button>+ </PopoverTrigger>+ <PopoverContent+ align="end"+ side="bottom"+ className="w-[240px] p-3"+ >+ <div className="flex items-start gap-2">+ <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-rose-500" />+ <div className="min-w-0">+ <p className="text-sm font-medium text-rose-600 dark:text-rose-400">+ {dashboardT("backendUnavailable")}+ </p>+ <p className="text-xs text-muted-foreground">+ {backendStatusHint || dashboardT("backendUnavailableHint")}+ </p>+ </div>+ </div>+ </PopoverContent>+ </Popover>+ </div>+ )}+{/* Mobile: More Options Dropdown */}<div className="sm:hidden"><DropdownMenu>@@ -830,21 +890,6 @@ export default function DashboardPage() {</header><div className="p-4 lg:p-6 pb-24 lg:pb-6 max-w-7xl mx-auto">- {backendStatus === "unhealthy" && (- <div className="mb-4 rounded-xl border border-rose-500/30 bg-rose-500/5 px-4 py-3">- <div className="flex items-start gap-3">- <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-rose-500" />- <div className="min-w-0">- <p className="text-sm font-medium text-rose-600 dark:text-rose-400">- {dashboardT("backendUnavailable")}- </p>- <p className="text-xs text-muted-foreground">- {backendStatusHint || dashboardT("backendUnavailableHint")}- </p>- </div>- </div>- </div>- )}{renderContent()}</div></main>diff --git a/apps/web/components/backend-config-dialog.tsx b/apps/web/components/backend-config-dialog.tsxindex 163aa13..fb1e9ff 100644--- a/apps/web/components/backend-config-dialog.tsx+++ b/apps/web/components/backend-config-dialog.tsx@@ -892,7 +892,7 @@ export function BackendConfigDialog({</div>) : (// View Mode- <div className="flex items-center justify-between gap-4">+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4">{/* Left: Info */}<div className="flex-1 min-w-0"><div className="flex items-center gap-2 flex-wrap">@@ -905,15 +905,17 @@ export function BackendConfigDialog({</span>)}</div>- <div className="text-sm text-muted-foreground mt-1">+ <div+ className="text-sm text-muted-foreground mt-1 break-all sm:break-normal sm:truncate"+ title={`${backend.host}:${backend.port}`}>{backend.host}:{backend.port}</div></div>{/* Right: Actions */}- <div className="flex items-center gap-2 shrink-0">+ <div className="flex w-full sm:w-auto items-center justify-between sm:justify-end gap-2 shrink-0">{/* Collect Toggle with Label */}- <div className="flex items-center gap-2 px-3 py-1.5 rounded-lg bg-secondary/50">+ <div className="flex items-center gap-2 px-2 sm:px-3 py-1.5 rounded-lg bg-secondary/50"><Switchchecked={backend.listening}onCheckedChange={(checked) =>@@ -927,7 +929,7 @@ export function BackendConfigDialog({</div>{/* Action Buttons Group */}- <div className="flex items-center gap-1 pl-2 border-l border-border">+ <div className="flex items-center gap-1 pl-0 border-l-0 sm:pl-2 sm:border-l sm:border-border">{/* Set Active Button - Show placeholder when active to maintain layout */}<Buttonvariant="ghost"diff --git a/apps/web/components/domains-table.tsx b/apps/web/components/domains-table.tsxindex 6b29cad..2145597 100644--- a/apps/web/components/domains-table.tsx+++ b/apps/web/components/domains-table.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useCallback, useEffect, useRef } from "react";+import { useState, useCallback, useEffect, useMemo, useRef } from "react";import { Search, ArrowUpDown, ArrowDown, ArrowUp, ChevronLeft, ChevronRight, Rows3, ChevronDown, ChevronUp, Server, Loader2 } from "lucide-react";import { useTranslations } from "next-intl";import { Input } from "@/components/ui/input";@@ -32,6 +32,10 @@ type PageSize = typeof PAGE_SIZE_OPTIONS[number];export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps) {const t = useTranslations("domains");+ const stableTimeRange = useMemo<TimeRange | undefined>(() => {+ if (!timeRange?.start && !timeRange?.end) return undefined;+ return { start: timeRange.start, end: timeRange.end };+ }, [timeRange?.start, timeRange?.end]);const [data, setData] = useState<DomainStats[]>([]);const [total, setTotal] = useState(0);const [loading, setLoading] = useState(false);@@ -46,8 +50,20 @@ export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps)const [proxyStatsLoading, setProxyStatsLoading] = useState<string | null>(null);const [ipDetails, setIPDetails] = useState<Record<string, IPStats[]>>({});const [ipDetailsLoading, setIPDetailsLoading] = useState<string | null>(null);+ const proxyStatsRef = useRef<Record<string, ProxyTrafficStats[]>>({});+ const ipDetailsRef = useRef<Record<string, IPStats[]>>({});+ const proxyStatsInFlightRef = useRef<Set<string>>(new Set());+ const ipDetailsInFlightRef = useRef<Set<string>>(new Set());const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ useEffect(() => {+ proxyStatsRef.current = proxyStats;+ }, [proxyStats]);++ useEffect(() => {+ ipDetailsRef.current = ipDetails;+ }, [ipDetails]);+// Debounce search inputuseEffect(() => {debounceRef.current = setTimeout(() => {@@ -69,8 +85,8 @@ export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps)sortBy: sortKey,sortOrder,search: debouncedSearch || undefined,- start: timeRange?.start,- end: timeRange?.end,+ start: stableTimeRange?.start,+ end: stableTimeRange?.end,});if (!cancelled) {setData(result.data);@@ -88,13 +104,17 @@ export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps)};fetchData();return () => { cancelled = true; };- }, [activeBackendId, currentPage, pageSize, sortKey, sortOrder, debouncedSearch, timeRange]);+ }, [activeBackendId, currentPage, pageSize, sortKey, sortOrder, debouncedSearch, stableTimeRange]);useEffect(() => {// Backend switch means a different data universe, collapse safely.setExpandedDomain(null);setProxyStats({});setIPDetails({});+ setProxyStatsLoading(null);+ setIPDetailsLoading(null);+ proxyStatsInFlightRef.current.clear();+ ipDetailsInFlightRef.current.clear();}, [activeBackendId]);// Fetch proxy stats when a domain is expanded@@ -104,27 +124,28 @@ export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps)) => {const force = options?.force ?? false;const background = options?.background ?? false;- const hasCached = !!proxyStats[domain];+ const hasCached = !!proxyStatsRef.current[domain];if (!force && hasCached) return;+ if (proxyStatsInFlightRef.current.has(domain)) return;if (!background || !hasCached) {setProxyStatsLoading(domain);}+ proxyStatsInFlightRef.current.add(domain);try {const stats = await api.getDomainProxyStats(domain,activeBackendId,- timeRange,+ stableTimeRange,);setProxyStats(prev => ({ ...prev, [domain]: stats }));} catch (err) {console.error(`Failed to fetch proxy stats for ${domain}:`, err);setProxyStats(prev => ({ ...prev, [domain]: [] }));} finally {- if (proxyStatsLoading === domain) {- setProxyStatsLoading(null);- }+ proxyStatsInFlightRef.current.delete(domain);+ setProxyStatsLoading((prev) => (prev === domain ? null : prev));}- }, [proxyStats, activeBackendId, timeRange, proxyStatsLoading]);+ }, [activeBackendId, stableTimeRange]);// Fetch IP details when a domain is expandedconst fetchIPDetails = useCallback(async (@@ -133,27 +154,28 @@ export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps)) => {const force = options?.force ?? false;const background = options?.background ?? false;- const hasCached = !!ipDetails[domain];+ const hasCached = !!ipDetailsRef.current[domain];if (!force && hasCached) return;+ if (ipDetailsInFlightRef.current.has(domain)) return;if (!background || !hasCached) {setIPDetailsLoading(domain);}+ ipDetailsInFlightRef.current.add(domain);try {const details = await api.getDomainIPDetails(domain,activeBackendId,- timeRange,+ stableTimeRange,);setIPDetails(prev => ({ ...prev, [domain]: details }));} catch (err) {console.error(`Failed to fetch IP details for ${domain}:`, err);setIPDetails(prev => ({ ...prev, [domain]: [] }));} finally {- if (ipDetailsLoading === domain) {- setIPDetailsLoading(null);- }+ ipDetailsInFlightRef.current.delete(domain);+ setIPDetailsLoading((prev) => (prev === domain ? null : prev));}- }, [ipDetails, activeBackendId, timeRange, ipDetailsLoading]);+ }, [activeBackendId, stableTimeRange]);useEffect(() => {if (!expandedDomain) return;@@ -165,7 +187,7 @@ export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps)if (!expandedDomain) return;fetchProxyStats(expandedDomain, { force: true, background: true });fetchIPDetails(expandedDomain, { force: true, background: true });- }, [timeRange?.start, timeRange?.end, expandedDomain, fetchProxyStats, fetchIPDetails]);+ }, [timeRange?.start, timeRange?.end, fetchProxyStats, fetchIPDetails]);const handleSort = (key: SortKey) => {if (sortKey === key) {@@ -191,10 +213,6 @@ export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps)const toggleExpand = (domain: string) => {const newExpanded = expandedDomain === domain ? null : domain;setExpandedDomain(newExpanded);- if (newExpanded) {- fetchProxyStats(newExpanded);- fetchIPDetails(newExpanded);- }};const SortIcon = ({ column }: { column: SortKey }) => {diff --git a/apps/web/components/interactive-device-stats.tsx b/apps/web/components/interactive-device-stats.tsxindex 3049860..1c06b0e 100644--- a/apps/web/components/interactive-device-stats.tsx+++ b/apps/web/components/interactive-device-stats.tsx@@ -42,6 +42,10 @@ export function InteractiveDeviceStats({const t = useTranslations("devices");const domainsT = useTranslations("domains");const backendT = useTranslations("dashboard");+ const stableTimeRange = useMemo<TimeRange | undefined>(() => {+ if (!timeRange?.start && !timeRange?.end) return undefined;+ return { start: timeRange.start, end: timeRange.end };+ }, [timeRange?.start, timeRange?.end]);const [selectedDevice, setSelectedDevice] = useState<string | null>(null);const [deviceDomains, setDeviceDomains] = useState<DomainStats[]>([]);@@ -87,8 +91,8 @@ export function InteractiveDeviceStats({}try {const [domains, ips] = await Promise.all([- api.getDeviceDomains(sourceIP, activeBackendId, timeRange),- api.getDeviceIPs(sourceIP, activeBackendId, timeRange),+ api.getDeviceDomains(sourceIP, activeBackendId, stableTimeRange),+ api.getDeviceIPs(sourceIP, activeBackendId, stableTimeRange),]);if (requestId !== requestIdRef.current) return;setDeviceDomains(domains);@@ -104,7 +108,7 @@ export function InteractiveDeviceStats({setLoading(false);}}- }, [activeBackendId, timeRange]);+ }, [activeBackendId, stableTimeRange]);useEffect(() => {if (chartData.length === 0) {@@ -120,18 +124,17 @@ export function InteractiveDeviceStats({}, [chartData, selectedDevice]);useEffect(() => {- if (selectedDevice) {- const selectedChanged = prevSelectedDeviceRef.current !== selectedDevice;- const backendChanged = prevBackendRef.current !== activeBackendId;- const hasExistingDetails = deviceDomains.length > 0 || deviceIPs.length > 0;- if (loading && !selectedChanged && !backendChanged) return;- prevSelectedDeviceRef.current = selectedDevice;- prevBackendRef.current = activeBackendId;- loadDeviceDetails(selectedDevice, {- background: !selectedChanged && !backendChanged && hasExistingDetails,- });- }- }, [selectedDevice, activeBackendId, timeRange, loadDeviceDetails, deviceDomains.length, deviceIPs.length, loading]);+ if (!selectedDevice) return;++ const selectedChanged = prevSelectedDeviceRef.current !== selectedDevice;+ const backendChanged = prevBackendRef.current !== activeBackendId;++ prevSelectedDeviceRef.current = selectedDevice;+ prevBackendRef.current = activeBackendId;+ loadDeviceDetails(selectedDevice, {+ background: !selectedChanged && !backendChanged,+ });+ }, [selectedDevice, activeBackendId, timeRange?.start, timeRange?.end, loadDeviceDetails]);const handleDeviceClick = useCallback((rawName: string) => {if (selectedDevice !== rawName) {diff --git a/apps/web/components/interactive-proxy-stats.tsx b/apps/web/components/interactive-proxy-stats.tsxindex 4e1b4b3..23c3d7e 100644--- a/apps/web/components/interactive-proxy-stats.tsx+++ b/apps/web/components/interactive-proxy-stats.tsx@@ -66,6 +66,10 @@ export function InteractiveProxyStats({const t = useTranslations("proxies");const domainsT = useTranslations("domains");const backendT = useTranslations("dashboard");+ const stableTimeRange = useMemo<TimeRange | undefined>(() => {+ if (!timeRange?.start && !timeRange?.end) return undefined;+ return { start: timeRange.start, end: timeRange.end };+ }, [timeRange?.start, timeRange?.end]);const [selectedProxy, setSelectedProxy] = useState<string | null>(null);const [proxyDomains, setProxyDomains] = useState<DomainStats[]>([]);@@ -112,8 +116,8 @@ export function InteractiveProxyStats({}try {const [domains, ips] = await Promise.all([- api.getProxyDomains(chain, activeBackendId, timeRange),- api.getProxyIPs(chain, activeBackendId, timeRange),+ api.getProxyDomains(chain, activeBackendId, stableTimeRange),+ api.getProxyIPs(chain, activeBackendId, stableTimeRange),]);if (requestId !== requestIdRef.current) return;setProxyDomains(domains);@@ -129,7 +133,7 @@ export function InteractiveProxyStats({setLoading(false);}}- }, [activeBackendId, timeRange]);+ }, [activeBackendId, stableTimeRange]);useEffect(() => {if (chartData.length === 0) {@@ -145,18 +149,17 @@ export function InteractiveProxyStats({}, [chartData, selectedProxy]);useEffect(() => {- if (selectedProxy) {- const selectedChanged = prevSelectedProxyRef.current !== selectedProxy;- const backendChanged = prevBackendRef.current !== activeBackendId;- const hasExistingDetails = proxyDomains.length > 0 || proxyIPs.length > 0;- if (loading && !selectedChanged && !backendChanged) return;- prevSelectedProxyRef.current = selectedProxy;- prevBackendRef.current = activeBackendId;- loadProxyDetails(selectedProxy, {- background: !selectedChanged && !backendChanged && hasExistingDetails,- });- }- }, [selectedProxy, activeBackendId, timeRange, loadProxyDetails, proxyDomains.length, proxyIPs.length, loading]);+ if (!selectedProxy) return;++ const selectedChanged = prevSelectedProxyRef.current !== selectedProxy;+ const backendChanged = prevBackendRef.current !== activeBackendId;++ prevSelectedProxyRef.current = selectedProxy;+ prevBackendRef.current = activeBackendId;+ loadProxyDetails(selectedProxy, {+ background: !selectedChanged && !backendChanged,+ });+ }, [selectedProxy, activeBackendId, timeRange?.start, timeRange?.end, loadProxyDetails]);const handleProxyClick = useCallback((rawName: string) => {if (selectedProxy !== rawName) {diff --git a/apps/web/components/interactive-rule-stats.tsx b/apps/web/components/interactive-rule-stats.tsxindex faa61e1..feb6623 100644--- a/apps/web/components/interactive-rule-stats.tsx+++ b/apps/web/components/interactive-rule-stats.tsx@@ -101,6 +101,10 @@ export function InteractiveRuleStats({const domainsT = useTranslations("domains");const ipsT = useTranslations("ips");const backendT = useTranslations("dashboard");+ const stableTimeRange = useMemo<TimeRange | undefined>(() => {+ if (!timeRange?.start && !timeRange?.end) return undefined;+ return { start: timeRange.start, end: timeRange.end };+ }, [timeRange?.start, timeRange?.end]);const [selectedRule, setSelectedRule] = useState<string | null>(null);const [ruleDomains, setRuleDomains] = useState<DomainStats[]>([]);@@ -135,6 +139,12 @@ export function InteractiveRuleStats({const [ipProxyStatsLoading, setIPProxyStatsLoading] = useState<string | null>(null);const [ipDomainDetails, setIPDomainDetails] = useState<Record<string, DomainStats[]>>({});const [ipDomainDetailsLoading, setIPDomainDetailsLoading] = useState<string | null>(null);+ const domainProxyStatsRef = useRef<Record<string, ProxyTrafficStats[]>>({});+ const domainIPDetailsRef = useRef<Record<string, IPStats[]>>({});+ const ipProxyStatsRef = useRef<Record<string, ProxyTrafficStats[]>>({});+ const ipDomainDetailsRef = useRef<Record<string, DomainStats[]>>({});+ const domainDetailsInFlightRef = useRef<Set<string>>(new Set());+ const ipDetailsInFlightRef = useRef<Set<string>>(new Set());const requestIdRef = useRef(0);const prevSelectedRuleRef = useRef<string | null>(null);const prevBackendRef = useRef<number | undefined>(undefined);@@ -147,6 +157,22 @@ export function InteractiveRuleStats({return () => media.removeEventListener("change", update);}, []);+ useEffect(() => {+ domainProxyStatsRef.current = domainProxyStats;+ }, [domainProxyStats]);++ useEffect(() => {+ domainIPDetailsRef.current = domainIPDetails;+ }, [domainIPDetails]);++ useEffect(() => {+ ipProxyStatsRef.current = ipProxyStats;+ }, [ipProxyStats]);++ useEffect(() => {+ ipDomainDetailsRef.current = ipDomainDetails;+ }, [ipDomainDetails]);+// Fetch Clash rules to find zero-traffic rulesuseEffect(() => {let cancelled = false;@@ -248,17 +274,11 @@ export function InteractiveRuleStats({const toggleExpandDomain = (domain: string) => {const newExpanded = expandedDomain === domain ? null : domain;setExpandedDomain(newExpanded);- if (newExpanded) {- fetchExpandedDomainDetails(newExpanded);- }};const toggleExpandIP = (ip: string) => {const newExpanded = expandedIP === ip ? null : ip;setExpandedIP(newExpanded);- if (newExpanded) {- fetchExpandedIPDetails(newExpanded);- }};const fetchExpandedDomainDetails = useCallback(async (@@ -268,16 +288,18 @@ export function InteractiveRuleStats({if (!selectedRule) return;const force = options?.force ?? false;const background = options?.background ?? false;- const hasProxyCached = !!domainProxyStats[domain];- const hasIPCached = !!domainIPDetails[domain];+ const hasProxyCached = !!domainProxyStatsRef.current[domain];+ const hasIPCached = !!domainIPDetailsRef.current[domain];if (!force && hasProxyCached && hasIPCached) return;+ if (domainDetailsInFlightRef.current.has(domain)) return;if (!background || !hasProxyCached) setDomainProxyStatsLoading(domain);if (!background || !hasIPCached) setDomainIPDetailsLoading(domain);+ domainDetailsInFlightRef.current.add(domain);try {const [proxyStats, ipDetails] = await Promise.all([- api.getRuleDomainProxyStats(selectedRule, domain, activeBackendId, timeRange),- api.getRuleDomainIPDetails(selectedRule, domain, activeBackendId, timeRange),+ api.getRuleDomainProxyStats(selectedRule, domain, activeBackendId, stableTimeRange),+ api.getRuleDomainIPDetails(selectedRule, domain, activeBackendId, stableTimeRange),]);setDomainProxyStats((prev) => ({ ...prev, [domain]: proxyStats }));setDomainIPDetails((prev) => ({ ...prev, [domain]: ipDetails }));@@ -286,17 +308,14 @@ export function InteractiveRuleStats({setDomainProxyStats((prev) => ({ ...prev, [domain]: [] }));setDomainIPDetails((prev) => ({ ...prev, [domain]: [] }));} finally {- if (domainProxyStatsLoading === domain) setDomainProxyStatsLoading(null);- if (domainIPDetailsLoading === domain) setDomainIPDetailsLoading(null);+ domainDetailsInFlightRef.current.delete(domain);+ setDomainProxyStatsLoading((prev) => (prev === domain ? null : prev));+ setDomainIPDetailsLoading((prev) => (prev === domain ? null : prev));}}, [selectedRule,- domainProxyStats,- domainIPDetails,activeBackendId,- timeRange,- domainProxyStatsLoading,- domainIPDetailsLoading,+ stableTimeRange,]);const fetchExpandedIPDetails = useCallback(async (@@ -306,16 +325,18 @@ export function InteractiveRuleStats({if (!selectedRule) return;const force = options?.force ?? false;const background = options?.background ?? false;- const hasProxyCached = !!ipProxyStats[ip];- const hasDomainCached = !!ipDomainDetails[ip];+ const hasProxyCached = !!ipProxyStatsRef.current[ip];+ const hasDomainCached = !!ipDomainDetailsRef.current[ip];if (!force && hasProxyCached && hasDomainCached) return;+ if (ipDetailsInFlightRef.current.has(ip)) return;if (!background || !hasProxyCached) setIPProxyStatsLoading(ip);if (!background || !hasDomainCached) setIPDomainDetailsLoading(ip);+ ipDetailsInFlightRef.current.add(ip);try {const [proxyStats, domainDetails] = await Promise.all([- api.getRuleIPProxyStats(selectedRule, ip, activeBackendId, timeRange),- api.getRuleIPDomainDetails(selectedRule, ip, activeBackendId, timeRange),+ api.getRuleIPProxyStats(selectedRule, ip, activeBackendId, stableTimeRange),+ api.getRuleIPDomainDetails(selectedRule, ip, activeBackendId, stableTimeRange),]);setIPProxyStats((prev) => ({ ...prev, [ip]: proxyStats }));setIPDomainDetails((prev) => ({ ...prev, [ip]: domainDetails }));@@ -324,17 +345,14 @@ export function InteractiveRuleStats({setIPProxyStats((prev) => ({ ...prev, [ip]: [] }));setIPDomainDetails((prev) => ({ ...prev, [ip]: [] }));} finally {- if (ipProxyStatsLoading === ip) setIPProxyStatsLoading(null);- if (ipDomainDetailsLoading === ip) setIPDomainDetailsLoading(null);+ ipDetailsInFlightRef.current.delete(ip);+ setIPProxyStatsLoading((prev) => (prev === ip ? null : prev));+ setIPDomainDetailsLoading((prev) => (prev === ip ? null : prev));}}, [selectedRule,- ipProxyStats,- ipDomainDetails,activeBackendId,- timeRange,- ipProxyStatsLoading,- ipDomainDetailsLoading,+ stableTimeRange,]);// Sort icon component@@ -371,8 +389,8 @@ export function InteractiveRuleStats({try {const [domains, ips] = await Promise.all([- api.getRuleDomains(rule, activeBackendId, timeRange),- api.getRuleIPs(rule, activeBackendId, timeRange),+ api.getRuleDomains(rule, activeBackendId, stableTimeRange),+ api.getRuleIPs(rule, activeBackendId, stableTimeRange),]);if (requestId !== requestIdRef.current) return;setRuleDomains(domains);@@ -394,7 +412,7 @@ export function InteractiveRuleStats({setLoading(false);}}- }, [activeBackendId, timeRange]);+ }, [activeBackendId, stableTimeRange]);// Default select first rule when data loadsuseEffect(() => {@@ -411,21 +429,19 @@ export function InteractiveRuleStats({}, [chartData, selectedRule]);useEffect(() => {- if (selectedRule) {- const selectedChanged = prevSelectedRuleRef.current !== selectedRule;- const backendChanged = prevBackendRef.current !== activeBackendId;- const hasExistingDetails = ruleDomains.length > 0 || ruleIPs.length > 0;- if (loading && !selectedChanged && !backendChanged) return;- const background = !selectedChanged && !backendChanged && hasExistingDetails;-- prevSelectedRuleRef.current = selectedRule;- prevBackendRef.current = activeBackendId;- loadRuleDetails(selectedRule, {- background,- preserveUiState: background,- });- }- }, [selectedRule, activeBackendId, timeRange, loadRuleDetails, ruleDomains.length, ruleIPs.length, loading]);+ if (!selectedRule) return;++ const selectedChanged = prevSelectedRuleRef.current !== selectedRule;+ const backendChanged = prevBackendRef.current !== activeBackendId;+ const background = !selectedChanged && !backendChanged;++ prevSelectedRuleRef.current = selectedRule;+ prevBackendRef.current = activeBackendId;+ loadRuleDetails(selectedRule, {+ background,+ preserveUiState: background,+ });+ }, [selectedRule, activeBackendId, timeRange?.start, timeRange?.end, loadRuleDetails]);useEffect(() => {setExpandedDomain(null);@@ -438,8 +454,20 @@ export function InteractiveRuleStats({setDomainIPDetailsLoading(null);setIPProxyStatsLoading(null);setIPDomainDetailsLoading(null);+ domainDetailsInFlightRef.current.clear();+ ipDetailsInFlightRef.current.clear();}, [selectedRule, activeBackendId]);+ useEffect(() => {+ if (!expandedDomain) return;+ fetchExpandedDomainDetails(expandedDomain);+ }, [expandedDomain, fetchExpandedDomainDetails]);++ useEffect(() => {+ if (!expandedIP) return;+ fetchExpandedIPDetails(expandedIP);+ }, [expandedIP, fetchExpandedIPDetails]);+useEffect(() => {if (expandedDomain) {fetchExpandedDomainDetails(expandedDomain, { force: true, background: true });@@ -450,8 +478,6 @@ export function InteractiveRuleStats({}, [timeRange?.start,timeRange?.end,- expandedDomain,- expandedIP,fetchExpandedDomainDetails,fetchExpandedIPDetails,]);diff --git a/apps/web/components/ips-table.tsx b/apps/web/components/ips-table.tsxindex 108de58..314d6c8 100644--- a/apps/web/components/ips-table.tsx+++ b/apps/web/components/ips-table.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useCallback, useEffect, useRef } from "react";+import { useState, useCallback, useEffect, useMemo, useRef } from "react";import {Search,ArrowUpDown,@@ -72,6 +72,10 @@ const getIPColor = (ip: string) => {export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {const t = useTranslations("ips");+ const stableTimeRange = useMemo<TimeRange | undefined>(() => {+ if (!timeRange?.start && !timeRange?.end) return undefined;+ return { start: timeRange.start, end: timeRange.end };+ }, [timeRange?.start, timeRange?.end]);const [data, setData] = useState<IPStats[]>([]);const [total, setTotal] = useState(0);const [loading, setLoading] = useState(false);@@ -94,8 +98,20 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {const [domainDetailsLoading, setDomainDetailsLoading] = useState<string | null>(null,);+ const proxyStatsRef = useRef<Record<string, ProxyTrafficStats[]>>({});+ const domainDetailsRef = useRef<Record<string, DomainStats[]>>({});+ const proxyStatsInFlightRef = useRef<Set<string>>(new Set());+ const domainDetailsInFlightRef = useRef<Set<string>>(new Set());const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ useEffect(() => {+ proxyStatsRef.current = proxyStats;+ }, [proxyStats]);++ useEffect(() => {+ domainDetailsRef.current = domainDetails;+ }, [domainDetails]);+// Debounce search inputuseEffect(() => {debounceRef.current = setTimeout(() => {@@ -119,8 +135,8 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {sortBy: sortKey,sortOrder,search: debouncedSearch || undefined,- start: timeRange?.start,- end: timeRange?.end,+ start: stableTimeRange?.start,+ end: stableTimeRange?.end,});if (!cancelled) {setData(result.data);@@ -147,7 +163,7 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {sortKey,sortOrder,debouncedSearch,- timeRange,+ stableTimeRange,]);useEffect(() => {@@ -155,6 +171,10 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {setExpandedIP(null);setProxyStats({});setDomainDetails({});+ setProxyStatsLoading(null);+ setDomainDetailsLoading(null);+ proxyStatsInFlightRef.current.clear();+ domainDetailsInFlightRef.current.clear();}, [activeBackendId]);// Fetch proxy stats when an IP is expanded@@ -162,24 +182,25 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {async (ip: string, options?: { force?: boolean; background?: boolean }) => {const force = options?.force ?? false;const background = options?.background ?? false;- const hasCached = !!proxyStats[ip];+ const hasCached = !!proxyStatsRef.current[ip];if (!force && hasCached) return;+ if (proxyStatsInFlightRef.current.has(ip)) return;if (!background || !hasCached) {setProxyStatsLoading(ip);}+ proxyStatsInFlightRef.current.add(ip);try {- const stats = await api.getIPProxyStats(ip, activeBackendId, timeRange);+ const stats = await api.getIPProxyStats(ip, activeBackendId, stableTimeRange);setProxyStats((prev) => ({ ...prev, [ip]: stats }));} catch (err) {console.error(`Failed to fetch proxy stats for ${ip}:`, err);setProxyStats((prev) => ({ ...prev, [ip]: [] }));} finally {- if (proxyStatsLoading === ip) {- setProxyStatsLoading(null);- }+ proxyStatsInFlightRef.current.delete(ip);+ setProxyStatsLoading((prev) => (prev === ip ? null : prev));}},- [proxyStats, activeBackendId, timeRange, proxyStatsLoading],+ [activeBackendId, stableTimeRange],);// Fetch domain details (with traffic) when an IP is expanded@@ -187,24 +208,25 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {async (ip: string, options?: { force?: boolean; background?: boolean }) => {const force = options?.force ?? false;const background = options?.background ?? false;- const hasCached = !!domainDetails[ip];+ const hasCached = !!domainDetailsRef.current[ip];if (!force && hasCached) return;+ if (domainDetailsInFlightRef.current.has(ip)) return;if (!background || !hasCached) {setDomainDetailsLoading(ip);}+ domainDetailsInFlightRef.current.add(ip);try {- const details = await api.getIPDomainDetails(ip, activeBackendId, timeRange);+ const details = await api.getIPDomainDetails(ip, activeBackendId, stableTimeRange);setDomainDetails((prev) => ({ ...prev, [ip]: details }));} catch (err) {console.error(`Failed to fetch domain details for ${ip}:`, err);setDomainDetails((prev) => ({ ...prev, [ip]: [] }));} finally {- if (domainDetailsLoading === ip) {- setDomainDetailsLoading(null);- }+ domainDetailsInFlightRef.current.delete(ip);+ setDomainDetailsLoading((prev) => (prev === ip ? null : prev));}},- [domainDetails, activeBackendId, timeRange, domainDetailsLoading],+ [activeBackendId, stableTimeRange],);useEffect(() => {@@ -217,7 +239,7 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {if (!expandedIP) return;fetchProxyStats(expandedIP, { force: true, background: true });fetchDomainDetails(expandedIP, { force: true, background: true });- }, [timeRange?.start, timeRange?.end, expandedIP, fetchProxyStats, fetchDomainDetails]);+ }, [timeRange?.start, timeRange?.end, fetchProxyStats, fetchDomainDetails]);const handleSort = (key: SortKey) => {if (sortKey === key) {@@ -243,10 +265,6 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {const toggleExpand = (ip: string) => {const newExpanded = expandedIP === ip ? null : ip;setExpandedIP(newExpanded);- if (newExpanded) {- fetchProxyStats(newExpanded);- fetchDomainDetails(newExpanded);- }};const SortIcon = ({ column }: { column: SortKey }) => {diff --git a/apps/web/components/navigation.tsx b/apps/web/components/navigation.tsxindex 48118bb..156322d 100644--- a/apps/web/components/navigation.tsx+++ b/apps/web/components/navigation.tsx@@ -87,6 +87,11 @@ export function Navigation({: backendStatus === "unhealthy"? dashboardT("backendUnavailable"): dashboardT("backendStatusUnknown");+ const isBackendUnhealthy = backendStatus === "unhealthy";+ const statusDotSizeClass = isBackendUnhealthy ? "h-3 w-3" : "h-2.5 w-2.5";+ const statusPingAnimationClass = isBackendUnhealthy+ ? "animate-ping [animation-duration:700ms]"+ : "animate-ping [animation-duration:2s]";return (<>@@ -112,19 +117,29 @@ export function Navigation({<Tooltip><TooltipTrigger asChild><span- className="relative inline-flex h-2.5 w-2.5 shrink-0"+ className={cn("relative inline-flex shrink-0", statusDotSizeClass)}aria-label={statusText}role="status"><spanclassName={cn(- "absolute inline-flex h-full w-full rounded-full animate-ping",+ "absolute inline-flex h-full w-full rounded-full",statusPingClass,+ statusPingAnimationClass,)}/>+ {isBackendUnhealthy && (+ <span+ className={cn(+ "absolute inline-flex h-full w-full rounded-full animate-ping [animation-duration:700ms] [animation-delay:140ms]",+ statusPingClass,+ )}+ />+ )}<spanclassName={cn(- "relative inline-flex h-2.5 w-2.5 rounded-full shadow-[0_0_0_3px_rgba(255,255,255,0.06)]",+ "relative inline-flex rounded-full shadow-[0_0_0_3px_rgba(255,255,255,0.06)]",statusClass,+ statusDotSizeClass,)}/></span>diff --git a/apps/web/components/proxy-chain-badge.tsx b/apps/web/components/proxy-chain-badge.tsxindex 98b1c9d..ef0cd94 100644--- a/apps/web/components/proxy-chain-badge.tsx+++ b/apps/web/components/proxy-chain-badge.tsx@@ -116,7 +116,9 @@ export function ProxyChainBadge({<spanclassName={cn("inline-flex items-center gap-1 rounded-md bg-secondary/60 text-foreground dark:bg-secondary/40 dark:text-foreground/80 text-[11px] font-medium",- truncateLabel ? "px-1.5 py-0.5 truncate max-w-[120px]" : "px-2 py-0.5 whitespace-nowrap",+ truncateLabel+ ? "px-1.5 py-0.5 truncate max-w-[180px] lg:max-w-[220px]"+ : "px-2 py-0.5 whitespace-nowrap",badgeClassName,)}>diff --git a/apps/web/components/rule-chain-flow.tsx b/apps/web/components/rule-chain-flow.tsxindex 1967665..782dd6b 100644--- a/apps/web/components/rule-chain-flow.tsx+++ b/apps/web/components/rule-chain-flow.tsx@@ -6,6 +6,7 @@ import {ReactFlowProvider,Background,Controls,+ ControlButton,Handle,getStraightPath,useReactFlow,@@ -17,7 +18,16 @@ import {useEdgesState,} from "@xyflow/react";import "@xyflow/react/dist/style.css";-import { Workflow, Loader2, Server, Layers, Eye, Activity } from "lucide-react";+import {+ Workflow,+ Loader2,+ Server,+ Layers,+ Eye,+ Activity,+ Maximize2,+ Minimize2,+} from "lucide-react";import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";import { Button } from "@/components/ui/button";import { cn, formatBytes, formatNumber } from "@/lib/utils";@@ -356,10 +366,14 @@ function FlowRenderer({data,selectedRule,showAll,+ isFullscreen,+ onToggleFullscreen,}: {data: AllChainFlowData;selectedRule: string | null;showAll: boolean;+ isFullscreen: boolean;+ onToggleFullscreen: () => void;}) {const { fitView } = useReactFlow();const { resolvedTheme } = useTheme();@@ -595,6 +609,28 @@ function FlowRenderer({}}, []);+ useEffect(() => {+ if (!reactFlowReady.current) return;++ const doFitView = () => {+ if (showAll || !activeIndices) {+ fitView({ duration: 300, padding: 0.15 });+ } else {+ fitView({+ nodes: activeIndices.nodeIndices.map((i) => ({ id: String(i) })),+ duration: 300,+ padding: 0.15,+ });+ }+ };++ requestAnimationFrame(() => {+ requestAnimationFrame(() => {+ doFitView();+ });+ });+ }, [isFullscreen, showAll, activeIndices, fitView]);+return (<ReactFlownodes={nodes}@@ -614,7 +650,17 @@ function FlowRenderer({zoomOnDoubleClick={true}className="chain-flow-graph"><Background color={isDark ? "#374151" : "#e5e7eb"} gap={20} size={1} />- <Controls showInteractive={false} />+ <Controls showInteractive={false} showFitView={false}>+ <ControlButton+ onClick={onToggleFullscreen}+ title={isFullscreen ? "Exit fullscreen" : "Fullscreen"}>+ {isFullscreen ? (+ <Minimize2 className="h-4 w-4" />+ ) : (+ <Maximize2 className="h-4 w-4" />+ )}+ </ControlButton>+ </Controls></ReactFlow>);}@@ -638,6 +684,64 @@ export function UnifiedRuleChainFlow({const hasLoadedRef = useRef(false);const requestIdRef = useRef(0);const prevBackendRef = useRef<number | undefined>(undefined);+ const flowContainerRef = useRef<HTMLDivElement | null>(null);+ const [isFullscreen, setIsFullscreen] = useState(false);++ const toggleFullscreen = useCallback(async () => {+ if (typeof document === "undefined") return;+ const target = flowContainerRef.current;+ if (!target) return;++ const doc = document as Document & {+ webkitExitFullscreen?: () => Promise<void> | void;+ webkitFullscreenElement?: Element | null;+ };+ const element = target as HTMLElement & {+ webkitRequestFullscreen?: () => Promise<void> | void;+ };+ const fullscreenElement =+ doc.fullscreenElement ?? doc.webkitFullscreenElement ?? null;++ try {+ if (fullscreenElement) {+ if (doc.exitFullscreen) {+ await doc.exitFullscreen();+ } else if (doc.webkitExitFullscreen) {+ await doc.webkitExitFullscreen();+ }+ return;+ }+ if (element.requestFullscreen) {+ await element.requestFullscreen();+ } else if (element.webkitRequestFullscreen) {+ await element.webkitRequestFullscreen();+ }+ } catch (err) {+ console.error("Failed to toggle fullscreen:", err);+ }+ }, []);++ useEffect(() => {+ if (typeof document === "undefined") return;++ const handleFullscreenChange = () => {+ const doc = document as Document & { webkitFullscreenElement?: Element | null };+ const fullscreenElement =+ doc.fullscreenElement ?? doc.webkitFullscreenElement ?? null;+ setIsFullscreen(fullscreenElement === flowContainerRef.current);+ };++ document.addEventListener("fullscreenchange", handleFullscreenChange);+ document.addEventListener("webkitfullscreenchange", handleFullscreenChange as EventListener);++ return () => {+ document.removeEventListener("fullscreenchange", handleFullscreenChange);+ document.removeEventListener(+ "webkitfullscreenchange",+ handleFullscreenChange as EventListener,+ );+ };+ }, []);// Fetch on backend/time-range changes. Parent already drives 5s updates// for rolling windows, so avoid an additional local polling loop.@@ -899,14 +1003,14 @@ export function UnifiedRuleChainFlow({}return (- <Card className="mb-4 overflow-hidden">+ <Card className="mb-4 overflow-hidden"><CardHeader className="pb-3">- <div className="flex items-center justify-between">- <CardTitle className="text-sm font-semibold flex items-center gap-2">- <Workflow className="h-4 w-4 text-primary" />- {t("chainFlow")}+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">+ <CardTitle className="text-sm font-semibold flex items-center gap-2 min-w-0">+ <Workflow className="h-4 w-4 text-primary shrink-0" />+ <span className="leading-tight">{t("chainFlow")}</span></CardTitle>- <div className="flex items-center gap-2">+ <div className="flex w-full sm:w-auto items-center justify-end gap-2"><Buttonvariant="outline"size="sm"@@ -935,12 +1039,47 @@ export function UnifiedRuleChainFlow({</div></CardHeader><CardContent className="pt-0">- <div style={{ height: containerHeight }} className="w-full">+ <div+ ref={flowContainerRef}+ style={{ height: isFullscreen ? "100vh" : containerHeight }}+ className={cn("relative w-full", isFullscreen && "bg-background")}>+ {isFullscreen && (+ <div className="absolute top-3 right-3 z-20 flex items-center gap-2">+ <Button+ variant="outline"+ size="sm"+ className={cn(+ "h-8 px-3 text-xs gap-1.5 rounded-full transition-colors bg-background/85 backdrop-blur",+ activePolicyOnly+ ? "border-emerald-500 text-emerald-600 bg-emerald-50 hover:bg-emerald-100 dark:text-emerald-400 dark:bg-emerald-500/10 dark:hover:bg-emerald-500/20 dark:border-emerald-500/50"+ : "hover:border-emerald-300 hover:text-emerald-600",+ )}+ onClick={() => setActivePolicyOnly(!activePolicyOnly)}>+ <Activity+ className={cn("h-3.5 w-3.5", activePolicyOnly && "text-emerald-500")}+ />+ {t("activePolicy")}+ </Button>+ <Button+ variant={showAll ? "default" : "outline"}+ size="sm"+ className={cn(+ "h-8 px-3 text-xs gap-1.5 rounded-full bg-background/85 backdrop-blur",+ showAll && "bg-primary/90 hover:bg-primary",+ )}+ onClick={() => setShowAll(!showAll)}>+ <Eye className="h-3.5 w-3.5" />+ {t("showAll")}+ </Button>+ </div>+ )}<ReactFlowProvider><FlowRendererdata={renderData}selectedRule={showAll ? null : selectedRule}showAll={showAll}+ isFullscreen={isFullscreen}+ onToggleFullscreen={toggleFullscreen}/></ReactFlowProvider></div>diff --git a/apps/web/components/stats-tables/domain-stats-table.tsx b/apps/web/components/stats-tables/domain-stats-table.tsxindex 1a8af07..2d2c6f0 100644--- a/apps/web/components/stats-tables/domain-stats-table.tsx+++ b/apps/web/components/stats-tables/domain-stats-table.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useMemo, useCallback, useEffect } from "react";+import { useState, useMemo, useCallback, useEffect, useRef } from "react";import {ChevronLeft,ChevronRight,@@ -66,6 +66,10 @@ export function DomainStatsTable({showProxyTrafficInExpand = true,}: DomainStatsTableProps) {const t = useTranslations("domains");+ const stableTimeRange = useMemo<TimeRange | undefined>(() => {+ if (!timeRange?.start && !timeRange?.end) return undefined;+ return { start: timeRange.start, end: timeRange.end };+ }, [timeRange?.start, timeRange?.end]);const [page, setPage] = useState(1);const [pageSize, setPageSize] = useState<PageSize>(10);@@ -78,6 +82,18 @@ export function DomainStatsTable({const [proxyStatsLoading, setProxyStatsLoading] = useState<string | null>(null);const [ipDetails, setIPDetails] = useState<Record<string, IPStats[]>>({});const [ipDetailsLoading, setIPDetailsLoading] = useState<string | null>(null);+ const proxyStatsRef = useRef<Record<string, ProxyTrafficStats[]>>({});+ const ipDetailsRef = useRef<Record<string, IPStats[]>>({});+ const proxyStatsInFlightRef = useRef<Set<string>>(new Set());+ const ipDetailsInFlightRef = useRef<Set<string>>(new Set());++ useEffect(() => {+ proxyStatsRef.current = proxyStats;+ }, [proxyStats]);++ useEffect(() => {+ ipDetailsRef.current = ipDetails;+ }, [ipDetails]);useEffect(() => {// Context switch (backend/device/proxy/rule binding change): collapse.@@ -86,22 +102,26 @@ export function DomainStatsTable({setIPDetails({});setProxyStatsLoading(null);setIPDetailsLoading(null);+ proxyStatsInFlightRef.current.clear();+ ipDetailsInFlightRef.current.clear();}, [activeBackendId, sourceIP, sourceChain, richExpand]);const fetchProxyStats = useCallback(async (domain: string, options?: { force?: boolean; background?: boolean }) => {const force = options?.force ?? false;const background = options?.background ?? false;- const hasCached = !!proxyStats[domain];+ const hasCached = !!proxyStatsRef.current[domain];if (!richExpand || (!force && hasCached)) return;+ if (proxyStatsInFlightRef.current.has(domain)) return;if (!background || !hasCached) {setProxyStatsLoading(domain);}+ proxyStatsInFlightRef.current.add(domain);try {const stats = await api.getDomainProxyStats(domain,activeBackendId,- timeRange,+ stableTimeRange,sourceIP,sourceChain,);@@ -110,28 +130,29 @@ export function DomainStatsTable({console.error(`Failed to fetch proxy stats for ${domain}:`, err);setProxyStats((prev) => ({ ...prev, [domain]: [] }));} finally {- if (proxyStatsLoading === domain) {- setProxyStatsLoading(null);- }+ proxyStatsInFlightRef.current.delete(domain);+ setProxyStatsLoading((prev) => (prev === domain ? null : prev));}},- [proxyStats, activeBackendId, timeRange, sourceIP, sourceChain, richExpand, proxyStatsLoading],+ [activeBackendId, stableTimeRange, sourceIP, sourceChain, richExpand],);const fetchIPDetails = useCallback(async (domain: string, options?: { force?: boolean; background?: boolean }) => {const force = options?.force ?? false;const background = options?.background ?? false;- const hasCached = !!ipDetails[domain];+ const hasCached = !!ipDetailsRef.current[domain];if (!richExpand || (!force && hasCached)) return;+ if (ipDetailsInFlightRef.current.has(domain)) return;if (!background || !hasCached) {setIPDetailsLoading(domain);}+ ipDetailsInFlightRef.current.add(domain);try {const details = await api.getDomainIPDetails(domain,activeBackendId,- timeRange,+ stableTimeRange,sourceIP,sourceChain,);@@ -140,12 +161,11 @@ export function DomainStatsTable({console.error(`Failed to fetch IP details for ${domain}:`, err);setIPDetails((prev) => ({ ...prev, [domain]: [] }));} finally {- if (ipDetailsLoading === domain) {- setIPDetailsLoading(null);- }+ ipDetailsInFlightRef.current.delete(domain);+ setIPDetailsLoading((prev) => (prev === domain ? null : prev));}},- [ipDetails, activeBackendId, timeRange, sourceIP, sourceChain, richExpand, ipDetailsLoading],+ [activeBackendId, stableTimeRange, sourceIP, sourceChain, richExpand],);useEffect(() => {@@ -158,7 +178,7 @@ export function DomainStatsTable({if (!expandedDomain || !richExpand) return;fetchProxyStats(expandedDomain, { force: true, background: true });fetchIPDetails(expandedDomain, { force: true, background: true });- }, [timeRange?.start, timeRange?.end, expandedDomain, richExpand, fetchProxyStats, fetchIPDetails]);+ }, [timeRange?.start, timeRange?.end, richExpand, fetchProxyStats, fetchIPDetails]);const handleSort = (key: DomainSortKey) => {if (sortKey === key) {@@ -173,10 +193,6 @@ export function DomainStatsTable({const toggleExpand = (domain: string) => {const newExpanded = expandedDomain === domain ? null : domain;setExpandedDomain(newExpanded);- if (newExpanded && richExpand) {- fetchProxyStats(newExpanded);- fetchIPDetails(newExpanded);- }};const SortIcon = ({ column }: { column: DomainSortKey }) => {diff --git a/apps/web/components/stats-tables/expanded-details.tsx b/apps/web/components/stats-tables/expanded-details.tsxindex a6e5e3c..a87144f 100644--- a/apps/web/components/stats-tables/expanded-details.tsx+++ b/apps/web/components/stats-tables/expanded-details.tsx@@ -171,8 +171,9 @@ function ProxyTrafficCards({<div className="flex flex-wrap items-center gap-2 sm:gap-3 text-[11px] tabular-nums"><span className="text-blue-500">↓ {formatBytes(ps.totalDownload)}</span><span className="text-purple-500">↑ {formatBytes(ps.totalUpload)}</span>- <span className="text-muted-foreground">- {formatNumber(ps.totalConnections)} {connLabel}+ <span className="inline-flex items-center gap-1 text-muted-foreground">+ <Link2 className="h-3 w-3" />+ {formatNumber(ps.totalConnections)}</span></div></div>@@ -325,8 +326,9 @@ export function DomainExpandedDetails({<div className="flex flex-wrap items-center gap-2 sm:gap-3 text-[11px] tabular-nums"><span className="text-blue-500">↓ {formatBytes(ipStat.totalDownload)}</span><span className="text-purple-500">↑ {formatBytes(ipStat.totalUpload)}</span>- <span className="text-muted-foreground">- {formatNumber(ipStat.totalConnections)} {labels.conn}+ <span className="inline-flex items-center gap-1 text-muted-foreground">+ <Link2 className="h-3 w-3" />+ {formatNumber(ipStat.totalConnections)}</span></div>{location && (@@ -447,8 +449,9 @@ export function IPExpandedDetails({<div className="flex flex-wrap items-center gap-2 sm:gap-3 text-[11px] tabular-nums"><span className="text-blue-500">↓ {formatBytes(domain.totalDownload)}</span><span className="text-purple-500">↑ {formatBytes(domain.totalUpload)}</span>- <span className="text-muted-foreground">- {formatNumber(domain.totalConnections)} {labels.conn}+ <span className="inline-flex items-center gap-1 text-muted-foreground">+ <Link2 className="h-3 w-3" />+ {formatNumber(domain.totalConnections)}</span></div></div>diff --git a/apps/web/components/stats-tables/ip-stats-table.tsx b/apps/web/components/stats-tables/ip-stats-table.tsxindex f40785c..0f83362 100644--- a/apps/web/components/stats-tables/ip-stats-table.tsx+++ b/apps/web/components/stats-tables/ip-stats-table.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useMemo, useCallback, useEffect } from "react";+import { useState, useMemo, useCallback, useEffect, useRef } from "react";import {ChevronLeft,ChevronRight,@@ -68,6 +68,10 @@ export function IPStatsTable({showProxyTrafficInExpand = true,}: IPStatsTableProps) {const t = useTranslations("ips");+ const stableTimeRange = useMemo<TimeRange | undefined>(() => {+ if (!timeRange?.start && !timeRange?.end) return undefined;+ return { start: timeRange.start, end: timeRange.end };+ }, [timeRange?.start, timeRange?.end]);const [page, setPage] = useState(1);const [pageSize, setPageSize] = useState<PageSize>(10);@@ -80,6 +84,18 @@ export function IPStatsTable({const [proxyStatsLoading, setProxyStatsLoading] = useState<string | null>(null);const [domainDetails, setDomainDetails] = useState<Record<string, DomainStats[]>>({});const [domainDetailsLoading, setDomainDetailsLoading] = useState<string | null>(null);+ const proxyStatsRef = useRef<Record<string, ProxyTrafficStats[]>>({});+ const domainDetailsRef = useRef<Record<string, DomainStats[]>>({});+ const proxyStatsInFlightRef = useRef<Set<string>>(new Set());+ const domainDetailsInFlightRef = useRef<Set<string>>(new Set());++ useEffect(() => {+ proxyStatsRef.current = proxyStats;+ }, [proxyStats]);++ useEffect(() => {+ domainDetailsRef.current = domainDetails;+ }, [domainDetails]);useEffect(() => {// Context switch (backend/device/proxy/rule binding change): collapse.@@ -88,22 +104,26 @@ export function IPStatsTable({setDomainDetails({});setProxyStatsLoading(null);setDomainDetailsLoading(null);+ proxyStatsInFlightRef.current.clear();+ domainDetailsInFlightRef.current.clear();}, [activeBackendId, sourceIP, sourceChain, richExpand]);const fetchProxyStats = useCallback(async (ip: string, options?: { force?: boolean; background?: boolean }) => {const force = options?.force ?? false;const background = options?.background ?? false;- const hasCached = !!proxyStats[ip];+ const hasCached = !!proxyStatsRef.current[ip];if (!richExpand || (!force && hasCached)) return;+ if (proxyStatsInFlightRef.current.has(ip)) return;if (!background || !hasCached) {setProxyStatsLoading(ip);}+ proxyStatsInFlightRef.current.add(ip);try {const stats = await api.getIPProxyStats(ip,activeBackendId,- timeRange,+ stableTimeRange,sourceIP,sourceChain,);@@ -112,28 +132,29 @@ export function IPStatsTable({console.error(`Failed to fetch proxy stats for ${ip}:`, err);setProxyStats((prev) => ({ ...prev, [ip]: [] }));} finally {- if (proxyStatsLoading === ip) {- setProxyStatsLoading(null);- }+ proxyStatsInFlightRef.current.delete(ip);+ setProxyStatsLoading((prev) => (prev === ip ? null : prev));}},- [proxyStats, activeBackendId, timeRange, sourceIP, sourceChain, richExpand, proxyStatsLoading],+ [activeBackendId, stableTimeRange, sourceIP, sourceChain, richExpand],);const fetchDomainDetails = useCallback(async (ip: string, options?: { force?: boolean; background?: boolean }) => {const force = options?.force ?? false;const background = options?.background ?? false;- const hasCached = !!domainDetails[ip];+ const hasCached = !!domainDetailsRef.current[ip];if (!richExpand || (!force && hasCached)) return;+ if (domainDetailsInFlightRef.current.has(ip)) return;if (!background || !hasCached) {setDomainDetailsLoading(ip);}+ domainDetailsInFlightRef.current.add(ip);try {const details = await api.getIPDomainDetails(ip,activeBackendId,- timeRange,+ stableTimeRange,sourceIP,undefined,sourceChain,@@ -143,12 +164,11 @@ export function IPStatsTable({console.error(`Failed to fetch domain details for ${ip}:`, err);setDomainDetails((prev) => ({ ...prev, [ip]: [] }));} finally {- if (domainDetailsLoading === ip) {- setDomainDetailsLoading(null);- }+ domainDetailsInFlightRef.current.delete(ip);+ setDomainDetailsLoading((prev) => (prev === ip ? null : prev));}},- [domainDetails, activeBackendId, timeRange, sourceIP, sourceChain, richExpand, domainDetailsLoading],+ [activeBackendId, stableTimeRange, sourceIP, sourceChain, richExpand],);useEffect(() => {@@ -161,7 +181,7 @@ export function IPStatsTable({if (!expandedIP || !richExpand) return;fetchProxyStats(expandedIP, { force: true, background: true });fetchDomainDetails(expandedIP, { force: true, background: true });- }, [timeRange?.start, timeRange?.end, expandedIP, richExpand, fetchProxyStats, fetchDomainDetails]);+ }, [timeRange?.start, timeRange?.end, richExpand, fetchProxyStats, fetchDomainDetails]);const handleSort = (key: IPSortKey) => {if (sortKey === key) {@@ -176,10 +196,6 @@ export function IPStatsTable({const toggleExpand = (ip: string) => {const newExpanded = expandedIP === ip ? null : ip;setExpandedIP(newExpanded);- if (newExpanded && richExpand) {- fetchProxyStats(newExpanded);- fetchDomainDetails(newExpanded);- }};const SortIcon = ({ column }: { column: IPSortKey }) => {diff --git a/apps/web/components/top-domains-chart.tsx b/apps/web/components/top-domains-chart.tsxindex fad4040..b548c81 100644--- a/apps/web/components/top-domains-chart.tsx+++ b/apps/web/components/top-domains-chart.tsx@@ -105,14 +105,6 @@ export function TopDomainsChart({ activeBackendId, timeRange }: TopDomainsChartPfetchData();}, [fetchData]);- // Auto-refresh every 5 seconds- useEffect(() => {- const interval = setInterval(() => {- fetchData();- }, 5000);- return () => clearInterval(interval);- }, [fetchData]);-useEffect(() => {if (!containerRef.current) return;diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.tsindex 663f9a7..e5862fc 100644--- a/apps/web/lib/api.ts+++ b/apps/web/lib/api.ts@@ -41,8 +41,32 @@ function resolveApiBase(): string {const API_BASE = resolveApiBase();const DETAIL_FETCH_LIMIT = 5000;+const GET_DEDUP_TTL_MS = 250;+const inflightGetRequests = new Map<string, Promise<unknown>>();+const recentGetResponses = new Map<string, { expiresAt: number; data: unknown }>();++function pruneRecentGetResponses(now: number) {+ if (recentGetResponses.size <= 200) return;+ for (const [key, entry] of recentGetResponses) {+ if (entry.expiresAt <= now) {+ recentGetResponses.delete(key);+ }+ }+}async function fetchJson<T>(url: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE' = 'GET', body?: any): Promise<T> {+ if (method === "GET") {+ const now = Date.now();+ const recent = recentGetResponses.get(url);+ if (recent && recent.expiresAt > now) {+ return recent.data as T;+ }+ const inflight = inflightGetRequests.get(url);+ if (inflight) {+ return inflight as Promise<T>;+ }+ }+const options: RequestInit = {method,headers: {},@@ -56,13 +80,33 @@ async function fetchJson<T>(url: string, method: 'GET' | 'POST' | 'PUT' | 'DELEToptions.body = JSON.stringify(body);}- console.log(`[API] ${method} ${url}`);- const res = await fetch(url, options);- if (!res.ok) {- console.error(`[API] Error ${res.status}: ${url}`);- throw new Error(`API error: ${res.status}`);+ const requestPromise = (async () => {+ console.log(`[API] ${method} ${url}`);+ const res = await fetch(url, options);+ if (!res.ok) {+ console.error(`[API] Error ${res.status}: ${url}`);+ throw new Error(`API error: ${res.status}`);+ }+ const json = await res.json();+ if (method === "GET") {+ const now = Date.now();+ recentGetResponses.set(url, { data: json, expiresAt: now + GET_DEDUP_TTL_MS });+ pruneRecentGetResponses(now);+ }+ return json as T;+ })();++ if (method === "GET") {+ inflightGetRequests.set(url, requestPromise as Promise<unknown>);+ }++ try {+ return await requestPromise;+ } finally {+ if (method === "GET") {+ inflightGetRequests.delete(url);+ }}- return res.json();}export interface TimeRange {diff --git a/package.json b/package.jsonindex cd1f524..747d7c7 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "clash-master",- "version": "1.1.1",+ "version": "1.1.2","private": true,"workspaces": ["apps/*",