Skip to content

A modern and elegant dashboard for network traffic visualization and analysis.

feat: Implement backend health monitoring and visualization on the dashboard.

luolei27a62cb816c9
diff --git a/apps/collector/src/database/repositories/health.repository.ts b/apps/collector/src/database/repositories/health.repository.ts
new file mode 100644
index 0000000..58bf869
--- /dev/null
+++ b/apps/collector/src/database/repositories/health.repository.ts
@@ -0,0 +1,91 @@
+/**
+ * Health Repository
+ *
+ * Persists periodic health-check results for each backend.
+ * One row per (backend_id, minute), keyed on truncated ISO-8601 UTC minute.
+ */
+import type Database from 'better-sqlite3';
+
+export type HealthStatus = 'healthy' | 'unhealthy' | 'unknown';
+
+export interface HealthLogRow {
+ backend_id: number;
+ minute: string;
+ status: HealthStatus;
+ latency_ms: number | null;
+ message: string | null;
+}
+
+export class HealthRepository {
+ constructor(private db: Database.Database) {}
+
+ /**
+ * Write (upsert) a health log entry for the current minute.
+ * Multiple checks within the same minute are overwritten — last write wins.
+ */
+ writeHealthLog(
+ backendId: number,
+ minute: string,
+ status: HealthStatus,
+ latencyMs?: number,
+ message?: string,
+ ): void {
+ this.db.prepare(`
+ INSERT INTO backend_health_logs (backend_id, minute, status, latency_ms, message)
+ VALUES (?, ?, ?, ?, ?)
+ ON CONFLICT(backend_id, minute) DO UPDATE SET
+ status = excluded.status,
+ latency_ms = excluded.latency_ms,
+ message = excluded.message
+ `).run(backendId, minute, status, latencyMs ?? null, message ?? null);
+ }
+
+ /**
+ * Return health log rows for a single backend within the given UTC ISO range.
+ */
+ getHealthHistory(
+ backendId: number,
+ fromISO: string,
+ toISO: string,
+ ): HealthLogRow[] {
+ return this.db.prepare(`
+ SELECT backend_id, minute, status, latency_ms, message
+ FROM backend_health_logs
+ WHERE backend_id = ? AND minute >= ? AND minute <= ?
+ ORDER BY minute ASC
+ `).all(backendId, fromISO, toISO) as HealthLogRow[];
+ }
+
+ /**
+ * Return health log rows for all backends within the given UTC ISO range.
+ */
+ getHealthHistoryAll(fromISO: string, toISO: string): HealthLogRow[] {
+ return this.db.prepare(`
+ SELECT backend_id, minute, status, latency_ms, message
+ FROM backend_health_logs
+ WHERE minute >= ? AND minute <= ?
+ ORDER BY backend_id ASC, minute ASC
+ `).all(fromISO, toISO) as HealthLogRow[];
+ }
+
+ /**
+ * Delete health log rows older than retentionDays for all backends.
+ */
+ pruneOldLogs(retentionDays: number): void {
+ const cutoff = new Date(Date.now() - retentionDays * 86_400_000)
+ .toISOString()
+ .slice(0, 16); // "YYYY-MM-DDTHH:MM"
+ this.db.prepare(`
+ DELETE FROM backend_health_logs WHERE minute < ?
+ `).run(cutoff);
+ }
+
+ /**
+ * Delete all health logs for a specific backend (called on backend data clear).
+ */
+ deleteByBackend(backendId: number): void {
+ this.db.prepare(
+ `DELETE FROM backend_health_logs WHERE backend_id = ?`,
+ ).run(backendId);
+ }
+}
diff --git a/apps/collector/src/database/repositories/index.ts b/apps/collector/src/database/repositories/index.ts
index 78c8980..b39a162 100644
--- a/apps/collector/src/database/repositories/index.ts
+++ b/apps/collector/src/database/repositories/index.ts
@@ -18,3 +18,4 @@ export { RuleRepository } from './rule.repository.js';
export { IPRepository } from './ip.repository.js';
export { ConfigRepository, type GeoLookupConfig, type GeoLookupProvider } from './config.repository.js';
export { TrafficWriterRepository, type TrafficUpdate } from './traffic-writer.repository.js';
+export { HealthRepository, type HealthLogRow, type HealthStatus } from './health.repository.js';
diff --git a/apps/collector/src/database/schema.ts b/apps/collector/src/database/schema.ts
index cd7591d..0517946 100644
--- a/apps/collector/src/database/schema.ts
+++ b/apps/collector/src/database/schema.ts
@@ -425,6 +425,19 @@ export const SCHEMA = {
FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
);
`,
+
+ // Backend health check log - one row per minute per backend
+ BACKEND_HEALTH_LOGS: `
+ CREATE TABLE IF NOT EXISTS backend_health_logs (
+ backend_id INTEGER NOT NULL,
+ minute TEXT NOT NULL,
+ status TEXT NOT NULL,
+ latency_ms INTEGER,
+ message TEXT,
+ PRIMARY KEY (backend_id, minute),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `,
} as const;
// Index definitions
@@ -488,6 +501,9 @@ export const INDEXES = [
// Agent heartbeat indexes
`CREATE INDEX IF NOT EXISTS idx_agent_heartbeats_last_seen ON agent_heartbeats(last_seen);`,
+ // Backend health log indexes
+ `CREATE INDEX IF NOT EXISTS idx_backend_health_logs_backend_minute ON backend_health_logs(backend_id, minute);`,
+
// Surge policy cache indexes
`CREATE INDEX IF NOT EXISTS idx_surge_policy_backend ON surge_policy_cache(backend_id);`,
`CREATE INDEX IF NOT EXISTS idx_surge_policy_updated ON surge_policy_cache(updated_at);`,
@@ -539,6 +555,7 @@ export function getAllSchemaStatements(): string[] {
SCHEMA.BACKEND_CONFIGS,
SCHEMA.AGENT_HEARTBEATS,
SCHEMA.AGENT_SNAPSHOTS,
+ SCHEMA.BACKEND_HEALTH_LOGS,
SCHEMA.APP_CONFIG,
SCHEMA.SURGE_POLICY_CACHE,
SCHEMA.AUTH_CONFIG,
diff --git a/apps/collector/src/modules/backend/backend.controller.ts b/apps/collector/src/modules/backend/backend.controller.ts
index 81dd53a..946765f 100644
--- a/apps/collector/src/modules/backend/backend.controller.ts
+++ b/apps/collector/src/modules/backend/backend.controller.ts
@@ -183,6 +183,49 @@ const backendController: FastifyPluginAsync = async (fastify: FastifyInstance):
return result;
});
+ // Get health history for all (or a specific) backend
+ fastify.get<{ Querystring: { from?: string; to?: string; backendId?: string } }>(
+ '/health/history',
+ async (request) => {
+ const { from, to, backendId } = request.query;
+
+ // Default to last 24 hours if not provided
+ const toISO = (to ?? new Date().toISOString()).slice(0, 16);
+ const fromISO = (from ?? new Date(Date.now() - 24 * 3600_000).toISOString()).slice(0, 16);
+
+ const parsedBackendId = backendId ? parseInt(backendId, 10) : undefined;
+ const rows = service.getHealthHistory(fromISO, toISO, parsedBackendId);
+
+ // Group by backend and enrich with backend name
+ const backends = service.getAllBackends();
+ const backendMap = new Map(backends.map((b) => [b.id, b.name]));
+
+ const grouped = new Map<number, {
+ backendId: number;
+ backendName: string;
+ points: Array<{ time: string; status: string; latency_ms: number | null; message: string | null }>;
+ }>();
+
+ for (const row of rows) {
+ if (!grouped.has(row.backend_id)) {
+ grouped.set(row.backend_id, {
+ backendId: row.backend_id,
+ backendName: backendMap.get(row.backend_id) ?? `Backend ${row.backend_id}`,
+ points: [],
+ });
+ }
+ grouped.get(row.backend_id)!.points.push({
+ time: row.minute,
+ status: row.status,
+ latency_ms: row.latency_ms,
+ message: row.message,
+ });
+ }
+
+ return Array.from(grouped.values());
+ },
+ );
+
// Clear all data for a specific backend
fastify.post<{ Params: BackendParams }>('/:id/clear-data', async (request, reply) => {
if (fastify.authService.isShowcaseMode()) {
diff --git a/apps/collector/src/modules/backend/backend.service.ts b/apps/collector/src/modules/backend/backend.service.ts
index 97c282a..e766a3b 100644
--- a/apps/collector/src/modules/backend/backend.service.ts
+++ b/apps/collector/src/modules/backend/backend.service.ts
@@ -22,6 +22,7 @@ import { loadClickHouseConfig, runClickHouseQuery } from '../clickhouse/clickhou
import type { ClickHouseConfig } from '../clickhouse/clickhouse.config.js';
import type { AuthService } from '../auth/auth.service.js';
+import type { HealthLogRow } from '../../database/repositories/health.repository.js';
/**
* Mask URL for showcase mode - hides host, port, credentials
@@ -94,12 +95,20 @@ export class BackendService {
}
/**
- * Run health checks for all listening backends
+ * Truncate a timestamp to the current UTC minute string "YYYY-MM-DDTHH:MM"
+ */
+ private toMinuteKey(ts: number): string {
+ return new Date(ts).toISOString().slice(0, 16);
+ }
+
+ /**
+ * Run health checks for all listening backends and persist results.
*/
private async runHealthChecks(): Promise<void> {
const backends = this.db.getListeningBackends();
const now = Date.now();
-
+ const minute = this.toMinuteKey(now);
+
for (const backend of backends) {
try {
if (isAgentBackendUrl(backend.url)) {
@@ -110,6 +119,7 @@ export class BackendService {
console.log(`[BackendService] Health check for ${backend.name}: ${health.status}${health.message ? ` - ${health.message}` : ''}`);
}
this.healthStatus.set(backend.id, health);
+ this.db.repos.health.writeHealthLog(backend.id, minute, health.status, undefined, health.message);
continue;
}
@@ -120,21 +130,28 @@ export class BackendService {
type: backend.type,
});
const latency = Date.now() - startTime;
-
+
const health: BackendHealthInfo = {
status: result.success ? 'healthy' : 'unhealthy',
lastChecked: Date.now(),
message: result.message,
latency: result.success ? latency : undefined,
};
-
+
// Only log when status changes or on failure
const prevHealth = this.healthStatus.get(backend.id);
if (!result.success || prevHealth?.status !== health.status) {
console.log(`[BackendService] Health check for ${backend.name}: ${health.status}${result.message ? ` - ${result.message}` : ''}`);
}
-
+
this.healthStatus.set(backend.id, health);
+ this.db.repos.health.writeHealthLog(
+ backend.id,
+ minute,
+ health.status,
+ result.success ? latency : undefined,
+ result.message,
+ );
} catch (error) {
const health: BackendHealthInfo = {
status: 'unhealthy',
@@ -142,11 +159,22 @@ export class BackendService {
message: error instanceof Error ? error.message : 'Health check failed',
};
this.healthStatus.set(backend.id, health);
+ this.db.repos.health.writeHealthLog(backend.id, minute, 'unhealthy', undefined, health.message);
console.warn(`[BackendService] Health check error for ${backend.name}:`, error);
}
}
}
+ /**
+ * Get health history for all backends (or a single one) over the given UTC ISO range.
+ */
+ getHealthHistory(fromISO: string, toISO: string, backendId?: number): HealthLogRow[] {
+ if (backendId !== undefined) {
+ return this.db.repos.health.getHealthHistory(backendId, fromISO, toISO);
+ }
+ return this.db.repos.health.getHealthHistoryAll(fromISO, toISO);
+ }
+
/**
* Attach health status to backend response
*/
@@ -350,6 +378,7 @@ export class BackendService {
async clearBackendData(id: number): Promise<{ message: string }> {
await this.clearClickHouseBackendData(id);
this.db.deleteBackendData(id);
+ this.db.repos.health.deleteByBackend(id);
// Also clear realtime cache
this.realtimeStore.clearBackend(id);
this.onBackendDataCleared?.(id);
diff --git a/apps/collector/src/modules/db/db.ts b/apps/collector/src/modules/db/db.ts
index 412caf3..db67eae 100644
--- a/apps/collector/src/modules/db/db.ts
+++ b/apps/collector/src/modules/db/db.ts
@@ -18,6 +18,7 @@ import {
TrafficWriterRepository,
DomainRepository,
BackendRepository,
+ HealthRepository,
} from '../../database/repositories/index.js';
export interface TrafficUpdate {
@@ -96,6 +97,7 @@ export class StatsDatabase {
trafficWriter: TrafficWriterRepository;
domain: DomainRepository;
backend: BackendRepository;
+ health: HealthRepository;
};
constructor(dbPath = 'stats.db') {
@@ -116,6 +118,7 @@ export class StatsDatabase {
trafficWriter: new TrafficWriterRepository(this.db),
domain: new DomainRepository(this.db),
backend: new BackendRepository(this.db),
+ health: new HealthRepository(this.db),
};
}
diff --git a/apps/web/app/[locale]/dashboard/components/content/index.tsx b/apps/web/app/[locale]/dashboard/components/content/index.tsx
index 0651513..8f53dbf 100644
--- a/apps/web/app/[locale]/dashboard/components/content/index.tsx
+++ b/apps/web/app/[locale]/dashboard/components/content/index.tsx
@@ -6,12 +6,13 @@ import {
keepPreviousData,
useQuery,
} from "@tanstack/react-query";
-import { Activity, BarChart3, Link2 } from "lucide-react";
+import { BarChart3, Link2 } from "lucide-react";
import { StatsCards, TopDomainsChart } from "@/components/features/stats";
import { OverviewTab } from "@/components/overview";
import { InteractiveProxyStats } from "@/components/features/proxies";
import { InteractiveDeviceStats } from "@/components/features/devices";
import { InteractiveRuleStats } from "@/components/features/rules";
+import { HealthContent } from "@/components/features/health";
import { WorldTrafficMap, CountryTrafficList } from "@/components/features/countries";
import { DomainsTable, IPsTable } from "@/components/features/stats/table";
import { Button } from "@/components/ui/button";
@@ -309,7 +310,6 @@ const NetworkContent = memo(function NetworkContent() {
return (
<div className="space-y-6">
<div className="p-12 text-center text-muted-foreground border rounded-xl">
- <Activity className="w-12 h-12 mx-auto mb-4 opacity-50" />
<p>{t("comingSoon")}</p>
</div>
</div>
@@ -386,6 +386,8 @@ export function Content({
);
case "network":
return <NetworkContent />;
+ case "health":
+ return <HealthContent timeRange={timeRange} />;
default:
return (
<OverviewContent
diff --git a/apps/web/app/[locale]/dashboard/components/header/index.tsx b/apps/web/app/[locale]/dashboard/components/header/index.tsx
index 72df823..cb7dcda 100644
--- a/apps/web/app/[locale]/dashboard/components/header/index.tsx
+++ b/apps/web/app/[locale]/dashboard/components/header/index.tsx
@@ -42,7 +42,7 @@ import { Switch } from "@/components/ui/switch";
import { TimeRangePicker, LanguageSwitcher, ThemeToggle, ClientOnly } from "@/components/common";
import { cn } from "@/lib/utils";
import type { TimeRange } from "@/lib/api";
-import type { BackendStatus, TimePreset } from "@/lib/types/dashboard";
+import type { BackendStatus, TabId, TimePreset } from "@/lib/types/dashboard";
interface BackendHealth {
status: 'healthy' | 'unhealthy' | 'unknown';
@@ -95,6 +95,9 @@ interface HeaderProps {
pathname: string;
onNavigate: (path: string) => void;
+ // Active tab (to conditionally show time picker)
+ activeTab?: TabId;
+
// Loading states
isLoading: boolean;
isTransitioning?: boolean;
@@ -124,11 +127,13 @@ export function Header({
locale,
pathname,
onNavigate,
+ activeTab,
isLoading,
isTransitioning,
backendT,
dashboardT,
}: HeaderProps) {
+ const showTimeRangePicker = true; // All tabs use the global time range picker
const { logout, authState } = useAuth();
const { data: authQueryState } = useAuthState(); // Added
const isShowcase = authQueryState?.showcaseMode ?? false; // Added
@@ -353,13 +358,15 @@ export function Header({
{/* Desktop: Language & Theme */}
<div className="hidden sm:flex items-center gap-1">
- <ClientOnly fallback={<div className="h-9 w-[152px] bg-secondary/45 rounded-xl" />}>
- <TimeRangePicker
- value={timeRange}
- onChange={onTimeRangeChange}
- showcaseMode={isShowcase}
- />
- </ClientOnly>
+ {showTimeRangePicker && (
+ <ClientOnly fallback={<div className="h-9 w-[152px] bg-secondary/45 rounded-xl" />}>
+ <TimeRangePicker
+ value={timeRange}
+ onChange={onTimeRangeChange}
+ showcaseMode={isShowcase}
+ />
+ </ClientOnly>
+ )}
<LanguageSwitcher />
<ThemeToggle />
@@ -377,16 +384,18 @@ export function Header({
</div>
{/* Mobile: Time range picker */}
- <div className="sm:hidden">
- <ClientOnly fallback={<div className="h-9 w-[122px] bg-secondary/45 rounded-xl" />}>
- <TimeRangePicker
- value={timeRange}
- onChange={onTimeRangeChange}
- className="w-[122px]"
- showcaseMode={isShowcase}
- />
- </ClientOnly>
- </div>
+ {showTimeRangePicker && (
+ <div className="sm:hidden">
+ <ClientOnly fallback={<div className="h-9 w-[122px] bg-secondary/45 rounded-xl" />}>
+ <TimeRangePicker
+ value={timeRange}
+ onChange={onTimeRangeChange}
+ className="w-[122px]"
+ showcaseMode={isShowcase}
+ />
+ </ClientOnly>
+ </div>
+ )}
{/* Mobile: Backend warning in top actions */}
{backendStatus === "unhealthy" && (
diff --git a/apps/web/app/[locale]/dashboard/page.tsx b/apps/web/app/[locale]/dashboard/page.tsx
index 4499026..270a7eb 100644
--- a/apps/web/app/[locale]/dashboard/page.tsx
+++ b/apps/web/app/[locale]/dashboard/page.tsx
@@ -73,6 +73,7 @@ export default function DashboardPage() {
listeningBackends={listeningBackends}
backendStatus={backendStatus}
backendStatusHint={backendStatusHint}
+ activeTab={activeTab}
timeRange={timeRange}
onTimeRangeChange={handleTimeRangeChange}
autoRefresh={autoRefresh}
diff --git a/apps/web/components/features/health/backend-health-chart.tsx b/apps/web/components/features/health/backend-health-chart.tsx
new file mode 100644
index 0000000..3c20ec2
--- /dev/null
+++ b/apps/web/components/features/health/backend-health-chart.tsx
@@ -0,0 +1,500 @@
+"use client";
+
+import React, { useMemo } from "react";
+import {
+ AreaChart,
+ Area,
+ XAxis,
+ YAxis,
+ Tooltip,
+ ResponsiveContainer,
+ CartesianGrid,
+ ReferenceArea,
+} from "recharts";
+import { Activity, Clock, Loader2 } from "lucide-react";
+import { useTranslations } from "next-intl";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { cn } from "@/lib/utils";
+import type { BackendHealthHistory, BackendHealthPoint } from "@/lib/api";
+
+type HealthStatus = "healthy" | "unhealthy" | "unknown";
+
+// ─── helpers ────────────────────────────────────────────────────────────────
+
+function toMinuteKey(iso: string): string {
+ return iso.slice(0, 16);
+}
+
+function formatLabel(cursor: Date, spanMs: number): string {
+ if (spanMs <= 48 * 3_600_000) {
+ // ≤ 48 h → time only (covers 1 h / 6 h / 12 h / 24 h / 2 d presets)
+ // Matches Overview's minute-granularity axis format exactly
+ return cursor.toLocaleTimeString(undefined, {
+ hour: "2-digit",
+ minute: "2-digit",
+ hour12: false,
+ });
+ }
+ if (spanMs <= 7 * 86_400_000) {
+ // 2 d – 7 d with hourly buckets → need the date visible too
+ return cursor.toLocaleString(undefined, {
+ month: "short",
+ day: "numeric",
+ hour: "2-digit",
+ minute: "2-digit",
+ hour12: false,
+ });
+ }
+ // > 7 d → date only, same as Overview day-granularity axis
+ return cursor.toLocaleDateString(undefined, { month: "short", day: "numeric" });
+}
+
+interface Slot {
+ time: string;
+ timeLabel: string;
+ status: HealthStatus | "gap";
+ /** null breaks the line (gap / outage) */
+ latency: number | null;
+ /** always 1 (online) or null (offline/gap) — used when no latency data available */
+ online: number | null;
+ latency_ms: number | null;
+ message: string | null;
+}
+
+function buildSlots(
+ from: Date,
+ to: Date,
+ points: BackendHealthPoint[],
+ bucketMinutes: number,
+): Slot[] {
+ // Build minute-key lookup
+ const lookup = new Map<string, BackendHealthPoint>();
+ for (const p of points) {
+ lookup.set(toMinuteKey(p.time), p);
+ }
+
+ const slots: Slot[] = [];
+ const cursor = new Date(from);
+ const spanMs = to.getTime() - from.getTime();
+
+ while (cursor <= to) {
+ const bucketStart = cursor.toISOString().slice(0, 16);
+ const bucketEnd = new Date(cursor.getTime() + bucketMinutes * 60_000)
+ .toISOString()
+ .slice(0, 16);
+
+ // Collect all raw points that fall within this bucket
+ const bucketPoints: BackendHealthPoint[] = [];
+ const tmp = new Date(cursor);
+ for (let m = 0; m < bucketMinutes; m++) {
+ const key = tmp.toISOString().slice(0, 16);
+ const pt = lookup.get(key);
+ if (pt) bucketPoints.push(pt);
+ tmp.setMinutes(tmp.getMinutes() + 1);
+ }
+
+ const timeLabel = formatLabel(new Date(cursor), spanMs);
+
+ if (bucketPoints.length === 0) {
+ slots.push({
+ time: bucketStart,
+ timeLabel,
+ status: "gap",
+ latency: null,
+ online: null,
+ latency_ms: null,
+ message: null,
+ });
+ } else {
+ // Worst-case status for the bucket
+ const hasUnhealthy = bucketPoints.some((p) => p.status === "unhealthy");
+ const hasUnknown = bucketPoints.some((p) => p.status === "unknown");
+ const status: HealthStatus = hasUnhealthy ? "unhealthy" : hasUnknown ? "unknown" : "healthy";
+
+ // Average latency
+ const lats = bucketPoints
+ .filter((p) => p.latency_ms !== null)
+ .map((p) => p.latency_ms as number);
+ const avgLatency = lats.length > 0
+ ? Math.round(lats.reduce((a, b) => a + b, 0) / lats.length)
+ : null;
+
+ // Last message
+ const lastMsg = bucketPoints[bucketPoints.length - 1].message ?? null;
+
+ slots.push({
+ time: bucketStart,
+ timeLabel,
+ status,
+ // Latency-line: only draw when healthy; null during outage breaks the area
+ latency: status === "healthy" ? avgLatency : null,
+ // Binary online-line: 1 when healthy, null otherwise (for agent-mode backends)
+ online: status === "healthy" ? 1 : null,
+ latency_ms: avgLatency,
+ message: lastMsg,
+ });
+ }
+
+ cursor.setMinutes(cursor.getMinutes() + bucketMinutes);
+ void bucketEnd; // suppress unused-var
+ }
+
+ return slots;
+}
+
+/**
+ * Only gaps that sit *between* the first and last recorded data point are
+ * treated as downtime ("unhealthy"). Leading / trailing gaps — time slots
+ * before monitoring started or beyond the last check — stay as "gap" so they
+ * render as blank space, not as a fault region.
+ *
+ * The original `slots` array (used for stats / gap counting) is never mutated.
+ */
+function resolveGapSlots(slots: Slot[]): Slot[] {
+ const firstData = slots.findIndex((s) => s.status !== "gap");
+ if (firstData === -1) return slots; // no data at all
+
+ let lastData = -1;
+ for (let i = slots.length - 1; i >= 0; i--) {
+ if (slots[i].status !== "gap") { lastData = i; break; }
+ }
+
+ return slots.map((s, i) => {
+ if (s.status !== "gap") return s;
+ // Interior gap → treat as downtime
+ if (i > firstData && i < lastData) return { ...s, status: "unhealthy" as const };
+ // Leading / trailing gap → leave blank
+ return s;
+ });
+}
+
+/** Find contiguous spans of a non-healthy state for ReferenceArea shading.
+ * x1/x2 use `slot.time` (unique UTC ISO minute string) so that duplicate
+ * timeLabels in a 24-hour view (where the first and last label are identical)
+ * don't cause recharts to misposition the shaded regions.
+ */
+function buildRefSpans(
+ slots: Slot[],
+): Array<{ x1: string; x2: string; type: "unhealthy" | "unknown" | "gap" }> {
+ const spans: ReturnType<typeof buildRefSpans> = [];
+ let spanStart: string | null = null;
+ let spanType: "unhealthy" | "unknown" | "gap" | null = null;
+
+ for (let i = 0; i < slots.length; i++) {
+ const s = slots[i];
+ const isProblematic = s.status !== "healthy";
+
+ if (isProblematic && spanStart === null) {
+ spanStart = s.time;
+ spanType = s.status as "unhealthy" | "unknown" | "gap";
+ } else if (!isProblematic && spanStart !== null) {
+ spans.push({ x1: spanStart, x2: slots[i - 1].time, type: spanType! });
+ spanStart = null;
+ spanType = null;
+ } else if (isProblematic && spanType !== null && s.status !== spanType) {
+ // status type changed within a problematic run — split span
+ spans.push({ x1: spanStart!, x2: slots[i - 1].time, type: spanType });
+ spanStart = s.time;
+ spanType = s.status as "unhealthy" | "unknown" | "gap";
+ }
+ }
+ if (spanStart !== null) {
+ spans.push({ x1: spanStart, x2: slots[slots.length - 1].time, type: spanType! });
+ }
+ return spans;
+}
+
+// ─── component ──────────────────────────────────────────────────────────────
+
+interface BackendHealthChartProps {
+ history: BackendHealthHistory;
+ from: Date;
+ to: Date;
+ bucketMinutes?: number;
+}
+
+export const BackendHealthChart = React.memo(function BackendHealthChart({
+ history,
+ from,
+ to,
+ bucketMinutes = 1,
+}: BackendHealthChartProps) {
+ const t = useTranslations("health");
+ const spanMs = to.getTime() - from.getTime();
+
+ const slots = useMemo(
+ () => buildSlots(from, to, history.points, bucketMinutes),
+ [from, to, history.points, bucketMinutes],
+ );
+
+ const refSpans = useMemo(() => buildRefSpans(resolveGapSlots(slots)), [slots]);
+
+ // Map from unique `time` key → display label, used as XAxis tickFormatter so
+ // the axis shows readable labels while x1/x2 reference unique time strings.
+ const labelMap = useMemo(
+ () => new Map(slots.map((s) => [s.time, s.timeLabel])),
+ [slots],
+ );
+
+ const stats = useMemo(() => {
+ const checked = slots.filter((s) => s.status !== "gap");
+ const healthy = checked.filter((s) => s.status === "healthy").length;
+ const uptimePct = checked.length > 0 ? (healthy / checked.length) * 100 : null;
+ const lats = checked
+ .filter((s) => s.latency_ms !== null)
+ .map((s) => s.latency_ms as number);
+ const avgLatency = lats.length > 0
+ ? Math.round(lats.reduce((a, b) => a + b, 0) / lats.length)
+ : null;
+ const maxLatency = lats.length > 0 ? Math.max(...lats) : null;
+ const gaps = slots.filter((s) => s.status === "gap").length;
+ return { uptimePct, avgLatency, maxLatency, gaps };
+ }, [slots]);
+
+ // Does this backend emit latency data? (direct mode)
+ const hasLatency = useMemo(
+ () => history.points.some((p) => p.latency_ms !== null),
+ [history.points],
+ );
+
+ // The Y-axis dataKey we'll plot
+ const dataKey = hasLatency ? "latency" : "online";
+
+ const currentStatus =
+ history.points.length > 0
+ ? history.points[history.points.length - 1].status
+ : "unknown";
+
+ const statusDotClass =
+ currentStatus === "healthy"
+ ? "bg-emerald-500"
+ : currentStatus === "unhealthy"
+ ? "bg-rose-500"
+ : "bg-slate-400";
+
+ // ── Tooltip ────────────────────────────────────────────────────────────────
+ const CustomTooltip = React.useCallback(
+ ({ active, payload }: any) => {
+ if (!active || !payload?.length) return null;
+ const slot: Slot = payload[0].payload;
+
+ // Parse the stored ISO minute string as UTC → local, then format like Overview
+ const slotDate = new Date(
+ slot.time.endsWith("Z") ? slot.time : slot.time + "Z",
+ );
+ const tooltipTitle =
+ spanMs > 7 * 86_400_000
+ ? slotDate.toLocaleDateString(undefined, {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ })
+ : slotDate.toLocaleString(undefined, {
+ month: "short",
+ day: "numeric",
+ hour: "2-digit",
+ minute: "2-digit",
+ });
+
+ const statusLabel =
+ slot.status === "healthy"
+ ? t("statusHealthy")
+ : slot.status === "unhealthy"
+ ? t("statusUnhealthy")
+ : slot.status === "unknown"
+ ? t("statusUnknown")
+ : t("noData");
+
+ const statusClass =
+ slot.status === "healthy"
+ ? "text-emerald-500"
+ : slot.status === "unhealthy"
+ ? "text-rose-500"
+ : "text-slate-400";
+
+ return (
+ <div className="bg-popover border border-border rounded-lg p-3 shadow-lg text-xs space-y-1 min-w-[130px]">
+ <p className="text-muted-foreground font-medium">{tooltipTitle}</p>
+ <p className={cn("font-semibold", statusClass)}>{statusLabel}</p>
+ {slot.latency_ms !== null && (
+ <p className="text-muted-foreground flex items-center gap-1">
+ <Clock className="w-3 h-3" />
+ <span className="tabular-nums font-medium">{slot.latency_ms}ms</span>
+ </p>
+ )}
+ {slot.message && slot.status !== "healthy" && (
+ <p className="text-muted-foreground max-w-[200px] truncate opacity-80">
+ {slot.message}
+ </p>
+ )}
+ </div>
+ );
+ },
+ [t, spanMs],
+ );
+
+ // ── Skeleton ───────────────────────────────────────────────────────────────
+ if (slots.length === 0) {
+ return (
+ <div className="space-y-3">
+ <div className="flex items-center gap-2">
+ <span className={cn("inline-flex w-2 h-2 rounded-full shrink-0", statusDotClass)} />
+ <span className="font-medium text-sm truncate">{history.backendName}</span>
+ </div>
+ <div className="h-[180px] w-full bg-muted/20 rounded-xl animate-pulse flex items-center justify-center">
+ <Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
+ </div>
+ </div>
+ );
+ }
+
+ // ── Render ─────────────────────────────────────────────────────────────────
+ return (
+ <div className="space-y-1">
+ {/* Title row — same pattern as TrafficTrendChart */}
+ <div className="flex items-center justify-between flex-wrap gap-2">
+ <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2">
+ <Activity className="w-4 h-4" />
+ {history.backendName}
+ <span className={cn("inline-flex w-2 h-2 rounded-full shrink-0", statusDotClass)} />
+ </CardTitle>
+ </div>
+
+ {/* Stats row — desktop inline / mobile cards */}
+ {/* Mobile */}
+ <div className="grid grid-cols-3 gap-2 lg:hidden">
+ {stats.uptimePct !== null && (
+ <div className="flex flex-col items-center py-1.5 px-1 rounded-md bg-secondary/50 border border-border/50">
+ <span className="text-[9px] text-muted-foreground">{t("uptime")}</span>
+ <span className={cn("text-xs font-bold tabular-nums",
+ stats.uptimePct >= 99 ? "text-emerald-500" : stats.uptimePct >= 90 ? "text-amber-500" : "text-rose-500")}>
+ {stats.uptimePct.toFixed(1)}%
+ </span>
+ </div>
+ )}
+ {stats.avgLatency !== null && (
+ <div className="flex flex-col items-center py-1.5 px-1 rounded-md bg-secondary/50 border border-border/50">
+ <span className="text-[9px] text-muted-foreground">{t("avgLatency")}</span>
+ <span className="text-xs font-semibold tabular-nums">{stats.avgLatency}ms</span>
+ </div>
+ )}
+ {stats.maxLatency !== null && (
+ <div className="flex flex-col items-center py-1.5 px-1 rounded-md bg-secondary/50 border border-border/50">
+ <span className="text-[9px] text-muted-foreground">{t("maxLatency")}</span>
+ <span className="text-xs font-semibold tabular-nums">{stats.maxLatency}ms</span>
+ </div>
+ )}
+ </div>
+ {/* Desktop */}
+ <div className="hidden lg:flex items-center gap-6 text-xs">
+ {stats.uptimePct !== null && (
+ <div className="flex items-center gap-1.5">
+ <span className="text-muted-foreground">{t("uptime")}:</span>
+ <span className={cn("font-semibold tabular-nums",
+ stats.uptimePct >= 99 ? "text-emerald-500" : stats.uptimePct >= 90 ? "text-amber-500" : "text-rose-500")}>
+ {stats.uptimePct.toFixed(1)}%
+ </span>
+ </div>
+ )}
+ {stats.avgLatency !== null && (
+ <div className="flex items-center gap-1.5">
+ <Clock className="w-3.5 h-3.5 text-muted-foreground" />
+ <span className="text-muted-foreground">{t("avgLatency")}:</span>
+ <span className="font-semibold text-emerald-500 tabular-nums">{stats.avgLatency}ms</span>
+ </div>
+ )}
+ {stats.maxLatency !== null && (
+ <div className="flex items-center gap-1.5">
+ <span className="text-muted-foreground">{t("maxLatency")}:</span>
+ <span className="font-semibold tabular-nums">{stats.maxLatency}ms</span>
+ </div>
+ )}
+ {stats.gaps > 0 && (
+ <div className="flex items-center gap-1.5 ml-auto">
+ <span className="text-slate-400 tabular-nums">
+ {stats.gaps} {t("gaps")}
+ </span>
+ </div>
+ )}
+ </div>
+
+ {/* Chart */}
+ <div className="relative h-[180px] w-full">
+ <ResponsiveContainer width="100%" height="100%">
+ <AreaChart data={slots} margin={{ top: 4, right: 10, left: 0, bottom: 0 }}>
+ <defs>
+ <linearGradient id={`colorHealth-${history.backendId}`} x1="0" y1="0" x2="0" y2="1">
+ <stop offset="5%" stopColor="#10b981" stopOpacity={0.3} />
+ <stop offset="95%" stopColor="#10b981" stopOpacity={0} />
+ </linearGradient>
+ </defs>
+
+ <CartesianGrid
+ strokeDasharray="3 3"
+ vertical={false}
+ stroke="#888888"
+ strokeOpacity={0.2}
+ />
+
+ {/* Shade problematic spans — skip leading/trailing gaps (blank) */}
+ {refSpans.filter((s) => s.type !== "gap").map((span, i) => (
+ <ReferenceArea
+ key={i}
+ x1={span.x1}
+ x2={span.x2}
+ fill={
+ span.type === "unhealthy"
+ ? "rgba(244,63,94,0.22)" // rose
+ : "rgba(251,191,36,0.18)" // amber / unknown
+ }
+ stroke={
+ span.type === "unhealthy"
+ ? "rgba(244,63,94,0.5)"
+ : "rgba(251,191,36,0.4)"
+ }
+ strokeOpacity={1}
+ />
+ ))}
+
+ <XAxis
+ dataKey="time"
+ axisLine={false}
+ tickLine={false}
+ tick={{ fontSize: 10, fill: "#888888" }}
+ interval="preserveStartEnd"
+ minTickGap={40}
+ tickFormatter={(v) => labelMap.get(v) ?? v}
+ />
+ <YAxis
+ axisLine={false}
+ tickLine={false}
+ tick={{ fontSize: 10, fill: "#888888" }}
+ tickFormatter={hasLatency ? (v) => `${v}ms` : () => ""}
+ width={hasLatency ? 44 : 0}
+ domain={hasLatency ? ["auto", "auto"] : [0, 1.2]}
+ />
+ <Tooltip content={<CustomTooltip />} />
+
+ <Area
+ type="monotone"
+ dataKey={dataKey}
+ stroke="#10b981"
+ strokeWidth={2}
+ fillOpacity={1}
+ fill={`url(#colorHealth-${history.backendId})`}
+ connectNulls={false}
+ isAnimationActive={false}
+ dot={false}
+ />
+ </AreaChart>
+ </ResponsiveContainer>
+ </div>
+ </div>
+ );
+},
+ (prev, next) =>
+ prev.history === next.history &&
+ prev.from.getTime() === next.from.getTime() &&
+ prev.to.getTime() === next.to.getTime() &&
+ prev.bucketMinutes === next.bucketMinutes,
+);
diff --git a/apps/web/components/features/health/index.tsx b/apps/web/components/features/health/index.tsx
new file mode 100644
index 0000000..2bbb98a
--- /dev/null
+++ b/apps/web/components/features/health/index.tsx
@@ -0,0 +1,226 @@
+"use client";
+
+import React, { useMemo } from "react";
+import { useTranslations } from "next-intl";
+import { keepPreviousData, useQuery } from "@tanstack/react-query";
+import {
+ Activity,
+ RefreshCw,
+ CheckCircle2,
+ XCircle,
+ Server,
+ Clock,
+ BarChart2,
+} from "lucide-react";
+import { Card, CardContent } from "@/components/ui/card";
+import { Button } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import { api, type TimeRange } from "@/lib/api";
+import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";
+import { BackendHealthChart } from "./backend-health-chart";
+
+/** Derive bucket granularity from the time span (ms). */
+function getBucketMinutes(spanMs: number): number {
+ const hours = spanMs / 3_600_000;
+ if (hours <= 2) return 1;
+ if (hours <= 12) return 5;
+ if (hours <= 48) return 15;
+ return 60;
+}
+
+interface HealthContentProps {
+ timeRange: TimeRange;
+}
+
+export function HealthContent({ timeRange }: HealthContentProps) {
+ const t = useTranslations("health");
+
+ // Round to minute so that per-second autoRefresh ticks don't change the query key
+ const stableRange = useStableTimeRange(timeRange, { roundToMinute: true });
+
+ const from = useMemo(
+ () => new Date(stableRange?.start ?? timeRange.start),
+ [stableRange?.start, timeRange.start],
+ );
+ const to = useMemo(
+ () => new Date(stableRange?.end ?? timeRange.end),
+ [stableRange?.end, timeRange.end],
+ );
+ const spanMs = to.getTime() - from.getTime();
+ const bucketMinutes = getBucketMinutes(spanMs);
+
+ const { data, isLoading, isFetching, refetch } = useQuery({
+ queryKey: ["backendHealthHistory", stableRange?.start, stableRange?.end],
+ queryFn: () =>
+ api.getBackendHealthHistory({
+ from: from.toISOString().slice(0, 16),
+ to: to.toISOString().slice(0, 16),
+ }),
+ refetchInterval: 60_000,
+ staleTime: 55_000,
+ placeholderData: keepPreviousData,
+ });
+
+ const summary = useMemo(() => {
+ if (!data?.length) return null;
+ let healthy = 0, total = 0, latSum = 0, latCount = 0;
+ let healthyBackends = 0, unhealthyBackends = 0;
+ for (const backend of data) {
+ const last = backend.points[backend.points.length - 1];
+ if (last?.status === "healthy") healthyBackends++;
+ else unhealthyBackends++;
+ for (const p of backend.points) {
+ total++;
+ if (p.status === "healthy") healthy++;
+ if (p.latency_ms !== null) { latSum += p.latency_ms; latCount++; }
+ }
+ }
+ return {
+ uptimePct: total > 0 ? (healthy / total) * 100 : null,
+ healthyBackends,
+ unhealthyBackends,
+ total: data.length,
+ avgLatency: latCount > 0 ? Math.round(latSum / latCount) : null,
+ };
+ }, [data]);
+
+ return (
+ <div className="space-y-6">
+ {/* Page header */}
+ <div className="flex items-center justify-between gap-3 flex-wrap">
+ <div>
+ <h2 className="text-lg font-semibold flex items-center gap-2">
+ <Activity className="w-5 h-5" />
+ {t("title")}
+ </h2>
+ <p className="text-sm text-muted-foreground mt-0.5">{t("subtitle")}</p>
+ </div>
+
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-7 w-7"
+ onClick={() => refetch()}
+ disabled={isFetching}>
+ <RefreshCw className={cn("w-3.5 h-3.5", isFetching && "animate-spin")} />
+ </Button>
+ </div>
+
+ {/* Summary stat cards — same grid density as Overview */}
+ {summary && (
+ <div className="grid gap-2.5 grid-cols-2 sm:grid-cols-3 lg:grid-cols-6">
+ {/* Overall Uptime */}
+ <div className="rounded-xl p-3.5 border bg-card shadow-xs flex flex-col">
+ <div className="w-8 h-8 rounded-md flex items-center justify-center mb-2.5" style={{ backgroundColor: "#10b98115" }}>
+ <Activity className="w-4 h-4" style={{ color: "#10b981" }} />
+ </div>
+ <p className="text-muted-foreground text-[11px] uppercase tracking-[0.14em] font-medium truncate">{t("overallUptime")}</p>
+ <span className={cn("text-lg leading-none font-semibold mt-2.5 tabular-nums",
+ (summary.uptimePct ?? 0) >= 99 ? "text-emerald-500" : (summary.uptimePct ?? 0) >= 90 ? "text-amber-500" : "text-rose-500")}>
+ {summary.uptimePct?.toFixed(1) ?? "—"}%
+ </span>
+ </div>
+
+ {/* Healthy Backends */}
+ <div className="rounded-xl p-3.5 border bg-card shadow-xs flex flex-col">
+ <div className="w-8 h-8 rounded-md flex items-center justify-center mb-2.5" style={{ backgroundColor: "#10b98115" }}>
+ <CheckCircle2 className="w-4 h-4" style={{ color: "#10b981" }} />
+ </div>
+ <p className="text-muted-foreground text-[11px] uppercase tracking-[0.14em] font-medium truncate">{t("healthyBackends")}</p>
+ <span className="text-lg leading-none font-semibold mt-2.5 tabular-nums text-emerald-500">
+ {summary.healthyBackends}
+ </span>
+ </div>
+
+ {/* Unhealthy Backends */}
+ <div className="rounded-xl p-3.5 border bg-card shadow-xs flex flex-col">
+ <div className="w-8 h-8 rounded-md flex items-center justify-center mb-2.5" style={{ backgroundColor: "#ef444415" }}>
+ <XCircle className="w-4 h-4" style={{ color: "#ef4444" }} />
+ </div>
+ <p className="text-muted-foreground text-[11px] uppercase tracking-[0.14em] font-medium truncate">{t("unhealthyBackends")}</p>
+ <span className={cn("text-lg leading-none font-semibold mt-2.5 tabular-nums",
+ summary.unhealthyBackends > 0 ? "text-rose-500" : "text-foreground")}>
+ {summary.unhealthyBackends}
+ </span>
+ </div>
+
+ {/* Total Backends */}
+ <div className="rounded-xl p-3.5 border bg-card shadow-xs flex flex-col">
+ <div className="w-8 h-8 rounded-md flex items-center justify-center mb-2.5" style={{ backgroundColor: "#3b82f615" }}>
+ <Server className="w-4 h-4" style={{ color: "#3b82f6" }} />
+ </div>
+ <p className="text-muted-foreground text-[11px] uppercase tracking-[0.14em] font-medium truncate">{t("backendsMonitored")}</p>
+ <span className="text-lg leading-none font-semibold mt-2.5 tabular-nums">
+ {summary.total}
+ </span>
+ </div>
+
+ {/* Avg Latency */}
+ <div className="rounded-xl p-3.5 border bg-card shadow-xs flex flex-col">
+ <div className="w-8 h-8 rounded-md flex items-center justify-center mb-2.5" style={{ backgroundColor: "#8b5cf615" }}>
+ <Clock className="w-4 h-4" style={{ color: "#8b5cf6" }} />
+ </div>
+ <p className="text-muted-foreground text-[11px] uppercase tracking-[0.14em] font-medium truncate">{t("overallAvgLatency")}</p>
+ <span className="text-lg leading-none font-semibold mt-2.5 tabular-nums">
+ {summary.avgLatency !== null ? `${summary.avgLatency}ms` : "—"}
+ </span>
+ </div>
+
+ {/* Bucket Size */}
+ <div className="rounded-xl p-3.5 border bg-card shadow-xs flex flex-col">
+ <div className="w-8 h-8 rounded-md flex items-center justify-center mb-2.5" style={{ backgroundColor: "#f59e0b15" }}>
+ <BarChart2 className="w-4 h-4" style={{ color: "#f59e0b" }} />
+ </div>
+ <p className="text-muted-foreground text-[11px] uppercase tracking-[0.14em] font-medium truncate">{t("granularity")}</p>
+ <span className="text-lg leading-none font-semibold mt-2.5 tabular-nums">
+ {bucketMinutes < 60
+ ? t("minuteBucket", { n: bucketMinutes })
+ : t("hourBucket", { n: bucketMinutes / 60 })}
+ </span>
+ </div>
+ </div>
+ )}
+
+ {/* Per-backend charts */}
+ {isLoading ? (
+ <div className="space-y-4">
+ {[1, 2].map((i) => (
+ <Card key={i}>
+ <CardContent className="p-5 space-y-3">
+ <div className="h-4 w-32 bg-muted/50 rounded animate-pulse" />
+ <div className="h-14 w-full bg-muted/30 rounded animate-pulse" />
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+ ) : !data?.length ? (
+ <Card>
+ <CardContent className="p-12 text-center text-muted-foreground">
+ <Activity className="w-10 h-10 mx-auto mb-3 opacity-40" />
+ <p className="font-medium">{t("noBackends")}</p>
+ <p className="text-sm mt-1 opacity-70">{t("noBackendsHint")}</p>
+ </CardContent>
+ </Card>
+ ) : (
+ <div className="space-y-4">
+ {data.map((backend) => (
+ <Card key={backend.backendId}>
+ <CardContent className="px-5 pt-4 pb-3">
+ <BackendHealthChart
+ history={backend}
+ from={from}
+ to={to}
+ bucketMinutes={bucketMinutes}
+ />
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+ )}
+
+ <p className="text-xs text-muted-foreground text-center pb-2">
+ {t("checkInterval")}
+ </p>
+ </div>
+ );
+}
diff --git a/apps/web/components/layout/navigation.tsx b/apps/web/components/layout/navigation.tsx
index 421c75d..a3d6b1d 100644
--- a/apps/web/components/layout/navigation.tsx
+++ b/apps/web/components/layout/navigation.tsx
@@ -16,7 +16,8 @@ import {
Smartphone,
RefreshCw,
X,
- ShieldAlert, // Added
+ ShieldAlert,
+ HeartPulse,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
@@ -51,6 +52,7 @@ const NAV_ITEMS = [
{ id: "countries", icon: MapPin },
{ id: "proxies", icon: Server },
{ id: "devices", icon: Smartphone },
+ { id: "health", icon: HeartPulse },
];
export function Navigation({
diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.ts
index 29d14ad..79d0109 100644
--- a/apps/web/lib/api.ts
+++ b/apps/web/lib/api.ts
@@ -117,6 +117,19 @@ export interface BackendHealth {
latency?: number;
}
+export interface BackendHealthPoint {
+ time: string;
+ status: 'healthy' | 'unhealthy' | 'unknown';
+ latency_ms: number | null;
+ message: string | null;
+}
+
+export interface BackendHealthHistory {
+ backendId: number;
+ backendName: string;
+ points: BackendHealthPoint[];
+}
+
export interface Backend {
id: number;
name: string;
@@ -549,6 +562,15 @@ export const api = {
rotateAgentToken: (id: number) =>
fetchJson<{ message: string; agentToken: string }>(`${API_BASE}/backends/${id}/rotate-agent-token`, 'POST'),
+
+ getBackendHealthHistory: (opts?: { from?: string; to?: string; backendId?: number }) =>
+ fetchJson<BackendHealthHistory[]>(
+ buildUrl(`${API_BASE}/backends/health/history`, {
+ from: opts?.from,
+ to: opts?.to,
+ backendId: opts?.backendId,
+ })
+ ),
// Database management
getDbStats: async () => {
diff --git a/apps/web/lib/types/dashboard.ts b/apps/web/lib/types/dashboard.ts
index 152ee98..2b4c3c7 100644
--- a/apps/web/lib/types/dashboard.ts
+++ b/apps/web/lib/types/dashboard.ts
@@ -19,4 +19,5 @@ export type TabId =
| "devices"
| "proxies"
| "rules"
- | "network";
+ | "network"
+ | "health";
diff --git a/apps/web/messages/en.json b/apps/web/messages/en.json
index 362b9df..db30eec 100644
--- a/apps/web/messages/en.json
+++ b/apps/web/messages/en.json
@@ -11,6 +11,7 @@
"proxies": "Proxies",
"rules": "Rules",
"network": "Network",
+ "health": "Health",
"settings": "Settings",
"showcaseMode": "Showcase Mode"
},
@@ -533,5 +534,30 @@
"emergencyResetDescription": "You are currently in Emergency Access Mode. After resetting the token, the old one will be invalid.",
"emergencyResetWarning": "For your security, please remove the backend environment variable FORCE_ACCESS_CONTROL_OFF and restart the service after the reset is complete."
}
+ },
+ "health": {
+ "title": "Node Health",
+ "subtitle": "Monitor the online status and data collection continuity of each backend",
+ "uptime": "uptime",
+ "latency": "Latency",
+ "avgLatency": "Avg latency",
+ "maxLatency": "Max latency",
+ "gaps": "gap(s)",
+ "statusHealthy": "Online",
+ "statusUnhealthy": "Offline",
+ "statusUnknown": "Unknown",
+ "noData": "No data",
+ "overallUptime": "Overall Uptime",
+ "healthyBackends": "Healthy",
+ "unhealthyBackends": "Unhealthy",
+ "backendsMonitored": "Total Backends",
+ "overallAvgLatency": "Avg Latency",
+ "granularity": "Bucket Size",
+ "minuteBucket": "{n} min/bar",
+ "hourBucket": "{n} hr/bar",
+ "backendStatus": "Backend Status",
+ "noBackends": "No health records yet",
+ "noBackendsHint": "Health checks run automatically every minute for all enabled backends and will appear here",
+ "checkInterval": "Health checks are recorded once per minute. Gaps indicate the collector service was interrupted."
}
}
diff --git a/apps/web/messages/zh.json b/apps/web/messages/zh.json
index 0a35acb..a0aae0b 100644
--- a/apps/web/messages/zh.json
+++ b/apps/web/messages/zh.json
@@ -11,6 +11,7 @@
"proxies": "代理",
"rules": "规则",
"network": "网络",
+ "health": "健康",
"settings": "设置",
"showcaseMode": "演示模式"
},
@@ -532,5 +533,30 @@
"emergencyResetDescription": "当前处于紧急访问模式。重置密码后,旧的令牌将失效。",
"emergencyResetWarning": "为了您的面板安全,请在重置完成后,务必删除后端环境变量 FORCE_ACCESS_CONTROL_OFF 并重启服务。"
}
+ },
+ "health": {
+ "title": "节点健康",
+ "subtitle": "监控各后端节点的在线状态与数据采集连续性",
+ "uptime": "正常运行",
+ "latency": "延迟",
+ "avgLatency": "平均延迟",
+ "maxLatency": "最大延迟",
+ "gaps": "个数据空缺",
+ "statusHealthy": "在线",
+ "statusUnhealthy": "离线",
+ "statusUnknown": "未知",
+ "noData": "无数据",
+ "overallUptime": "整体可用率",
+ "healthyBackends": "在线节点",
+ "unhealthyBackends": "异常节点",
+ "backendsMonitored": "节点总数",
+ "overallAvgLatency": "平均延迟",
+ "granularity": "聚合粒度",
+ "minuteBucket": "{n} 分钟/格",
+ "hourBucket": "{n} 小时/格",
+ "backendStatus": "节点状态",
+ "noBackends": "暂无节点健康记录",
+ "noBackendsHint": "系统每分钟自动检查所有已启用的后端节点,检查结果将在此处显示",
+ "checkInterval": "系统每分钟记录一次健康检查结果,数据空缺表示采集服务中断"
}
}