Skip to content

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

feat: Add server latency reporting and monitoring for backend health.

luoleie202282a32b4
diff --git a/apps/agent/internal/agent/runner.go b/apps/agent/internal/agent/runner.go
index 5b5ce99..d510733 100644
--- a/apps/agent/internal/agent/runner.go
+++ b/apps/agent/internal/agent/runner.go
@@ -46,15 +46,16 @@ type reportPayload struct {
}
type heartbeatPayload struct {
- BackendID int `json:"backendId"`
- AgentID string `json:"agentId"`
- Hostname string `json:"hostname,omitempty"`
- Version string `json:"version,omitempty"`
- AgentVersion string `json:"agentVersion,omitempty"`
- ProtocolVersion int `json:"protocolVersion"`
- GatewayType string `json:"gatewayType,omitempty"`
- GatewayURL string `json:"gatewayUrl,omitempty"`
- GatewayLatencyMs int64 `json:"gatewayLatencyMs,omitempty"`
+ BackendID int `json:"backendId"`
+ AgentID string `json:"agentId"`
+ Hostname string `json:"hostname,omitempty"`
+ Version string `json:"version,omitempty"`
+ AgentVersion string `json:"agentVersion,omitempty"`
+ ProtocolVersion int `json:"protocolVersion"`
+ GatewayType string `json:"gatewayType,omitempty"`
+ GatewayURL string `json:"gatewayUrl,omitempty"`
+ GatewayLatencyMs int64 `json:"gatewayLatencyMs,omitempty"`
+ ServerLatencyMs int64 `json:"serverLatencyMs,omitempty"`
}
type configPayload struct {
@@ -86,6 +87,7 @@ type Runner struct {
lastConfigHash string
lastPolicyHash string
gatewayLatencyMs int64
+ serverLatencyMs int64
}
func NewRunner(cfg config.Config) *Runner {
@@ -576,7 +578,8 @@ func (r *Runner) setRetryBatch(batch []domain.TrafficUpdate, id string) {
func (r *Runner) sendHeartbeat(ctx context.Context) error {
r.mu.Lock()
- latencyMs := r.gatewayLatencyMs
+ gatewayLatencyMs := r.gatewayLatencyMs
+ serverLatencyMs := r.serverLatencyMs
r.mu.Unlock()
payload := heartbeatPayload{
@@ -588,42 +591,57 @@ func (r *Runner) sendHeartbeat(ctx context.Context) error {
ProtocolVersion: config.AgentProtocolVersion,
GatewayType: r.cfg.GatewayType,
GatewayURL: r.cfg.GatewayEndpoint,
- GatewayLatencyMs: latencyMs,
+ GatewayLatencyMs: gatewayLatencyMs,
+ ServerLatencyMs: serverLatencyMs,
}
- return r.postJSON(ctx, "/agent/heartbeat", payload)
+ latencyMs, err := r.postJSONWithLatency(ctx, "/agent/heartbeat", payload)
+ if err != nil {
+ return err
+ }
+
+ r.mu.Lock()
+ r.serverLatencyMs = latencyMs
+ r.mu.Unlock()
+ return nil
}
func (r *Runner) postJSON(ctx context.Context, path string, payload interface{}) error {
+ _, err := r.postJSONWithLatency(ctx, path, payload)
+ return err
+}
+
+func (r *Runner) postJSONWithLatency(ctx context.Context, path string, payload interface{}) (int64, error) {
body, err := json.Marshal(payload)
if err != nil {
- return err
+ return 0, err
}
var buf bytes.Buffer
gz := gzip.NewWriter(&buf)
if _, err = gz.Write(body); err != nil {
- return err
+ return 0, err
}
if err = gz.Close(); err != nil {
- return err
+ return 0, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.cfg.ServerAPIBase+path, &buf)
if err != nil {
- return err
+ return 0, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Content-Encoding", "gzip")
req.Header.Set("Authorization", "Bearer "+r.cfg.BackendToken)
+ requestAt := time.Now()
resp, err := r.httpClient.Do(req)
if err != nil {
- return err
+ return 0, err
}
defer resp.Body.Close()
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
- return nil
+ return time.Since(requestAt).Milliseconds(), nil
}
respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
@@ -631,7 +649,7 @@ func (r *Runner) postJSON(ctx context.Context, path string, payload interface{})
if msg == "" {
msg = resp.Status
}
- return fmt.Errorf("server http %d: %s", resp.StatusCode, msg)
+ return 0, fmt.Errorf("server http %d: %s", resp.StatusCode, msg)
}
func newRequestID() string {
diff --git a/apps/collector/src/database/repositories/health.repository.ts b/apps/collector/src/database/repositories/health.repository.ts
index 58bf869..477820d 100644
--- a/apps/collector/src/database/repositories/health.repository.ts
+++ b/apps/collector/src/database/repositories/health.repository.ts
@@ -13,6 +13,7 @@ export interface HealthLogRow {
minute: string;
status: HealthStatus;
latency_ms: number | null;
+ server_latency_ms: number | null;
message: string | null;
}
@@ -28,16 +29,18 @@ export class HealthRepository {
minute: string,
status: HealthStatus,
latencyMs?: number,
+ serverLatencyMs?: number,
message?: string,
): void {
this.db.prepare(`
- INSERT INTO backend_health_logs (backend_id, minute, status, latency_ms, message)
- VALUES (?, ?, ?, ?, ?)
+ INSERT INTO backend_health_logs (backend_id, minute, status, latency_ms, server_latency_ms, message)
+ VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(backend_id, minute) DO UPDATE SET
status = excluded.status,
latency_ms = excluded.latency_ms,
+ server_latency_ms = excluded.server_latency_ms,
message = excluded.message
- `).run(backendId, minute, status, latencyMs ?? null, message ?? null);
+ `).run(backendId, minute, status, latencyMs ?? null, serverLatencyMs ?? null, message ?? null);
}
/**
@@ -49,7 +52,7 @@ export class HealthRepository {
toISO: string,
): HealthLogRow[] {
return this.db.prepare(`
- SELECT backend_id, minute, status, latency_ms, message
+ SELECT backend_id, minute, status, latency_ms, server_latency_ms, message
FROM backend_health_logs
WHERE backend_id = ? AND minute >= ? AND minute <= ?
ORDER BY minute ASC
@@ -61,7 +64,7 @@ export class HealthRepository {
*/
getHealthHistoryAll(fromISO: string, toISO: string): HealthLogRow[] {
return this.db.prepare(`
- SELECT backend_id, minute, status, latency_ms, message
+ SELECT backend_id, minute, status, latency_ms, server_latency_ms, message
FROM backend_health_logs
WHERE minute >= ? AND minute <= ?
ORDER BY backend_id ASC, minute ASC
diff --git a/apps/collector/src/database/schema.ts b/apps/collector/src/database/schema.ts
index cf49220..decee54 100644
--- a/apps/collector/src/database/schema.ts
+++ b/apps/collector/src/database/schema.ts
@@ -378,6 +378,7 @@ export const SCHEMA = {
gateway_url TEXT,
remote_ip TEXT,
gateway_latency_ms INTEGER,
+ server_latency_ms INTEGER,
last_seen DATETIME NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
@@ -434,6 +435,7 @@ export const SCHEMA = {
minute TEXT NOT NULL,
status TEXT NOT NULL,
latency_ms INTEGER,
+ server_latency_ms INTEGER,
message TEXT,
PRIMARY KEY (backend_id, minute),
FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
diff --git a/apps/collector/src/modules/app/app.ts b/apps/collector/src/modules/app/app.ts
index 7a0d921..1043797 100644
--- a/apps/collector/src/modules/app/app.ts
+++ b/apps/collector/src/modules/app/app.ts
@@ -84,6 +84,7 @@ type AgentHeartbeatPayload = {
gatewayType?: string;
gatewayUrl?: string;
gatewayLatencyMs?: number;
+ serverLatencyMs?: number;
};
type AgentReportPayload = {
@@ -573,8 +574,15 @@ export async function createApp(options: AppOptions) {
const gatewayType = String(body.gatewayType || '').trim().slice(0, 16) || undefined;
const gatewayUrl = String(body.gatewayUrl || '').trim().slice(0, 512) || undefined;
const remoteIP = request.ip || request.headers['x-forwarded-for']?.toString().split(',')[0]?.trim();
- const gatewayLatencyMs = typeof body.gatewayLatencyMs === 'number' && body.gatewayLatencyMs > 0
- ? body.gatewayLatencyMs
+ const gatewayLatencyMs = typeof body.gatewayLatencyMs === 'number'
+ && Number.isFinite(body.gatewayLatencyMs)
+ && body.gatewayLatencyMs >= 0
+ ? Math.round(body.gatewayLatencyMs)
+ : undefined;
+ const serverLatencyMs = typeof body.serverLatencyMs === 'number'
+ && Number.isFinite(body.serverLatencyMs)
+ && body.serverLatencyMs >= 0
+ ? Math.round(body.serverLatencyMs)
: undefined;
db.upsertAgentHeartbeat({
@@ -586,6 +594,7 @@ export async function createApp(options: AppOptions) {
gatewayUrl,
remoteIP,
gatewayLatencyMs,
+ serverLatencyMs,
lastSeen: new Date().toISOString(),
});
diff --git a/apps/collector/src/modules/backend/backend.service.ts b/apps/collector/src/modules/backend/backend.service.ts
index dc28761..063de5d 100644
--- a/apps/collector/src/modules/backend/backend.service.ts
+++ b/apps/collector/src/modules/backend/backend.service.ts
@@ -119,7 +119,14 @@ 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, health.latency, health.message);
+ this.db.repos.health.writeHealthLog(
+ backend.id,
+ minute,
+ health.status,
+ health.latency,
+ health.serverLatency,
+ health.message,
+ );
continue;
}
@@ -150,6 +157,7 @@ export class BackendService {
minute,
health.status,
result.success ? latency : undefined,
+ undefined,
result.message,
);
} catch (error) {
@@ -159,7 +167,7 @@ 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);
+ this.db.repos.health.writeHealthLog(backend.id, minute, 'unhealthy', undefined, undefined, health.message);
console.warn(`[BackendService] Health check error for ${backend.name}:`, error);
}
}
@@ -189,6 +197,7 @@ export class BackendService {
time: row.minute,
status: row.status,
latency_ms: row.latency_ms,
+ server_latency_ms: row.server_latency_ms,
message: row.message,
});
}
@@ -553,11 +562,18 @@ export class BackendService {
const ageText = Number.isFinite(ageMs) ? `${Math.round(ageMs / 1000)}s ago` : 'unknown';
const timeoutText = `${Math.round(timeoutMs / 1000)}s`;
const isOnline = Number.isFinite(ageMs) && ageMs <= timeoutMs;
+ const gatewayLatency = typeof heartbeat.gatewayLatencyMs === 'number' && Number.isFinite(heartbeat.gatewayLatencyMs)
+ ? heartbeat.gatewayLatencyMs
+ : undefined;
+ const serverLatency = typeof heartbeat.serverLatencyMs === 'number' && Number.isFinite(heartbeat.serverLatencyMs)
+ ? heartbeat.serverLatencyMs
+ : undefined;
return {
status: isOnline ? 'healthy' : 'unhealthy',
lastChecked: now,
- latency: isOnline && heartbeat.gatewayLatencyMs ? heartbeat.gatewayLatencyMs : undefined,
+ latency: isOnline ? gatewayLatency : undefined,
+ serverLatency: isOnline ? serverLatency : undefined,
message: isOnline
? `Agent ${heartbeat.agentId} online (last seen ${ageText})`
: `Agent offline (last seen ${ageText}, timeout ${timeoutText})`,
diff --git a/apps/collector/src/modules/backend/backend.types.ts b/apps/collector/src/modules/backend/backend.types.ts
index 7f00e0f..65527b4 100644
--- a/apps/collector/src/modules/backend/backend.types.ts
+++ b/apps/collector/src/modules/backend/backend.types.ts
@@ -39,6 +39,7 @@ export interface BackendHealthInfo {
lastChecked: number;
message?: string;
latency?: number;
+ serverLatency?: number;
}
export interface BackendResponse {
@@ -94,6 +95,7 @@ export interface BackendHealthPoint {
time: string;
status: 'healthy' | 'unhealthy' | 'unknown';
latency_ms: number | null;
+ server_latency_ms: number | null;
message: string | null;
}
diff --git a/apps/collector/src/modules/db/db.ts b/apps/collector/src/modules/db/db.ts
index a78df26..796d972 100644
--- a/apps/collector/src/modules/db/db.ts
+++ b/apps/collector/src/modules/db/db.ts
@@ -56,7 +56,8 @@ export interface AgentHeartbeat {
gatewayType?: string;
gatewayUrl?: string;
remoteIP?: string;
- gatewayLatencyMs?: number;
+ gatewayLatencyMs?: number | null;
+ serverLatencyMs?: number | null;
lastSeen: string;
}
@@ -248,6 +249,22 @@ export class StatsDatabase {
// Column already exists
}
+ // Migration: Add server_latency_ms column to agent_heartbeats
+ try {
+ this.db.exec(`ALTER TABLE agent_heartbeats ADD COLUMN server_latency_ms INTEGER`);
+ console.log('[DB] Migration: Added server_latency_ms column to agent_heartbeats');
+ } catch {
+ // Column already exists
+ }
+
+ // Migration: Add server_latency_ms column to backend_health_logs
+ try {
+ this.db.exec(`ALTER TABLE backend_health_logs ADD COLUMN server_latency_ms INTEGER`);
+ console.log('[DB] Migration: Added server_latency_ms column to backend_health_logs');
+ } catch {
+ // Column already exists
+ }
+
// Migrate connection_logs data to new aggregation tables (one-time backfill)
this.migrateConnectionLogsToAggregation();
}
@@ -1018,13 +1035,14 @@ export class StatsDatabase {
gatewayUrl?: string;
remoteIP?: string;
gatewayLatencyMs?: number;
+ serverLatencyMs?: number;
lastSeen?: string;
}): void {
const stmt = this.db.prepare(`
INSERT INTO agent_heartbeats (
- backend_id, agent_id, hostname, version, gateway_type, gateway_url, remote_ip, gateway_latency_ms, last_seen, updated_at
+ backend_id, agent_id, hostname, version, gateway_type, gateway_url, remote_ip, gateway_latency_ms, server_latency_ms, last_seen, updated_at
)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(backend_id) DO UPDATE SET
agent_id = excluded.agent_id,
hostname = COALESCE(excluded.hostname, agent_heartbeats.hostname),
@@ -1033,6 +1051,7 @@ export class StatsDatabase {
gateway_url = COALESCE(excluded.gateway_url, agent_heartbeats.gateway_url),
remote_ip = COALESCE(excluded.remote_ip, agent_heartbeats.remote_ip),
gateway_latency_ms = COALESCE(excluded.gateway_latency_ms, agent_heartbeats.gateway_latency_ms),
+ server_latency_ms = COALESCE(excluded.server_latency_ms, agent_heartbeats.server_latency_ms),
last_seen = excluded.last_seen,
updated_at = CURRENT_TIMESTAMP
`);
@@ -1047,6 +1066,7 @@ export class StatsDatabase {
input.gatewayUrl || null,
input.remoteIP || null,
input.gatewayLatencyMs ?? null,
+ input.serverLatencyMs ?? null,
lastSeen,
);
}
@@ -1062,6 +1082,7 @@ export class StatsDatabase {
gateway_url as gatewayUrl,
remote_ip as remoteIP,
gateway_latency_ms as gatewayLatencyMs,
+ server_latency_ms as serverLatencyMs,
last_seen as lastSeen
FROM agent_heartbeats
WHERE backend_id = ?
diff --git a/apps/web/components/features/health/backend-health-chart.tsx b/apps/web/components/features/health/backend-health-chart.tsx
index de031ea..79fd5c0 100644
--- a/apps/web/components/features/health/backend-health-chart.tsx
+++ b/apps/web/components/features/health/backend-health-chart.tsx
@@ -79,6 +79,8 @@ interface Slot {
/** always 1 (online) or null (offline/gap) — used when no latency data available */
online: number | null;
latency_ms: number | null;
+ gateway_latency_ms: number | null;
+ server_latency_ms: number | null;
message: string | null;
}
@@ -119,6 +121,8 @@ function buildSlots(
latency: null,
online: null,
latency_ms: null,
+ gateway_latency_ms: null,
+ server_latency_ms: null,
message: null,
});
} else {
@@ -126,13 +130,22 @@ function buildSlots(
const hasUnknown = bucketPoints.some((p) => p.status === "unknown");
const status: HealthStatus = hasUnhealthy ? "unhealthy" : hasUnknown ? "unknown" : "healthy";
- const lats = bucketPoints
+ const gatewayLats = 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)
+ const avgGatewayLatency = gatewayLats.length > 0
+ ? Math.round(gatewayLats.reduce((a, b) => a + b, 0) / gatewayLats.length)
: null;
+ const serverLats = bucketPoints
+ .filter((p) => p.server_latency_ms !== null)
+ .map((p) => p.server_latency_ms as number);
+ const avgServerLatency = serverLats.length > 0
+ ? Math.round(serverLats.reduce((a, b) => a + b, 0) / serverLats.length)
+ : null;
+
+ const avgLatency = avgGatewayLatency !== null ? avgGatewayLatency : avgServerLatency;
+
const lastMsg = bucketPoints[bucketPoints.length - 1].message ?? null;
slots.push({
@@ -142,6 +155,8 @@ function buildSlots(
latency: status === "healthy" ? avgLatency : null,
online: status === "healthy" ? 1 : null,
latency_ms: avgLatency,
+ gateway_latency_ms: status === "healthy" ? avgGatewayLatency : null,
+ server_latency_ms: status === "healthy" ? avgServerLatency : null,
message: lastMsg,
});
}
@@ -221,7 +236,7 @@ interface BackendHealthChartProps {
bucketMinutes?: number;
}
-export const BackendHealthChart = React.memo(function BackendHealthChart({
+export function BackendHealthChart({
history,
from,
to,
@@ -235,6 +250,8 @@ export const BackendHealthChart = React.memo(function BackendHealthChart({
[from, to, history.points, bucketMinutes],
);
+ // Debug - moved after variable definitions
+
const refSpans = useMemo(() => buildRefSpans(resolveGapSlots(slots)), [slots]);
const labelMap = useMemo(
@@ -257,10 +274,15 @@ export const BackendHealthChart = React.memo(function BackendHealthChart({
return { uptimePct, avgLatency, maxLatency, gaps };
}, [slots]);
- const hasLatency = useMemo(
- () => history.points.some((p) => p.latency_ms !== null),
- [history.points],
+ const hasGatewayLatency = useMemo(
+ () => slots.some((s) => s.gateway_latency_ms !== null),
+ [slots],
);
+ const hasServerLatency = useMemo(
+ () => slots.some((s) => s.server_latency_ms !== null),
+ [slots],
+ );
+ const hasLatency = hasGatewayLatency || hasServerLatency;
const dataKey = hasLatency ? "latency" : "online";
@@ -274,7 +296,11 @@ export const BackendHealthChart = React.memo(function BackendHealthChart({
// Tier is driven by max latency in the visible data
const latencyTier: LatencyTier = getLatencyTier(stats.maxLatency);
- const strokeColor = hasLatency ? TIER_STROKE[latencyTier] : "#10b981";
+ const gatewayStrokeColor = TIER_STROKE[latencyTier];
+ const serverStrokeColor = "#3b82f6";
+ const strokeColor = hasGatewayLatency ? gatewayStrokeColor : serverStrokeColor;
+
+
const avgLatencyTier: LatencyTier = getLatencyTier(stats.avgLatency);
const maxLatencyTier: LatencyTier = getLatencyTier(stats.maxLatency);
@@ -331,16 +357,25 @@ export const BackendHealthChart = React.memo(function BackendHealthChart({
? "text-rose-500"
: "text-slate-400";
- const slotLatencyTier = getLatencyTier(slot.latency_ms);
+ const gatewayLatencyTier = getLatencyTier(slot.gateway_latency_ms);
+ const serverLatencyTier = getLatencyTier(slot.server_latency_ms);
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={cn("flex items-center gap-1", TIER_TEXT[slotLatencyTier])}>
+ {slot.gateway_latency_ms !== null && (
+ <p className={cn("flex items-center gap-1", TIER_TEXT[gatewayLatencyTier])}>
+ <Clock className="w-3 h-3" />
+ <span>Gateway:</span>
+ <span className="tabular-nums font-medium">{slot.gateway_latency_ms}ms</span>
+ </p>
+ )}
+ {slot.server_latency_ms !== null && (
+ <p className={cn("flex items-center gap-1", TIER_TEXT[serverLatencyTier])}>
<Clock className="w-3 h-3" />
- <span className="tabular-nums font-medium">{slot.latency_ms}ms</span>
+ <span>Server:</span>
+ <span className="tabular-nums font-medium">{slot.server_latency_ms}ms</span>
</p>
)}
{slot.message && slot.status !== "healthy" && (
@@ -381,6 +416,26 @@ export const BackendHealthChart = React.memo(function BackendHealthChart({
<span className={cn("inline-flex w-2 h-2 rounded-full shrink-0", statusDotClass)} />
</div>
+ {/* Legend for agent mode */}
+ {hasServerLatency && (
+ <div className="flex items-center gap-3 text-[11px] text-muted-foreground">
+ <div className="inline-flex items-center gap-1.5">
+ <span
+ className="inline-flex h-0.5 w-4 rounded-full"
+ style={{ backgroundColor: gatewayStrokeColor }}
+ />
+ <span>Gateway</span>
+ </div>
+ <div className="inline-flex items-center gap-1.5">
+ <span
+ className="inline-flex h-0 w-4 border-t-2 border-dashed"
+ style={{ borderColor: serverStrokeColor }}
+ />
+ <span>Server</span>
+ </div>
+ </div>
+ )}
+
{/* Stats row — mobile */}
<div className="grid grid-cols-3 gap-2 lg:hidden">
{stats.uptimePct !== null && (
@@ -503,26 +558,40 @@ export const BackendHealthChart = React.memo(function BackendHealthChart({
/>
<Tooltip content={<CustomTooltip />} />
+ {/* Gateway latency curve - always show if has latency */}
<Area
type="monotone"
- dataKey={dataKey}
- stroke={strokeColor}
+ dataKey="latency"
+ stroke={gatewayStrokeColor}
strokeWidth={2}
fillOpacity={1}
fill={`url(#colorHealth-${history.backendId})`}
connectNulls={false}
isAnimationActive={false}
dot={false}
+ activeDot={{ r: 3 }}
/>
+ {/* Server latency curve - show only for agent mode */}
+ {hasServerLatency && (
+ <Area
+ type="monotone"
+ dataKey="server_latency_ms"
+ stroke={serverStrokeColor}
+ strokeWidth={2}
+ strokeDasharray="5 4"
+ fill="none"
+ fillOpacity={0}
+ connectNulls={false}
+ isAnimationActive={false}
+ dot={false}
+ activeDot={{ r: 3 }}
+ />
+ )}
</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,
-);
+}
+// Note: Removed React.memo to ensure real-time updates work correctly
+// The component will re-render when any prop changes
diff --git a/apps/web/components/features/health/index.tsx b/apps/web/components/features/health/index.tsx
index 04df8fb..81f1c35 100644
--- a/apps/web/components/features/health/index.tsx
+++ b/apps/web/components/features/health/index.tsx
@@ -72,7 +72,8 @@ export function HealthContent({ timeRange }: HealthContentProps) {
for (const p of backend.points) {
total++;
if (p.status === "healthy") healthy++;
- if (p.latency_ms !== null) { latSum += p.latency_ms; latCount++; }
+ const latency = p.latency_ms ?? p.server_latency_ms;
+ if (latency !== null) { latSum += latency; latCount++; }
}
}
return {
diff --git a/apps/web/components/layout/navigation.tsx b/apps/web/components/layout/navigation.tsx
index 009c8ea..377d07f 100644
--- a/apps/web/components/layout/navigation.tsx
+++ b/apps/web/components/layout/navigation.tsx
@@ -282,24 +282,25 @@ export function Navigation({
{/* Mobile Bottom Navigation */}
<nav className="lg:hidden fixed bottom-0 left-0 right-0 z-50 border-t border-border/40 bg-background/80 backdrop-blur-md">
- <div className="flex items-center justify-around h-16 px-2">
- {NAV_ITEMS.map((item) => {
- const Icon = item.icon;
- const isActive = activeTab === item.id;
- return (
- <button
- key={item.id}
- onClick={() => onTabChange(item.id)}
- className={cn(
- "flex flex-col items-center gap-1 px-3 py-2 rounded-lg transition-all",
- isActive ? "text-primary" : "text-muted-foreground",
- item.id === "devices" && "hidden min-[410px]:flex",
- )}>
- <Icon className={cn("w-5 h-5", isActive && "scale-110")} />
- <span className="text-[10px]">{t(item.id)}</span>
- </button>
- );
- })}
+ <div className="h-16 overflow-x-auto overscroll-x-contain [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden">
+ <div className="flex items-center h-full min-w-full px-1">
+ {NAV_ITEMS.map((item) => {
+ const Icon = item.icon;
+ const isActive = activeTab === item.id;
+ return (
+ <button
+ key={item.id}
+ onClick={() => onTabChange(item.id)}
+ className={cn(
+ "min-w-[20%] shrink-0 flex flex-col items-center justify-center gap-1 px-2 py-2 rounded-lg transition-all",
+ isActive ? "text-primary" : "text-muted-foreground",
+ )}>
+ <Icon className="w-5 h-5" />
+ <span className="text-[10px]">{t(item.id)}</span>
+ </button>
+ );
+ })}
+ </div>
</div>
</nav>
diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.ts
index 79d0109..e2bcf68 100644
--- a/apps/web/lib/api.ts
+++ b/apps/web/lib/api.ts
@@ -115,12 +115,14 @@ export interface BackendHealth {
lastChecked: number;
message?: string;
latency?: number;
+ serverLatency?: number;
}
export interface BackendHealthPoint {
time: string;
status: 'healthy' | 'unhealthy' | 'unknown';
latency_ms: number | null;
+ server_latency_ms: number | null;
message: string | null;
}
@@ -648,6 +650,7 @@ export function getPresetTimeRange(
const now = new Date();
const end = new Date(now);
end.setMilliseconds(0);
+ end.setSeconds(0); // Truncate to minute to align with backend health log interval
// Helper to get start of today in local time
const getStartOfToday = () => {
diff --git a/apps/web/messages/en.json b/apps/web/messages/en.json
index db30eec..416da13 100644
--- a/apps/web/messages/en.json
+++ b/apps/web/messages/en.json
@@ -540,6 +540,8 @@
"subtitle": "Monitor the online status and data collection continuity of each backend",
"uptime": "uptime",
"latency": "Latency",
+ "gatewayLatency": "Gateway latency",
+ "serverLatency": "Server latency",
"avgLatency": "Avg latency",
"maxLatency": "Max latency",
"gaps": "gap(s)",
diff --git a/apps/web/messages/zh.json b/apps/web/messages/zh.json
index a0aae0b..9bd959f 100644
--- a/apps/web/messages/zh.json
+++ b/apps/web/messages/zh.json
@@ -539,6 +539,8 @@
"subtitle": "监控各后端节点的在线状态与数据采集连续性",
"uptime": "正常运行",
"latency": "延迟",
+ "gatewayLatency": "网关延迟",
+ "serverLatency": "中心服务延迟",
"avgLatency": "平均延迟",
"maxLatency": "最大延迟",
"gaps": "个数据空缺",