ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(monitoring): fold Fleet Monitor in, and scope the page to a server
Juan Denisb41314819445
diff --git a/docs/screenshots/monitoring-alerts.png b/docs/screenshots/monitoring-alerts.pngnew file mode 100644index 00000000..54e09c39Binary files /dev/null and b/docs/screenshots/monitoring-alerts.png differdiff --git a/docs/screenshots/monitoring-capacity.png b/docs/screenshots/monitoring-capacity.pngnew file mode 100644index 00000000..d53a6e23Binary files /dev/null and b/docs/screenshots/monitoring-capacity.png differdiff --git a/docs/screenshots/monitoring-rules.png b/docs/screenshots/monitoring-rules.pngnew file mode 100644index 00000000..371a5d19Binary files /dev/null and b/docs/screenshots/monitoring-rules.png differdiff --git a/docs/screenshots/monitoring-server.png b/docs/screenshots/monitoring-server.pngnew file mode 100644index 00000000..18667c45Binary files /dev/null and b/docs/screenshots/monitoring-server.png differdiff --git a/docs/screenshots/monitoring.png b/docs/screenshots/monitoring.pngindex dbf9f347..9c442122 100644Binary files a/docs/screenshots/monitoring.png and b/docs/screenshots/monitoring.png differdiff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex f37f0fb6..c69fa47d 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -34,7 +34,6 @@ import Templates from './pages/Templates';import Servers from './pages/Servers';import ServerDetail from './pages/ServerDetail';import AgentFleet from './pages/AgentFleet';-import FleetMonitor from './pages/FleetMonitor';import TabGroupLayout from './layouts/TabGroupLayout';import { SERVER_TABS } from './components/servers/serverTabs';import { DOMAIN_TABS } from './components/domains/domainTabs';@@ -103,7 +102,7 @@ const PAGE_TITLES = {'/servers': 'Servers','/downloads': 'Downloads','/files': 'File Manager',- '/observability': 'Observability',+ '/observability': 'Monitoring','/monitoring': 'Monitoring','/backups': 'Backups','/cron': 'Cron Jobs',@@ -114,7 +113,6 @@ const PAGE_TITLES = {'/connections/github-app/callback': 'GitHub Setup','/migrate': 'Database Migration','/fleet': 'Agent Fleet',- '/fleet-monitor': 'Fleet Monitor','/agent-plugins': 'Extensions','/server-templates': 'Server Templates','/workspaces': 'Workspaces',@@ -369,7 +367,6 @@ function AppRoutes() {<Route element={<TabGroupLayout tabs={SERVER_TABS} groupId="servers" />}><Route path="servers" element={<Servers />} /><Route path="fleet" element={<AgentFleet />} />- <Route path="fleet-monitor" element={<FleetMonitor />} /><Route path="fleet-proxy" element={<FleetProxy />} /><Route path="server-templates" element={<ServerTemplates />} />{groupRoutes.servers}@@ -427,6 +424,11 @@ function AppRoutes() {{groupRoutes.monitoring}</Route><Route path="observability" element={<Navigate to="/monitoring" replace />} />+ {/* Fleet Monitor folded into /monitoring: it asked the same+ questions at fleet scope, so its heatmap is now the Host+ health grid on the overview (click a card to re-scope the+ page) and its analytics are the Capacity tab. */}+ <Route path="fleet-monitor" element={<Navigate to="/monitoring" replace />} />{/* /gpu is contributed by the standalone serverkit-gpu extension. */}<Route element={<TabGroupLayout tabs={BACKUP_TABS} />}><Route path="backups" element={<Backups />} />diff --git a/frontend/src/components/ds/MetricCard.jsx b/frontend/src/components/ds/MetricCard.jsxindex 6fba1f87..873eff88 100644--- a/frontend/src/components/ds/MetricCard.jsx+++ b/frontend/src/components/ds/MetricCard.jsx@@ -15,6 +15,10 @@ import { formatCompact, formatFull } from '../../utils/formatNumber';// `compact` opts a numeric tile into space-tight formatting: a value ≥ 1000 is// rendered compact (107814 → "107.8K") with the exact grouped number as the// hover title. Non-numeric values (or values under 1000) render verbatim.+// `spark` takes a chart node (Sparkline / AreaChart) and bleeds it to the+// tile's edges along the bottom — the design mock's `.kpi-spark`. Passing it is+// what turns a bare stat into a trend tile; tiles without a series simply omit+// it and keep the same geometry, so a row can mix both.export function MetricCard({icon,tone,@@ -24,6 +28,7 @@ export function MetricCard({label,trend,trendDir = 'flat',+ spark,onClick,compact = false,className,@@ -60,6 +65,7 @@ export function MetricCard({</div>{label && <div className="sk-kpi__label">{label}</div>}{children}+ {spark && <div className="sk-kpi__spark">{spark}</div>}</>);diff --git a/frontend/src/components/monitoring/FleetAlertsPanel.jsx b/frontend/src/components/monitoring/FleetAlertsPanel.jsxnew file mode 100644index 00000000..f2a67ae0--- /dev/null+++ b/frontend/src/components/monitoring/FleetAlertsPanel.jsx@@ -0,0 +1,125 @@+import { useState, useEffect } from 'react';+import { CheckCircle, Eye } from 'lucide-react';+import api from '../../services/api';+import { useToast } from '../../contexts/ToastContext';+import { Button } from '@/components/ui/button';+import { Pill, SegControl } from '@/components/ds';+import { METRIC_LABELS } from './fleetMetrics';++const ALERT_FILTERS = [+ { value: 'active', label: 'Active' },+ { value: 'acknowledged', label: 'Acknowledged' },+ { value: 'resolved', label: 'Resolved' },+ { value: 'all', label: 'All' },+];++// Alerts raised by per-server thresholds across the fleet. The panel host's own+// alerts are a different system (a single set of limits, delivered by the+// monitoring scheduler) and sit above this on the Alerts tab; the limits behind+// these rows are edited on the Rules tab.+export default function FleetAlertsPanel({ scope, refreshKey = 0 }) {+ const toast = useToast();+ const [alerts, setAlerts] = useState([]);+ const [filter, setFilter] = useState('active');+ const [reloadKey, setReloadKey] = useState(0);++ useEffect(() => {+ let cancelled = false;+ api.getFleetAlerts({+ status: filter !== 'all' ? filter : undefined,+ // Following the top-bar scope keeps every section answering the+ // same question about the same host.+ server_id: scope && scope !== 'host' ? scope : undefined,+ })+ .then((data) => { if (!cancelled) setAlerts(Array.isArray(data) ? data : []); })+ .catch(() => { if (!cancelled) setAlerts([]); });+ return () => { cancelled = true; };+ }, [filter, scope, refreshKey, reloadKey]);++ const runAction = async (fn, failure) => {+ try {+ await fn();+ setReloadKey((k) => k + 1);+ } catch {+ toast.error(failure);+ }+ };++ return (+ <section className="monitoring-panel">+ <div className="monitoring-panel__header">+ <h3>Fleet alerts</h3>+ <SegControl value={filter} onChange={setFilter} options={ALERT_FILTERS} />+ </div>++ {alerts.length > 0 ? (+ <div className="mon-table-scroll">+ <table className="sk-dtable">+ <thead>+ <tr>+ <th>Server</th>+ <th>Metric</th>+ <th>Value</th>+ <th>Threshold</th>+ <th>Severity</th>+ <th>Status</th>+ <th>Time</th>+ <th />+ </tr>+ </thead>+ <tbody>+ {alerts.map((a) => (+ <tr key={a.id}>+ <td>{a.server_name}</td>+ <td>{METRIC_LABELS[a.metric] || a.metric}</td>+ <td className="sk-cell-mono">{a.value}%</td>+ <td className="sk-cell-mono">{a.threshold}%</td>+ <td><Pill kind={a.severity === 'critical' ? 'red' : 'amber'}>{a.severity}</Pill></td>+ <td>+ <Pill kind={a.status === 'active' ? 'red' : a.status === 'acknowledged' ? 'amber' : 'green'}>+ {a.status}+ </Pill>+ </td>+ <td>{new Date(a.created_at).toLocaleString()}</td>+ <td className="mon-row-actions">+ {a.status === 'active' && (+ <Button+ variant="ghost"+ size="sm"+ onClick={() => runAction(+ () => api.acknowledgeFleetAlert(a.id),+ 'Failed to acknowledge alert',+ )}+ >+ <Eye size={14} /> Ack+ </Button>+ )}+ {a.status !== 'resolved' && (+ <Button+ variant="ghost"+ size="sm"+ onClick={() => runAction(+ () => api.resolveFleetAlert(a.id),+ 'Failed to resolve alert',+ )}+ >+ <CheckCircle size={14} /> Resolve+ </Button>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ ) : (+ <p className="mon-panel-hint">+ <CheckCircle size={14} />+ {filter === 'all'+ ? 'No fleet alerts have ever been raised.'+ : `No ${filter} fleet alerts.`}+ </p>+ )}+ </section>+ );+}diff --git a/frontend/src/components/monitoring/FleetCapacityPanel.jsx b/frontend/src/components/monitoring/FleetCapacityPanel.jsxnew file mode 100644index 00000000..d12183ef--- /dev/null+++ b/frontend/src/components/monitoring/FleetCapacityPanel.jsx@@ -0,0 +1,344 @@+import { useState, useEffect, useMemo } from 'react';+import { BarChart3, CheckCircle, Download, TrendingUp } from 'lucide-react';+import {+ LineChart, Line, AreaChart, Area, XAxis, YAxis,+ CartesianGrid, Tooltip, ResponsiveContainer, Legend,+} from 'recharts';+import api from '../../services/api';+import { useToast } from '../../contexts/ToastContext';+import { Button } from '@/components/ui/button';+import { Pill } from '@/components/ds';+import { CHART_COLORS, METRIC_LABELS } from './fleetMetrics';++// The three fleet-wide questions that only make sense across servers: how do+// these boxes compare, which one is behaving unlike itself, and when does a+// disk run out. Host-scoped gauges live on the Overview tab.+export default function FleetCapacityPanel({ scope, refreshKey = 0 }) {+ const toast = useToast();+ const [servers, setServers] = useState([]);++ // Comparison+ const [selectedServers, setSelectedServers] = useState([]);+ // The top-bar scope is the page's answer to "which host?", so it seeds both+ // controls here — you land on the server you were already looking at.+ const scopedServer = scope && scope !== 'host' ? scope : '';+ const [compMetric, setCompMetric] = useState('cpu');+ const [compPeriod, setCompPeriod] = useState('24h');+ const [compData, setCompData] = useState(null);+ const [comparing, setComparing] = useState(false);++ // Anomalies+ const [anomalies, setAnomalies] = useState([]);++ // Forecast+ const [forecastServer, setForecastServer] = useState(scopedServer);+ const [forecastMetric, setForecastMetric] = useState('disk');+ const [forecast, setForecast] = useState(null);++ useEffect(() => {+ if (!scopedServer) return;+ setForecastServer(scopedServer);+ setSelectedServers((prev) => (prev.includes(scopedServer) ? prev : [...prev, scopedServer]));+ }, [scopedServer]);++ useEffect(() => {+ let cancelled = false;+ api.getServers()+ .then((data) => {+ if (cancelled) return;+ const list = data?.servers || data;+ setServers(Array.isArray(list) ? list : []);+ })+ .catch(() => { if (!cancelled) setServers([]); });+ api.getFleetAnomalies()+ .then((data) => { if (!cancelled) setAnomalies(Array.isArray(data) ? data : []); })+ .catch(() => { if (!cancelled) setAnomalies([]); });+ return () => { cancelled = true; };+ }, [refreshKey]);++ const loadComparison = async () => {+ if (selectedServers.length === 0) return;+ setComparing(true);+ try {+ setCompData(await api.getFleetComparison(selectedServers, compMetric, compPeriod));+ } catch {+ toast.error('Failed to load comparison data');+ } finally {+ setComparing(false);+ }+ };++ const loadForecast = async () => {+ if (!forecastServer) return;+ try {+ setForecast(await api.getCapacityForecast(forecastServer, forecastMetric));+ } catch {+ toast.error('Failed to load forecast');+ }+ };++ const exportCsv = async () => {+ if (selectedServers.length === 0) return;+ try {+ const blob = await api.exportFleetCsv(selectedServers, compMetric, compPeriod);+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = `fleet_${compMetric}_${compPeriod}.csv`;+ a.click();+ URL.revokeObjectURL(url);+ } catch {+ toast.error('Export failed');+ }+ };++ const toggleServer = (id) => {+ setSelectedServers((prev) => (+ prev.includes(id) ? prev.filter((s) => s !== id) : [...prev, id]+ ));+ };++ // Recharts wants one row per timestamp with a column per series; the API+ // returns one series per server, so pivot before rendering.+ const compChartData = useMemo(() => {+ if (!compData?.series?.length) return [];+ const byTime = {};+ compData.series.forEach((s) => {+ s.data.forEach((point) => {+ if (!byTime[point.timestamp]) byTime[point.timestamp] = { timestamp: point.timestamp };+ byTime[point.timestamp][s.name] = point.value;+ });+ });+ return Object.values(byTime).sort((a, b) => a.timestamp.localeCompare(b.timestamp));+ }, [compData]);++ return (+ <div className="monitoring-stack">+ <section className="monitoring-panel">+ <div className="monitoring-panel__header">+ <h3>Server Comparison</h3>+ <div>+ <Button variant="outline" size="sm" onClick={exportCsv} disabled={selectedServers.length === 0}>+ <Download size={14} /> Export CSV+ </Button>+ <Button size="sm" onClick={loadComparison} disabled={selectedServers.length === 0 || comparing}>+ <BarChart3 size={14} /> {comparing ? 'Comparing…' : 'Compare'}+ </Button>+ </div>+ </div>++ <div className="mon-compare-controls">+ <div className="mon-compare-controls__servers">+ <span className="mon-field-label">Servers</span>+ <div className="mon-server-picker">+ {servers.length === 0 ? (+ <span className="mon-field-hint">No servers paired yet.</span>+ ) : servers.map((s) => (+ <Button+ key={s.id}+ size="sm"+ variant={selectedServers.includes(s.id) ? 'default' : 'ghost'}+ onClick={() => toggleServer(s.id)}+ >+ {s.name}+ </Button>+ ))}+ </div>+ </div>+ <div className="form-group">+ <span className="mon-field-label">Metric</span>+ <select value={compMetric} onChange={(e) => setCompMetric(e.target.value)}>+ {Object.entries(METRIC_LABELS).map(([k, v]) => (+ <option key={k} value={k}>{v}</option>+ ))}+ </select>+ </div>+ <div className="form-group">+ <span className="mon-field-label">Period</span>+ <div className="mon-period-switch">+ {['1h', '6h', '24h', '7d'].map((p) => (+ <Button+ key={p}+ size="sm"+ variant={compPeriod === p ? 'default' : 'ghost'}+ onClick={() => setCompPeriod(p)}+ >+ {p}+ </Button>+ ))}+ </div>+ </div>+ </div>++ {compChartData.length > 0 && compData?.series ? (+ <ResponsiveContainer width="100%" height={360}>+ <AreaChart data={compChartData}>+ <CartesianGrid strokeDasharray="3 3" stroke="var(--border-color)" />+ <XAxis+ dataKey="timestamp"+ tickFormatter={(v) => new Date(v).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}+ stroke="var(--text-secondary)"+ fontSize={12}+ />+ <YAxis stroke="var(--text-secondary)" fontSize={12} unit="%" />+ <Tooltip+ labelFormatter={(v) => new Date(v).toLocaleString()}+ contentStyle={{ backgroundColor: 'var(--card-bg)', border: '1px solid var(--border-color)' }}+ />+ <Legend />+ {compData.series.map((s, i) => (+ <Area+ key={s.server_id}+ type="monotone"+ dataKey={s.name}+ stroke={CHART_COLORS[i % CHART_COLORS.length]}+ fill={CHART_COLORS[i % CHART_COLORS.length]}+ fillOpacity={0.1}+ strokeWidth={2}+ dot={false}+ />+ ))}+ </AreaChart>+ </ResponsiveContainer>+ ) : (+ <p className="mon-panel-hint">+ Pick two or more servers, then Compare to plot the same metric across all of them.+ </p>+ )}+ </section>++ <section className="monitoring-panel">+ <div className="monitoring-panel__header">+ <h3>Anomaly Detection</h3>+ </div>+ {anomalies.length > 0 ? (+ <div className="mon-table-scroll">+ <table className="sk-dtable">+ <thead>+ <tr>+ <th>Server</th>+ <th>Metric</th>+ <th>Current</th>+ <th>Baseline (mean)</th>+ <th>Std dev</th>+ <th>Z-score</th>+ <th>Direction</th>+ </tr>+ </thead>+ <tbody>+ {anomalies.map((a, i) => (+ <tr key={`${a.server_name}-${a.metric}-${i}`}>+ <td>{a.server_name}</td>+ <td>{METRIC_LABELS[a.metric] || a.metric}</td>+ <td className="sk-cell-mono">{a.current_value}%</td>+ <td className="sk-cell-mono">{a.mean}%</td>+ <td className="sk-cell-mono">{a.stddev}</td>+ <td className="sk-cell-mono">{a.z_score}</td>+ <td>+ <Pill kind={a.direction === 'high' ? 'red' : 'cyan'}>+ {a.direction === 'high' ? 'Unusually high' : 'Unusually low'}+ </Pill>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ ) : (+ <p className="mon-panel-hint">+ <CheckCircle size={14} /> Every metric is within its own recent baseline.+ </p>+ )}+ </section>++ <section className="monitoring-panel">+ <div className="monitoring-panel__header">+ <h3>Capacity Forecast</h3>+ <Button size="sm" onClick={loadForecast} disabled={!forecastServer}>+ <TrendingUp size={14} /> Forecast+ </Button>+ </div>++ <div className="mon-compare-controls">+ <div className="form-group">+ <span className="mon-field-label">Server</span>+ <select value={forecastServer} onChange={(e) => setForecastServer(e.target.value)}>+ <option value="">Select a server…</option>+ {servers.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}+ </select>+ </div>+ <div className="form-group">+ <span className="mon-field-label">Metric</span>+ <select value={forecastMetric} onChange={(e) => setForecastMetric(e.target.value)}>+ <option value="disk">Disk</option>+ <option value="memory">Memory</option>+ <option value="cpu">CPU</option>+ </select>+ </div>+ </div>++ {forecast?.error && <div className="fleet-warnrow">{forecast.error}</div>}++ {forecast && !forecast.error ? (+ <div className="mon-forecast">+ <div className="mon-forecast__stats">+ <div className="fleet-statbox">+ <span className="mon-field-label">Current</span>+ <strong>{forecast.current_value}%</strong>+ </div>+ <div className="fleet-statbox">+ <span className="mon-field-label">Growth rate</span>+ <strong>{forecast.growth_rate_per_day}%/day</strong>+ </div>+ <div className="fleet-statbox">+ <span className="mon-field-label">Trend</span>+ <strong>{forecast.trend}</strong>+ </div>+ </div>++ {forecast.predictions && (+ <div className="mon-forecast__predictions">+ <div className={`fleet-predbox ${forecast.predictions.days_to_90pct === 0 ? 'is-red' : 'is-amber'}`}>+ <span className="mon-field-label">Reaches 90%</span>+ <strong>+ {forecast.predictions.date_90pct || 'N/A'}+ {forecast.predictions.days_to_90pct > 0 && (+ <em> ({forecast.predictions.days_to_90pct} days)</em>+ )}+ </strong>+ </div>+ <div className="fleet-predbox is-red">+ <span className="mon-field-label">Reaches 100%</span>+ <strong>+ {forecast.predictions.date_100pct || 'N/A'}+ {forecast.predictions.days_to_100pct > 0 && (+ <em> ({forecast.predictions.days_to_100pct} days)</em>+ )}+ </strong>+ </div>+ </div>+ )}++ {forecast.trend_data && (+ <ResponsiveContainer width="100%" height={280}>+ <LineChart data={forecast.trend_data}>+ <CartesianGrid strokeDasharray="3 3" stroke="var(--border-color)" />+ <XAxis dataKey="date" stroke="var(--text-secondary)" fontSize={11} />+ <YAxis stroke="var(--text-secondary)" fontSize={12} unit="%" domain={[0, 100]} />+ <Tooltip contentStyle={{ backgroundColor: 'var(--card-bg)', border: '1px solid var(--border-color)' }} />+ <Legend />+ <Line type="monotone" dataKey="actual" stroke="var(--accent-bright)" strokeWidth={2} dot={false} name="Actual" />+ <Line type="monotone" dataKey="trend" stroke="var(--red)" strokeWidth={2} strokeDasharray="5 5" dot={false} name="Trend" />+ </LineChart>+ </ResponsiveContainer>+ )}+ </div>+ ) : !forecast && (+ <p className="mon-panel-hint">+ Pick a server and a metric to project when it runs out of headroom.+ </p>+ )}+ </section>+ </div>+ );+}diff --git a/frontend/src/components/monitoring/FleetThresholdsPanel.jsx b/frontend/src/components/monitoring/FleetThresholdsPanel.jsxnew file mode 100644index 00000000..7609cc0b--- /dev/null+++ b/frontend/src/components/monitoring/FleetThresholdsPanel.jsx@@ -0,0 +1,164 @@+import { useState, useEffect } from 'react';+import { Plus, XCircle } from 'lucide-react';+import api from '../../services/api';+import { useToast } from '../../contexts/ToastContext';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { METRIC_LABELS } from './fleetMetrics';++const DEFAULT_THRESHOLD = {+ metric: 'cpu',+ warning_threshold: 80,+ critical_threshold: 95,+ duration_seconds: 300,+};++// Per-server limits, sitting under the panel host's own limits on the Rules+// tab: same idea, wider scope. Two lists rather than one because they are two+// backends — the host's four values are a single config, these are rows.+export default function FleetThresholdsPanel({ servers = [], refreshKey = 0 }) {+ const toast = useToast();+ const [thresholds, setThresholds] = useState([]);+ const [draft, setDraft] = useState(DEFAULT_THRESHOLD);+ const [adding, setAdding] = useState(false);+ const [reloadKey, setReloadKey] = useState(0);++ useEffect(() => {+ let cancelled = false;+ api.getFleetThresholds()+ .then((data) => { if (!cancelled) setThresholds(Array.isArray(data) ? data : []); })+ .catch(() => { if (!cancelled) setThresholds([]); });+ return () => { cancelled = true; };+ }, [refreshKey, reloadKey]);++ const reload = () => setReloadKey((k) => k + 1);++ const saveThreshold = async () => {+ try {+ await api.createFleetThreshold(draft);+ toast.success('Threshold saved');+ setDraft(DEFAULT_THRESHOLD);+ setAdding(false);+ reload();+ } catch {+ toast.error('Failed to save threshold');+ }+ };++ const removeThreshold = async (id) => {+ try {+ await api.deleteFleetThreshold(id);+ reload();+ } catch {+ toast.error('Failed to delete threshold');+ }+ };++ return (+ <section className="monitoring-panel">+ <div className="monitoring-panel__header">+ <div>+ <h3>Per-server rules</h3>+ <span className="mon-panel-sub">Limits applied to paired servers by their agents</span>+ </div>+ <Button size="sm" variant={adding ? 'outline' : 'default'} onClick={() => setAdding((v) => !v)}>+ <Plus size={14} /> {adding ? 'Cancel' : 'Add rule'}+ </Button>+ </div>++ {adding && (+ <div className="mon-threshold-form">+ <div className="form-group">+ <Label htmlFor="fleet-threshold-server">Applies to</Label>+ <select+ id="fleet-threshold-server"+ value={draft.server_id || ''}+ onChange={(e) => setDraft((p) => ({ ...p, server_id: e.target.value || undefined }))}+ >+ <option value="">Every server (fleet default)</option>+ {servers.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}+ </select>+ </div>+ <div className="form-group">+ <Label htmlFor="fleet-threshold-metric">Metric</Label>+ <select+ id="fleet-threshold-metric"+ value={draft.metric}+ onChange={(e) => setDraft((p) => ({ ...p, metric: e.target.value }))}+ >+ <option value="cpu">CPU</option>+ <option value="memory">Memory</option>+ <option value="disk">Disk</option>+ </select>+ </div>+ <div className="form-group">+ <Label htmlFor="fleet-threshold-warning">Warning (%)</Label>+ <Input+ id="fleet-threshold-warning"+ type="number"+ value={draft.warning_threshold}+ onChange={(e) => setDraft((p) => ({ ...p, warning_threshold: parseFloat(e.target.value) || 80 }))}+ />+ </div>+ <div className="form-group">+ <Label htmlFor="fleet-threshold-critical">Critical (%)</Label>+ <Input+ id="fleet-threshold-critical"+ type="number"+ value={draft.critical_threshold}+ onChange={(e) => setDraft((p) => ({ ...p, critical_threshold: parseFloat(e.target.value) || 95 }))}+ />+ </div>+ <div className="form-group">+ <Label htmlFor="fleet-threshold-duration">Sustained for (s)</Label>+ <Input+ id="fleet-threshold-duration"+ type="number"+ value={draft.duration_seconds}+ onChange={(e) => setDraft((p) => ({ ...p, duration_seconds: parseInt(e.target.value, 10) || 300 }))}+ />+ </div>+ <Button size="sm" onClick={saveThreshold}>Save rule</Button>+ </div>+ )}++ {thresholds.length > 0 ? (+ <div className="mon-table-scroll">+ <table className="sk-dtable">+ <thead>+ <tr>+ <th>Applies to</th>+ <th>Metric</th>+ <th>Warning</th>+ <th>Critical</th>+ <th>Sustained</th>+ <th />+ </tr>+ </thead>+ <tbody>+ {thresholds.map((t) => (+ <tr key={t.id}>+ <td>{t.server_name || 'Every server'}</td>+ <td>{METRIC_LABELS[t.metric] || t.metric}</td>+ <td className="sk-cell-mono">{t.warning_threshold}%</td>+ <td className="sk-cell-mono">{t.critical_threshold}%</td>+ <td className="sk-cell-mono">{t.duration_seconds}s</td>+ <td className="mon-row-actions">+ <Button variant="ghost" size="sm" onClick={() => removeThreshold(t.id)}>+ <XCircle size={14} />+ </Button>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ ) : (+ <p className="mon-panel-hint">+ No per-server rules yet — paired servers fall back to their agent defaults.+ </p>+ )}+ </section>+ );+}diff --git a/frontend/src/components/monitoring/MonitoringOverview.jsx b/frontend/src/components/monitoring/MonitoringOverview.jsxnew file mode 100644index 00000000..d34b11be--- /dev/null+++ b/frontend/src/components/monitoring/MonitoringOverview.jsx@@ -0,0 +1,444 @@+import { useState, useEffect, useMemo } from 'react';+import {+ ArrowDown, ArrowUp, Boxes, Cpu, Gauge as GaugeIcon, HardDrive,+ MemoryStick, Server as ServerIcon, Siren, Timer, Zap,+} from 'lucide-react';+import api from '../../services/api';+import { formatBytes } from '@/utils/formatBytes';+import { AreaChart, KpiBand, MetricCard, Pill, Sparkline } from '@/components/ds';+import { Button } from '@/components/ui/button';+import EmptyState from '../EmptyState';+import { HOST_SCOPE, useScopeMetrics, trendOf } from './useMonitorScope';++const PERIODS = ['1h', '6h', '24h', '7d'];++// Tint per metric, matching the Servers list convention (CPU accent / RAM cyan+// / disk green) so the same metric is the same color everywhere in the panel.+// Two spellings of one decision: charts take a colour prop, MetricCard takes a+// design-system tone name.+const TONE = {+ cpu: 'var(--accent-bright)',+ memory: 'var(--cyan)',+ disk: 'var(--green)',+ extra: 'var(--violet)',+};++const TILE_TONE = { cpu: 'accent', memory: 'cyan', disk: 'green', extra: 'violet' };++function fmt(value, digits = 1) {+ if (typeof value !== 'number' || Number.isNaN(value)) return '—';+ return value.toFixed(digits);+}++function last(series) {+ return series?.length ? series[series.length - 1] : null;+}++// One overview for every host: the KPI band, the two trend charts and the+// alerts panel describe whichever server the top-bar scope picker names, and+// the Host health grid below is how you switch between them. That grid is what+// the standalone Fleet Monitor page used to be — a heatmap you had to leave+// this page to read, for numbers that belong next to these ones.+export default function MonitoringOverview({+ scope, isHost, scopeLabel, status, activeAlerts = [],+ speedTest, speedTestRunning, onRunSpeedTest,+ thresholds = {}, onScopeChange, refreshKey = 0,+}) {+ const [period, setPeriod] = useState('24h');+ const { series, loading } = useScopeMetrics(scope, period, refreshKey);++ // The fleet strip: current values per server in one call, CPU history for+ // all of them in a second — rather than one history request per card.+ const [fleet, setFleet] = useState([]);+ const [fleetSpark, setFleetSpark] = useState({});+ // The panel host isn't in the fleet comparison (it has no agent row), so its+ // card would be the only one in the strip without a line. One extra call+ // buys it the same trend as every other card, whatever the current scope.+ const [hostSpark, setHostSpark] = useState(null);++ useEffect(() => {+ let cancelled = false;+ api.getMetricsHistory(period)+ .then((res) => {+ if (cancelled) return;+ const points = Array.isArray(res?.data) ? res.data : [];+ setHostSpark(points.map((p) => p.cpu?.percent ?? p.cpu_percent ?? 0));+ })+ .catch(() => { if (!cancelled) setHostSpark(null); });+ return () => { cancelled = true; };+ }, [period, refreshKey]);++ useEffect(() => {+ let cancelled = false;+ api.getFleetHeatmap()+ .then((rows) => {+ if (cancelled) return;+ const list = Array.isArray(rows) ? rows : [];+ setFleet(list);+ if (!list.length) return;+ return api.getFleetComparison(list.map((r) => r.id), 'cpu', period)+ .then((res) => {+ if (cancelled) return;+ const byServer = {};+ (res?.series || []).forEach((s) => {+ byServer[s.server_id] = (s.data || []).map((p) => p.value ?? 0);+ });+ setFleetSpark(byServer);+ })+ .catch(() => { if (!cancelled) setFleetSpark({}); });+ })+ .catch(() => { if (!cancelled) setFleet([]); });+ return () => { cancelled = true; };+ }, [period, refreshKey]);++ const hostMetrics = status?.current_metrics || {};+ const scopeRow = !isHost ? fleet.find((r) => String(r.id) === String(scope)) : null;++ // Current value per metric: the live reading for the panel host, the newest+ // stored sample for a paired server (whose agent reports on its own cadence).+ const current = useMemo(() => {+ if (isHost) {+ return {+ cpu: hostMetrics.cpu?.percent,+ memory: hostMetrics.memory?.percent,+ disk: hostMetrics.disk?.percent,+ load: hostMetrics.load_average?.['1min'],+ containers: null,+ };+ }+ return {+ cpu: scopeRow?.cpu ?? last(series?.cpu),+ memory: scopeRow?.memory ?? last(series?.memory),+ disk: scopeRow?.disk ?? last(series?.disk),+ load: null,+ containers: scopeRow?.containers ?? null,+ };+ }, [isHost, hostMetrics, scopeRow, series]);++ const tiles = [+ {+ key: 'cpu',+ label: 'CPU usage',+ icon: Cpu,+ value: fmt(current.cpu),+ unit: '%',+ spark: series?.cpu,+ tone: 'cpu',+ sub: isHost && hostMetrics.cpu?.cores ? `${hostMetrics.cpu.cores} cores` : null,+ limit: thresholds.cpu_percent,+ },+ {+ key: 'memory',+ label: 'Memory usage',+ icon: MemoryStick,+ value: fmt(current.memory),+ unit: '%',+ spark: series?.memory,+ tone: 'memory',+ sub: isHost && hostMetrics.memory?.total+ ? `${formatBytes(hostMetrics.memory.used)} / ${formatBytes(hostMetrics.memory.total)}`+ : null,+ limit: thresholds.memory_percent,+ },+ {+ key: 'disk',+ label: 'Disk usage',+ icon: HardDrive,+ value: fmt(current.disk),+ unit: '%',+ spark: series?.disk,+ tone: 'disk',+ sub: isHost && hostMetrics.disk?.total+ ? `${formatBytes(hostMetrics.disk.used)} / ${formatBytes(hostMetrics.disk.total)}`+ : null,+ limit: thresholds.disk_percent,+ },+ // The fourth tile is the one thing each scope has that the other+ // doesn't: load average is a local reading, container count comes off+ // the agent. Same slot, different question.+ isHost+ ? {+ key: 'load',+ label: 'Load average',+ icon: GaugeIcon,+ value: fmt(current.load, 2),+ unit: '',+ spark: null,+ tone: 'extra',+ sub: `5m ${fmt(hostMetrics.load_average?.['5min'], 2)} · 15m ${fmt(hostMetrics.load_average?.['15min'], 2)}`,+ limit: thresholds.load_average,+ }+ : {+ key: 'containers',+ label: 'Containers running',+ icon: Boxes,+ value: current.containers == null ? '—' : String(current.containers),+ unit: '',+ spark: null,+ tone: 'extra',+ sub: scopeRow?.status ? `agent ${scopeRow.status}` : null,+ limit: null,+ },+ ];++ const online = fleet.filter((s) => s.status === 'online').length;++ return (+ <div className="mon-overview">+ {/* The shared DS tile, not a monitoring-only copy of it — same+ geometry as every other KPI strip in the panel, plus the+ sparkline slot this page needed. */}+ <KpiBand max={4}>+ {tiles.map((tile) => {+ const numeric = Number(tile.value);+ const alerting = tile.limit != null && !Number.isNaN(numeric) && numeric > tile.limit;+ const trend = trendOf(tile.spark);+ return (+ <MetricCard+ key={tile.key}+ tone={alerting ? 'amber' : TILE_TONE[tile.tone]}+ className={alerting ? 'is-alerting' : undefined}+ icon={<tile.icon size={16} />}+ value={tile.value}+ unit={tile.unit || undefined}+ label={tile.label}+ trend={trend == null ? undefined : (+ <>+ {trend > 0 ? <ArrowUp size={11} /> : <ArrowDown size={11} />}+ {Math.abs(trend).toFixed(1)}+ </>+ )}+ // On a resource gauge, "up" is the bad direction —+ // rising CPU is not good news the way rising revenue+ // would be, so the tones are deliberately inverted.+ trendDir={trend == null ? 'flat' : trend > 0 ? 'down' : 'up'}+ spark={tile.spark?.length > 1 ? (+ <AreaChart+ series={[tile.spark]}+ colors={[alerting ? 'var(--amber)' : TONE[tile.tone]]}+ height={34}+ grid={false}+ />+ ) : undefined}+ >+ {tile.sub && <div className="sk-kpi__sub"><span>{tile.sub}</span></div>}+ </MetricCard>+ );+ })}+ </KpiBand>++ <div className="mon-grid2">+ <section className="monitoring-panel">+ <div className="monitoring-panel__header">+ <div>+ <h3>Processor</h3>+ <span className="mon-panel-sub">{scopeLabel} · CPU % · last {period}</span>+ </div>+ <div className="mon-period-switch" role="group" aria-label="Chart period">+ {PERIODS.map((p) => (+ <Button+ key={p}+ size="sm"+ variant={period === p ? 'default' : 'ghost'}+ onClick={() => setPeriod(p)}+ >+ {p}+ </Button>+ ))}+ </div>+ </div>+ <ChartBody loading={loading} values={series?.cpu}>+ <AreaChart series={[series?.cpu || []]} colors={[TONE.cpu]} height={180} />+ </ChartBody>+ </section>++ <section className="monitoring-panel">+ <div className="monitoring-panel__header">+ <div>+ <h3>Memory & disk</h3>+ <span className="mon-panel-sub">{scopeLabel} · percent used · last {period}</span>+ </div>+ <div className="mon-legend">+ <span><i className="is-memory" />Memory</span>+ <span><i className="is-disk" />Disk</span>+ </div>+ </div>+ <ChartBody loading={loading} values={series?.memory}>+ <AreaChart+ series={[series?.memory || [], series?.disk || []]}+ colors={[TONE.memory, TONE.disk]}+ height={180}+ />+ </ChartBody>+ </section>+ </div>++ {/* The fleet, inline. Clicking a card re-scopes everything above it,+ which is the whole reason this replaced a separate page. */}+ {fleet.length > 0 && (+ <>+ <div className="mon-section-head">+ <h3>Host health</h3>+ <span className="mon-section-head__meta">{online}/{fleet.length} online</span>+ </div>+ <div className="mon-fleet-grid">+ {/* Always the panel host's own numbers, never the+ scoped ones — a card in this strip has to keep+ describing its own machine while another is+ selected, or the strip stops being a comparison. */}+ <HostCard+ active={isHost}+ name="This server"+ sub="Panel host"+ status={status?.enabled ? 'online' : 'idle'}+ cpu={hostMetrics.cpu?.percent}+ memory={hostMetrics.memory?.percent}+ disk={hostMetrics.disk?.percent}+ spark={hostSpark}+ onClick={() => onScopeChange(HOST_SCOPE)}+ />+ {fleet.map((s) => (+ <HostCard+ key={s.id}+ active={String(scope) === String(s.id)}+ name={s.name}+ sub={s.group_name || 'Ungrouped'}+ status={s.status}+ cpu={s.cpu}+ memory={s.memory}+ disk={s.disk}+ spark={fleetSpark[s.id]}+ onClick={() => onScopeChange(s.id)}+ />+ ))}+ </div>+ </>+ )}++ <div className="mon-grid2">+ <section className={`monitoring-panel${activeAlerts.length ? ' monitoring-panel--warning' : ''}`}>+ <div className="monitoring-panel__header">+ <h3>Active alerts</h3>+ <span className="mon-panel-sub">{activeAlerts.length} firing</span>+ </div>+ {activeAlerts.length === 0 ? (+ <p className="mon-panel-hint"><Siren size={14} /> Nothing is over its limit right now.</p>+ ) : (+ <div className="mon-alert-list">+ {activeAlerts.map((alert, i) => (+ <div key={`${alert.type}-${i}`} className="mon-alert-row">+ <span className={`mon-sev mon-sev--${alert.severity}`} />+ <div className="mon-alert-row__body">+ <div className="mon-alert-row__title">{alert.message}</div>+ <div className="mon-alert-row__sub">+ {alert.type} · {fmt(alert.value)} / {alert.threshold}+ </div>+ </div>+ <span className="mon-state mon-state--red">firing</span>+ </div>+ ))}+ </div>+ )}+ </section>++ <section className="monitoring-panel">+ <div className="monitoring-panel__header">+ <h3>Speed test</h3>+ <Button size="sm" variant="outline" onClick={onRunSpeedTest} disabled={speedTestRunning}>+ <Zap size={14} />+ {speedTestRunning ? 'Running…' : 'Run test'}+ </Button>+ </div>+ {speedTest?.last_result ? (+ <>+ <div className="mon-speed-row">+ {[+ { icon: ArrowDown, label: 'Down', value: fmt(speedTest.last_result.download_mbps), unit: 'Mbps', tone: 'cpu' },+ { icon: ArrowUp, label: 'Up', value: fmt(speedTest.last_result.upload_mbps), unit: 'Mbps', tone: 'memory' },+ { icon: Timer, label: 'Latency', value: fmt(speedTest.last_result.latency_ms, 0), unit: 'ms', tone: 'extra' },+ ].map((s) => {+ const Icon = s.icon;+ return (+ <div key={s.label} className="mon-speed">+ <span className={`mon-speed__ico is-${s.tone}`}><Icon size={15} /></span>+ <span className="mon-speed__val">{s.value}<small>{s.unit}</small></span>+ <span className="mon-speed__label">{s.label}</span>+ </div>+ );+ })}+ </div>+ <div className="mon-speed-meta">+ <Pill kind={speedTest.last_result.success === false ? 'red' : 'green'}>+ {speedTest.last_result.success === false ? 'failed' : 'ok'}+ </Pill>+ <span>+ Tested {speedTest.last_result.tested_at+ ? new Date(speedTest.last_result.tested_at).toLocaleString()+ : 'never'}+ </span>+ </div>+ </>+ ) : (+ <p className="mon-panel-hint">+ No speed test yet — run one to measure this server's connection.+ </p>+ )}+ </section>+ </div>+ </div>+ );+}++// A chart with nothing behind it should say so rather than draw an empty box:+// on a fresh install the collector simply hasn't run yet.+function ChartBody({ loading, values, children }) {+ if (loading) return <EmptyState loading loadingVariant="chart" title="Loading metrics" />;+ if (!values || values.length < 2) {+ return (+ <p className="mon-panel-hint">+ No history yet for this host — samples are collected on the monitoring interval.+ </p>+ );+ }+ return children;+}++function HostCard({ active, name, sub, status, cpu, memory, disk, spark, onClick }) {+ const kind = status === 'online' ? 'green' : status === 'offline' ? 'red' : 'gray';+ const hot = typeof cpu === 'number' && cpu > 75;+ return (+ <button+ type="button"+ className={`mon-host${active ? ' is-active' : ''}`}+ onClick={onClick}+ aria-pressed={active}+ title={`Monitor ${name}`}+ >+ <span className="mon-host__head">+ <span className="mon-host__ico"><ServerIcon size={14} /></span>+ <span className="mon-host__name">+ {name}+ <small>{sub}</small>+ </span>+ <Pill kind={kind}>{status || 'unknown'}</Pill>+ </span>+ {spark?.length > 1 ? (+ <span className="mon-host__spark">+ <Sparkline+ data={spark}+ width={240}+ height={38}+ color={status === 'offline' ? 'var(--text-ghost)' : hot ? 'var(--amber)' : 'var(--accent-bright)'}+ />+ </span>+ ) : (+ <span className="mon-host__spark mon-host__spark--empty" />+ )}+ <span className="mon-host__mini">+ <span>CPU <b>{cpu == null ? '—' : `${fmt(cpu, 0)}%`}</b></span>+ <span>MEM <b>{memory == null ? '—' : `${fmt(memory, 0)}%`}</b></span>+ <span>DSK <b>{disk == null ? '—' : `${fmt(disk, 0)}%`}</b></span>+ </span>+ </button>+ );+}diff --git a/frontend/src/components/monitoring/ServerScopePicker.jsx b/frontend/src/components/monitoring/ServerScopePicker.jsxnew file mode 100644index 00000000..414210af--- /dev/null+++ b/frontend/src/components/monitoring/ServerScopePicker.jsx@@ -0,0 +1,58 @@+import { Check, ChevronDown, Server as ServerIcon, HardDrive } from 'lucide-react';+import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/popover';+import { useState } from 'react';+import { HOST_SCOPE } from './useMonitorScope';++// Top-bar control that picks which host every Monitoring section describes.+// Hidden entirely when nothing is paired — with one machine there is no choice+// to make, and an inert dropdown is worse than no dropdown.+export default function ServerScopePicker({ scope, servers, onChange, label }) {+ const [open, setOpen] = useState(false);+ if (!servers.length) return null;++ const pick = (value) => { onChange(value); setOpen(false); };++ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <button type="button" className="mon-scope" aria-label="Choose which server to monitor">+ <span className="mon-scope__ico">+ {scope === HOST_SCOPE ? <HardDrive size={14} /> : <ServerIcon size={14} />}+ </span>+ <span className="mon-scope__label">{label}</span>+ <ChevronDown size={14} className="mon-scope__chev" />+ </button>+ </PopoverTrigger>+ <PopoverContent align="end" sideOffset={6} className="ui-popover-content mon-scope__menu">+ <button+ type="button"+ className={`mon-scope__item${scope === HOST_SCOPE ? ' is-on' : ''}`}+ onClick={() => pick(HOST_SCOPE)}+ >+ <HardDrive size={14} />+ <span>+ This server+ <small>The machine running the panel</small>+ </span>+ {scope === HOST_SCOPE && <Check size={14} />}+ </button>+ <div className="mon-scope__sep" />+ {servers.map((s) => (+ <button+ key={s.id}+ type="button"+ className={`mon-scope__item${String(scope) === String(s.id) ? ' is-on' : ''}`}+ onClick={() => pick(s.id)}+ >+ <ServerIcon size={14} />+ <span>+ {s.name}+ <small>{s.hostname || s.ip_address || s.status || 'agent'}</small>+ </span>+ {String(scope) === String(s.id) && <Check size={14} />}+ </button>+ ))}+ </PopoverContent>+ </Popover>+ );+}diff --git a/frontend/src/components/monitoring/fleetMetrics.js b/frontend/src/components/monitoring/fleetMetrics.jsnew file mode 100644index 00000000..e7d64d47--- /dev/null+++ b/frontend/src/components/monitoring/fleetMetrics.js@@ -0,0 +1,28 @@+// Shared vocabulary for the fleet-scoped monitoring panels (heatmap, capacity,+// fleet alerts). These used to live inside the standalone Fleet Monitor page;+// they moved here when that page folded into /monitoring so the three panels+// can share one metric label map and one heat scale.++export const CHART_COLORS = [+ '#6366f1', '#ec4899', '#14b8a6', '#f59e0b',+ '#8b5cf6', '#06b6d4', '#ef4444', '#22c55e',+ '#a855f7', '#f97316',+];++export const METRIC_LABELS = {+ cpu: 'CPU %',+ memory: 'Memory %',+ disk: 'Disk %',+ network_rx: 'Network RX',+ network_tx: 'Network TX',+};++// Percentage → heat bucket. Drives the `is-*` class on heatmap cells and the+// legend dots (see styles/pages/_fleet-monitor.scss).+export const heatLevel = (value) => {+ if (value == null) return 'empty';+ if (value >= 90) return 'critical';+ if (value >= 75) return 'high';+ if (value >= 50) return 'medium';+ return 'low';+};diff --git a/frontend/src/components/monitoring/monitorTabs.jsx b/frontend/src/components/monitoring/monitorTabs.jsxindex 71cc04d6..05729202 100644--- a/frontend/src/components/monitoring/monitorTabs.jsx+++ b/frontend/src/components/monitoring/monitorTabs.jsx@@ -1,13 +1,23 @@-import { Activity, ScrollText } from 'lucide-react';+import { Activity, Bell, Gauge, ScrollText, SlidersHorizontal, Stethoscope } from 'lucide-react';-// Shared sub-nav for the Observability page group — Monitoring (live metrics +-// alerts) and Events (the unified SystemEvent stream, formerly "Telemetry").-// Rendered in each page's <PageTopbar tabs={MONITOR_TABS}>. Fleet Monitor stays-// under the Servers group (it is server-scoped); GPU is its own hardware page.+// Shared sub-nav for the Observability page group. The Monitoring page's own+// sections live HERE, in the group's one top bar, rather than in a second tab+// strip inside the page — a nav under a nav reads as two competing headers+// (and is what the design mock does: its tabs sit in the top bar).+//+// Which host each section describes is a separate axis, carried by the top-bar+// server picker as `?server=` — so Overview/Alerts/Capacity all follow the same+// scope. Fleet Monitor used to be a page of its own under Servers; its heatmap+// is now the Host health grid on Overview, and its analytics are Capacity.+//// The Status Pages tab is contributed by the serverkit-status builtin extension// (tab-group contribution, #43) and merged in by TabGroupLayout// groupId="monitoring".export const MONITOR_TABS = [- { to: '/monitoring', label: 'Monitoring', end: true, icon: <Activity size={15} /> },+ { to: '/monitoring', label: 'Overview', end: true, icon: <Activity size={15} /> },+ { to: '/monitoring/alerts', label: 'Alerts', icon: <Bell size={15} /> },+ { to: '/monitoring/rules', label: 'Rules', icon: <SlidersHorizontal size={15} /> },+ { to: '/monitoring/capacity', label: 'Capacity', icon: <Gauge size={15} /> },+ { to: '/monitoring/doctor', label: 'Doctor', icon: <Stethoscope size={15} /> },{ to: '/telemetry', label: 'Events', icon: <ScrollText size={15} /> },];diff --git a/frontend/src/components/monitoring/useMonitorScope.js b/frontend/src/components/monitoring/useMonitorScope.jsnew file mode 100644index 00000000..9e83f123--- /dev/null+++ b/frontend/src/components/monitoring/useMonitorScope.js@@ -0,0 +1,106 @@+import { useState, useEffect, useMemo } from 'react';+import { useSearchParams } from 'react-router-dom';+import api from '../../services/api';++// Which host the Monitoring pages are describing. Kept in the URL (`?server=`)+// rather than component state so it survives a tab change, a refresh, and a+// pasted link — every section under /monitoring reads the same scope.+//+// `host` is the panel's own machine (the one /monitoring/status reports on);+// any other value is a paired server id.+export const HOST_SCOPE = 'host';++export function useMonitorScope() {+ const [params, setParams] = useSearchParams();+ const [servers, setServers] = useState([]);++ useEffect(() => {+ let cancelled = false;+ api.getServers()+ .then((data) => {+ if (cancelled) return;+ const list = data?.servers || data;+ setServers(Array.isArray(list) ? list : []);+ })+ .catch(() => { if (!cancelled) setServers([]); });+ return () => { cancelled = true; };+ }, []);++ const scope = params.get('server') || HOST_SCOPE;++ const setScope = (next) => {+ const p = new URLSearchParams(params);+ if (!next || next === HOST_SCOPE) p.delete('server');+ else p.set('server', next);+ setParams(p, { replace: true });+ };++ // A scope pointing at a server that has since been unpaired falls back to+ // the panel host rather than rendering an empty page.+ const server = useMemo(+ () => servers.find((s) => String(s.id) === String(scope)) || null,+ [servers, scope],+ );+ const effective = scope === HOST_SCOPE || server ? scope : HOST_SCOPE;++ return {+ scope: effective,+ isHost: effective === HOST_SCOPE,+ server,+ servers,+ setScope,+ label: effective === HOST_SCOPE ? 'This server' : (server?.name || 'Unknown server'),+ };+}++// Metric history for whichever host is in scope. The panel host and a paired+// server come from different endpoints with slightly different point shapes,+// so normalize both to plain number[] series here — every caller downstream+// (KPI sparklines, the big charts) then works the same for either scope.+export function useScopeMetrics(scope, period, refreshKey = 0) {+ const [series, setSeries] = useState(null);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ let cancelled = false;+ setLoading(true);+ const request = scope === HOST_SCOPE+ ? api.getMetricsHistory(period)+ : api.getServerMetricsHistory(scope, period);+ request+ .then((res) => {+ if (cancelled) return;+ const points = Array.isArray(res?.data) ? res.data : [];+ setSeries({+ cpu: points.map((p) => num(p.cpu?.percent ?? p.cpu_percent)),+ memory: points.map((p) => num(p.memory?.percent ?? p.memory_percent)),+ disk: points.map((p) => num(p.disk?.percent ?? p.disk_percent)),+ timestamps: points.map((p) => p.timestamp),+ summary: res?.summary || null,+ });+ })+ .catch(() => { if (!cancelled) setSeries(null); })+ .finally(() => { if (!cancelled) setLoading(false); });+ return () => { cancelled = true; };+ }, [scope, period, refreshKey]);++ return { series, loading };+}++function num(value) {+ return typeof value === 'number' && !Number.isNaN(value) ? value : 0;+}++// Change over the window: mean of the last third against the mean of the+// first third. A first-vs-last-point delta reads as noise on a jittery series;+// comparing block means says whether the metric is actually trending.+export function trendOf(values) {+ // Explicitly null for the tiles that have no series (load average, container+ // count) — a default parameter only covers `undefined`.+ if (!values || values.length < 6) return null;+ const block = Math.floor(values.length / 3);+ const mean = (xs) => xs.reduce((a, b) => a + b, 0) / (xs.length || 1);+ const delta = mean(values.slice(-block)) - mean(values.slice(0, block));+ if (Math.abs(delta) < 0.5) return null;+ return delta;+}diff --git a/frontend/src/components/servers/serverTabs.jsx b/frontend/src/components/servers/serverTabs.jsxindex 0b829f35..7f07057a 100644--- a/frontend/src/components/servers/serverTabs.jsx+++ b/frontend/src/components/servers/serverTabs.jsx@@ -1,9 +1,11 @@-import { Server, Users, Activity, FileCog, Network } from 'lucide-react';+import { Server, Users, FileCog, Network } from 'lucide-react';// Shared sub-nav for the Servers page group (Servers / Agent Fleet / Fleet-// Monitor / Fleet Proxy / Config Templates). Rendered in each page's+// Proxy / Config Templates). Rendered in each page's// <PageTopbar tabs={SERVER_TABS}> — the demo's top-bar layout replaces the// old sidebar sub-menu (see docs/REDESIGN_MAP.md §6 decision 3).+// Fleet Monitor used to sit here; it folded into /monitoring, which was already+// asking the same questions about the panel host.// The Cloud Servers and Remote Access tabs are contributed by the// serverkit-cloud-provision and serverkit-remote-access builtin extensions// (tab-group contribution, #43) and merged in by TabGroupLayout@@ -12,7 +14,6 @@ import { Server, Users, Activity, FileCog, Network } from 'lucide-react';export const SERVER_TABS = [{ to: '/servers', label: 'Servers', end: true, icon: <Server size={15} /> },{ to: '/fleet', label: 'Agent Fleet', icon: <Users size={15} /> },- { to: '/fleet-monitor', label: 'Fleet Monitor', icon: <Activity size={15} /> },{ to: '/fleet-proxy', label: 'Fleet Proxy', icon: <Network size={15} /> },{ to: '/server-templates', label: 'Config Templates', icon: <FileCog size={15} /> },];diff --git a/frontend/src/components/sidebarItems.js b/frontend/src/components/sidebarItems.jsindex 24cbd598..348b5700 100644--- a/frontend/src/components/sidebarItems.js+++ b/frontend/src/components/sidebarItems.js@@ -49,15 +49,16 @@ export const SIDEBAR_ITEMS = [},{// Redesign: Servers uses the top-bar layout (REDESIGN_MAP §6 decision 3).- // Its Agent Fleet / Fleet Monitor / Cloud Servers / Config Templates+ // Its Agent Fleet / Fleet Proxy / Cloud Servers / Config Templates// sub-nav now lives in the page's top bar (PageTopbar SERVER_TABS), not- // as sidebar sub-items. Routes /fleet, /fleet-monitor, /cloud,+ // as sidebar sub-items. Routes /fleet, /fleet-proxy, /cloud,// /server-templates are unchanged and reachable from those tabs.+ // (Fleet Monitor left this group for /monitoring.)id: 'servers',label: 'Servers',route: '/servers',// Keep "Servers" lit across the whole tab group (Agent Fleet, Fleet- // Monitor, Cloud Servers, Config Templates) — see serverTabs.jsx.+ // Proxy, Cloud Servers, Config Templates) — see serverTabs.jsx.matchPrefixes: groupPrefixes(SERVER_TABS),category: 'infrastructure',icon: '<rect x="2" y="2" width="20" height="8" rx="2" ry="2"/><rect x="2" y="14" width="20" height="8" rx="2" ry="2"/><line x1="6" y1="6" x2="6.01" y2="6"/><line x1="6" y1="18" x2="6.01" y2="18"/>'@@ -125,11 +126,13 @@ export const SIDEBAR_ITEMS = [},{// Redesign: Monitoring uses the top-bar layout (REDESIGN_MAP §6 dec. 3).- // Observability group (§4): Monitoring / Events / Status Pages share the- // top bar (PageTopbar MONITOR_TABS). The sidebar entry lights for any of- // them via matchPrefixes. Events absorbed the old standalone Telemetry.+ // Its sections (Overview / Alerts / Rules / Capacity / Doctor / Events)+ // share the top bar (PageTopbar MONITOR_TABS); the sidebar entry lights+ // for any of them via matchPrefixes. Events absorbed the old standalone+ // Telemetry. Labelled "Monitoring" to match the route and the page —+ // this used to say "Observability", which named the same thing twice.id: 'monitoring',- label: 'Observability',+ label: 'Monitoring',route: '/monitoring',matchPrefixes: groupPrefixes(MONITOR_TABS),category: 'operations',diff --git a/frontend/src/data/palettePages.js b/frontend/src/data/palettePages.jsindex 1a0be4ee..036d7c7b 100644--- a/frontend/src/data/palettePages.js+++ b/frontend/src/data/palettePages.js@@ -20,14 +20,16 @@ export const PALETTE_PAGES = [{ label: 'Templates', path: '/templates', navId: 'services', keywords: 'deploy one-click gallery' },{ label: 'Deployments', path: '/deployments', navId: 'services', keywords: 'deploy jobs status logs' },{ label: 'Files', path: '/files', navId: 'files', keywords: 'file manager explorer' },- { label: 'Observability', path: '/monitoring', navId: 'monitoring', keywords: 'metrics uptime monitoring alerts' },+ { label: 'Monitoring', path: '/monitoring', navId: 'monitoring', keywords: 'metrics uptime observability alerts host health' },{ label: 'Events', path: '/telemetry', navId: 'monitoring', keywords: 'telemetry metrics observability system events' },{ label: 'Backups', path: '/backups', navId: 'backups', keywords: 'snapshots restore protection' },{ label: 'Cron Jobs', path: '/cron', navId: 'cron', keywords: 'schedule tasks' },{ label: 'Security', path: '/security', navId: 'security', keywords: 'firewall fail2ban' },{ label: 'Terminal', path: '/terminal', navId: 'terminal', keywords: 'shell ssh console logs' },{ label: 'Servers', path: '/servers', navId: 'servers', keywords: 'fleet agents' },- { label: 'Fleet Monitor', path: '/fleet-monitor', navId: 'servers', keywords: 'agents status' },+ { label: 'Fleet Monitor', path: '/monitoring', navId: 'monitoring', keywords: 'agents status heatmap fleet host health servers' },+ { label: 'Capacity Forecast', path: '/monitoring/capacity', navId: 'monitoring', keywords: 'compare anomaly forecast disk trend' },+ { label: 'Alert Rules', path: '/monitoring/rules', navId: 'monitoring', keywords: 'thresholds limits notifications delivery' },{ label: 'Extensions', path: '/extensions', navId: 'marketplace', keywords: 'extensions plugins marketplace' },{ label: 'Downloads', path: '/downloads', navId: 'marketplace', keywords: 'agent installer' },{ label: 'Import a Site', path: '/imports', keywords: 'import migrate cpanel directadmin hestia backup adoption move existing' },diff --git a/frontend/src/pages/FleetMonitor.jsx b/frontend/src/pages/FleetMonitor.jsxdeleted file mode 100644index d2044ded..00000000--- a/frontend/src/pages/FleetMonitor.jsx+++ /dev/null@@ -1,847 +0,0 @@-import { useState, useEffect, useMemo } from 'react';-import { useTopbarActions } from '@/hooks/useTopbarActions';-import {- Activity,- AlertTriangle,- BarChart3,- CheckCircle,- ChevronDown,- Download,- Eye,- Layers,- RefreshCw,- Search,- Server,- TrendingUp,- XCircle,- Zap-} from 'lucide-react';-import {- LineChart, Line, AreaChart, Area, XAxis, YAxis,- CartesianGrid, Tooltip, ResponsiveContainer, Legend-} from 'recharts';-import api from '../services/api';-import { useToast } from '../contexts/ToastContext';-import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';-import { Pill } from '@/components/ds';--const CHART_COLORS = [- '#6366f1', '#ec4899', '#14b8a6', '#f59e0b',- '#8b5cf6', '#06b6d4', '#ef4444', '#22c55e',- '#a855f7', '#f97316'-];--const METRIC_LABELS = {- cpu: 'CPU %',- memory: 'Memory %',- disk: 'Disk %',- network_rx: 'Network RX',- network_tx: 'Network TX'-};--const heatLevel = (value) => {- if (value == null) return 'empty';- if (value >= 90) return 'critical';- if (value >= 75) return 'high';- if (value >= 50) return 'medium';- return 'low';-};--const heatColor = (value) => {- const level = heatLevel(value);- if (level === 'empty') return 'var(--card-bg)';- if (level === 'critical') return 'var(--red)';- if (level === 'high') return '#f97316';- if (level === 'medium') return 'var(--amber)';- return 'var(--green)';-};--const FleetMonitor = () => {- const [activeTab, setActiveTab] = useState('overview');- const [loading, setLoading] = useState(true);- const toast = useToast();-- // Publish the Refresh button to the shared tab-group top bar; re-registers- // on `loading` so the spinner/disabled state stays in sync.- useTopbarActions(() =>- <Button size="sm" onClick={fetchTabData} disabled={loading}>- <RefreshCw size={18} className={loading ? 'animate-spin' : ''} />- Refresh- </Button>,- [loading]- );-- // Overview state- const [heatmapData, setHeatmapData] = useState([]);-- // Comparison state- const [servers, setServers] = useState([]);- const [selectedServers, setSelectedServers] = useState([]);- const [compMetric, setCompMetric] = useState('cpu');- const [compPeriod, setCompPeriod] = useState('24h');- const [compData, setCompData] = useState(null);-- // Alerts state- const [alerts, setAlerts] = useState([]);- const [thresholds, setThresholds] = useState([]);- const [alertFilter, setAlertFilter] = useState('active');- const [newThreshold, setNewThreshold] = useState({- metric: 'cpu', warning_threshold: 80, critical_threshold: 95, duration_seconds: 300- });-- // Anomaly/Forecast state- const [anomalies, setAnomalies] = useState([]);- const [forecastServer, setForecastServer] = useState('');- const [forecastMetric, setForecastMetric] = useState('disk');- const [forecast, setForecast] = useState(null);-- // Search state- const [searchQuery, setSearchQuery] = useState('');- const [searchType, setSearchType] = useState('any');- const [searchResults, setSearchResults] = useState([]);-- useEffect(() => {- loadServers();- }, []);-- useEffect(() => {- fetchTabData();- }, [activeTab, alertFilter]);-- const loadServers = async () => {- try {- const data = await api.getServers();- const list = data.servers || data;- setServers(Array.isArray(list) ? list : []);- } catch (e) {- console.error('Error loading servers:', e);- }- };-- const fetchTabData = async () => {- setLoading(true);- try {- if (activeTab === 'overview') {- const data = await api.getFleetHeatmap();- setHeatmapData(data);- } else if (activeTab === 'alerts') {- const [alertData, thresholdData] = await Promise.all([- api.getFleetAlerts({ status: alertFilter !== 'all' ? alertFilter : undefined }),- api.getFleetThresholds()- ]);- setAlerts(alertData);- setThresholds(thresholdData);- } else if (activeTab === 'anomalies') {- const data = await api.getFleetAnomalies();- setAnomalies(data);- }- } catch (e) {- console.error('Error fetching tab data:', e);- } finally {- setLoading(false);- }- };-- const loadComparison = async () => {- if (selectedServers.length === 0) return;- setLoading(true);- try {- const data = await api.getFleetComparison(selectedServers, compMetric, compPeriod);- setCompData(data);- } catch (e) {- toast.error('Failed to load comparison data');- } finally {- setLoading(false);- }- };-- const loadForecast = async (serverId) => {- try {- const data = await api.getCapacityForecast(serverId || forecastServer, forecastMetric);- setForecast(data);- } catch (e) {- toast.error('Failed to load forecast');- }- };-- const handleSearch = async () => {- if (searchQuery.length < 2) return;- setLoading(true);- try {- const data = await api.searchFleet(searchQuery, searchType);- setSearchResults(data);- } catch (e) {- toast.error('Search failed');- } finally {- setLoading(false);- }- };-- const acknowledgeAlert = async (id) => {- try {- await api.acknowledgeFleetAlert(id);- fetchTabData();- } catch (e) {- toast.error('Failed to acknowledge alert');- }- };-- const resolveAlert = async (id) => {- try {- await api.resolveFleetAlert(id);- fetchTabData();- } catch (e) {- toast.error('Failed to resolve alert');- }- };-- const saveThreshold = async () => {- try {- await api.createFleetThreshold(newThreshold);- toast.success('Threshold saved');- fetchTabData();- } catch (e) {- toast.error('Failed to save threshold');- }- };-- const deleteThreshold = async (id) => {- try {- await api.deleteFleetThreshold(id);- fetchTabData();- } catch (e) {- toast.error('Failed to delete threshold');- }- };-- const toggleServer = (id) => {- setSelectedServers(prev =>- prev.includes(id) ? prev.filter(s => s !== id) : [...prev, id]- );- };-- // Merge comparison series into recharts-compatible format- const compChartData = useMemo(() => {- if (!compData?.series?.length) return [];- const timeMap = {};- compData.series.forEach((s, idx) => {- s.data.forEach(point => {- if (!timeMap[point.timestamp]) {- timeMap[point.timestamp] = { timestamp: point.timestamp };- }- timeMap[point.timestamp][s.name] = point.value;- });- });- return Object.values(timeMap).sort((a, b) => a.timestamp.localeCompare(b.timestamp));- }, [compData]);-- const exportCsv = async () => {- if (selectedServers.length === 0) return;- try {- const blob = await api.exportFleetCsv(selectedServers, compMetric, compPeriod);- const url = URL.createObjectURL(blob);- const a = document.createElement('a');- a.href = url;- a.download = `fleet_${compMetric}_${compPeriod}.csv`;- a.click();- URL.revokeObjectURL(url);- } catch (e) {- toast.error('Export failed');- }- };-- return (- <div className="sk-tabgroup__inner">- <Tabs value={activeTab} onValueChange={setActiveTab}>- <TabsList>- {[- { key: 'overview', icon: Layers, label: 'Overview' },- { key: 'comparison', icon: BarChart3, label: 'Comparison' },- { key: 'alerts', icon: AlertTriangle, label: 'Alerts' },- { key: 'anomalies', icon: TrendingUp, label: 'Anomalies & Forecast' },- { key: 'search', icon: Search, label: 'Fleet Search' },- ].map(tab => (- <TabsTrigger key={tab.key} value={tab.key}>- <tab.icon size={18} />- {tab.label}- </TabsTrigger>- ))}- </TabsList>- </Tabs>-- <div className="tab-content mt-6">- {/* ==================== Overview Heatmap ==================== */}- {activeTab === 'overview' && (- <div className="space-y-6">- <div className="card">- <div className="card-header">- <h2>Server Health Heatmap</h2>- </div>- <div className="card-body">- {heatmapData.length > 0 ? (- <div className="fleet-heatmap">- <div className="fleet-heatmap__header">- <div className="fleet-heatmap__label">Server</div>- <div className="fleet-heatmap__label">CPU</div>- <div className="fleet-heatmap__label">Memory</div>- <div className="fleet-heatmap__label">Disk</div>- <div className="fleet-heatmap__label">Containers</div>- <div className="fleet-heatmap__label">Status</div>- </div>- {heatmapData.map(server => (- <div key={server.id} className="fleet-heatmap__row">- <div className="fleet-heatmap__server">- <Server size={14} />- <span>{server.name}</span>- {server.group_name && (- <span className="text-xs text-gray-400 ml-1">({server.group_name})</span>- )}- </div>- <div- className={`fleet-heatmap__cell is-${heatLevel(server.cpu)}`}- title={`CPU: ${server.cpu ?? 'N/A'}%`}- >- {server.cpu != null ? `${server.cpu}%` : '-'}- </div>- <div- className={`fleet-heatmap__cell is-${heatLevel(server.memory)}`}- title={`Memory: ${server.memory ?? 'N/A'}%`}- >- {server.memory != null ? `${server.memory}%` : '-'}- </div>- <div- className={`fleet-heatmap__cell is-${heatLevel(server.disk)}`}- title={`Disk: ${server.disk ?? 'N/A'}%`}- >- {server.disk != null ? `${server.disk}%` : '-'}- </div>- <div className="fleet-heatmap__cell">- {server.containers ?? '-'}- </div>- <div className="fleet-heatmap__cell">- <Pill kind={server.status === 'online' ? 'green' : 'red'}>{server.status}</Pill>- </div>- </div>- ))}- </div>- ) : (- <div className="py-12 text-center text-gray-500">- <Server size={48} className="mx-auto text-gray-300 mb-4" />- <p>No servers registered. Add servers to see the fleet heatmap.</p>- </div>- )}- </div>- </div>- <div className="flex gap-3 items-center text-sm text-gray-500">- <span>Legend:</span>- <span className="flex items-center gap-1"><span className="fleet-heatmap__legend-dot is-low"></span> 0-50%</span>- <span className="flex items-center gap-1"><span className="fleet-heatmap__legend-dot is-medium"></span> 50-75%</span>- <span className="flex items-center gap-1"><span className="fleet-heatmap__legend-dot is-high"></span> 75-90%</span>- <span className="flex items-center gap-1"><span className="fleet-heatmap__legend-dot is-critical"></span> 90-100%</span>- </div>- </div>- )}-- {/* ==================== Comparison ==================== */}- {activeTab === 'comparison' && (- <div className="space-y-6">- <div className="card">- <div className="card-header flex justify-between items-center">- <h2>Server Comparison</h2>- <div className="flex gap-2">- <Button variant="ghost" size="sm" onClick={exportCsv} disabled={selectedServers.length === 0}>- <Download size={14} /> Export CSV- </Button>- </div>- </div>- <div className="card-body">- <div className="grid grid-cols-1 lg:grid-cols-4 gap-4 mb-6">- <div className="lg:col-span-2">- <label className="text-sm font-medium mb-1 block">Select Servers (click to toggle)</label>- <div className="flex flex-wrap gap-2 max-h-24 overflow-y-auto p-2 border rounded">- {servers.map(s => (- <Button- key={s.id}- size="sm"- variant={selectedServers.includes(s.id) ? 'default' : 'ghost'}- onClick={() => toggleServer(s.id)}- >- {s.name}- </Button>- ))}- </div>- </div>- <div>- <label className="text-sm font-medium mb-1 block">Metric</label>- <select className="form-select w-full" value={compMetric} onChange={e => setCompMetric(e.target.value)}>- {Object.entries(METRIC_LABELS).map(([k, v]) => (- <option key={k} value={k}>{v}</option>- ))}- </select>- </div>- <div>- <label className="text-sm font-medium mb-1 block">Period</label>- <div className="flex gap-1">- {['1h', '6h', '24h', '7d'].map(p => (- <Button- key={p}- size="sm"- variant={compPeriod === p ? 'default' : 'ghost'}- onClick={() => setCompPeriod(p)}- >- {p}- </Button>- ))}- </div>- </div>- </div>- <div className="flex justify-end mb-4">- <Button- onClick={loadComparison}- disabled={selectedServers.length === 0 || loading}- >- <BarChart3 size={16} /> Compare- </Button>- </div>-- {compChartData.length > 0 && compData?.series && (- <ResponsiveContainer width="100%" height={400}>- <AreaChart data={compChartData}>- <CartesianGrid strokeDasharray="3 3" stroke="var(--border-color)" />- <XAxis- dataKey="timestamp"- tickFormatter={v => new Date(v).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}- stroke="var(--text-secondary)"- fontSize={12}- />- <YAxis stroke="var(--text-secondary)" fontSize={12} unit="%" />- <Tooltip- labelFormatter={v => new Date(v).toLocaleString()}- contentStyle={{ backgroundColor: 'var(--card-bg)', border: '1px solid var(--border-color)' }}- />- <Legend />- {compData.series.map((s, i) => (- <Area- key={s.server_id}- type="monotone"- dataKey={s.name}- stroke={CHART_COLORS[i % CHART_COLORS.length]}- fill={CHART_COLORS[i % CHART_COLORS.length]}- fillOpacity={0.1}- strokeWidth={2}- dot={false}- />- ))}- </AreaChart>- </ResponsiveContainer>- )}-- {selectedServers.length === 0 && (- <div className="py-12 text-center text-gray-500">- <BarChart3 size={48} className="mx-auto text-gray-300 mb-4" />- <p>Select servers above to compare their metrics.</p>- </div>- )}- </div>- </div>- </div>- )}-- {/* ==================== Alerts ==================== */}- {activeTab === 'alerts' && (- <div className="space-y-6">- <div className="card">- <div className="card-header flex justify-between items-center">- <h2>Metric Alerts</h2>- <div className="flex gap-1">- {['active', 'acknowledged', 'resolved', 'all'].map(f => (- <Button- key={f}- size="sm"- variant={alertFilter === f ? 'default' : 'ghost'}- onClick={() => setAlertFilter(f)}- >- {f.charAt(0).toUpperCase() + f.slice(1)}- </Button>- ))}- </div>- </div>- {alerts.length > 0 ? (- <div className="overflow-x-auto">- <table className="sk-dtable">- <thead>- <tr>- <th>Server</th>- <th>Metric</th>- <th>Value</th>- <th>Threshold</th>- <th>Severity</th>- <th>Status</th>- <th>Time</th>- <th>Actions</th>- </tr>- </thead>- <tbody>- {alerts.map(a => (- <tr key={a.id}>- <td className="font-semibold">{a.server_name}</td>- <td>{METRIC_LABELS[a.metric] || a.metric}</td>- <td className="font-mono">{a.value}%</td>- <td className="font-mono">{a.threshold}%</td>- <td>- <Pill kind={a.severity === 'critical' ? 'red' : 'amber'}>{a.severity}</Pill>- </td>- <td>- <Pill kind={a.status === 'active' ? 'red' : a.status === 'acknowledged' ? 'amber' : 'green'}>- {a.status}- </Pill>- </td>- <td className="text-sm">{new Date(a.created_at).toLocaleString()}</td>- <td className="actions">- {a.status === 'active' && (- <>- <Button variant="ghost" size="sm" onClick={() => acknowledgeAlert(a.id)}>- <Eye size={14} /> Ack- </Button>- <Button variant="ghost" size="sm" onClick={() => resolveAlert(a.id)}>- <CheckCircle size={14} />- </Button>- </>- )}- {a.status === 'acknowledged' && (- <Button variant="ghost" size="sm" onClick={() => resolveAlert(a.id)}>- <CheckCircle size={14} /> Resolve- </Button>- )}- </td>- </tr>- ))}- </tbody>- </table>- </div>- ) : (- <div className="card-body py-8 text-center text-gray-500">- <CheckCircle size={36} className="mx-auto text-gray-300 mb-3" />- <p>No {alertFilter !== 'all' ? alertFilter : ''} alerts.</p>- </div>- )}- </div>-- <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">- <div className="card">- <div className="card-header"><h2>Alert Thresholds</h2></div>- {thresholds.length > 0 ? (- <div className="overflow-x-auto">- <table className="sk-dtable">- <thead>- <tr>- <th>Scope</th>- <th>Metric</th>- <th>Warning</th>- <th>Critical</th>- <th>Duration</th>- <th></th>- </tr>- </thead>- <tbody>- {thresholds.map(t => (- <tr key={t.id}>- <td>{t.server_name || 'Global'}</td>- <td>{METRIC_LABELS[t.metric] || t.metric}</td>- <td className="text-yellow-600">{t.warning_threshold}%</td>- <td className="text-red-600">{t.critical_threshold}%</td>- <td>{t.duration_seconds}s</td>- <td>- <Button variant="ghost" size="sm" className="text-red-600" onClick={() => deleteThreshold(t.id)}>- <XCircle size={14} />- </Button>- </td>- </tr>- ))}- </tbody>- </table>- </div>- ) : (- <div className="card-body py-6 text-center text-gray-500 text-sm">- No thresholds configured. Add one to start receiving metric alerts.- </div>- )}- </div>-- <div className="card">- <div className="card-header"><h2>Add Threshold</h2></div>- <div className="card-body space-y-4">- <div className="form-group">- <label>Server (leave empty for global)</label>- <select- className="form-select w-full"- value={newThreshold.server_id || ''}- onChange={e => setNewThreshold(p => ({ ...p, server_id: e.target.value || undefined }))}- >- <option value="">Global Default</option>- {servers.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}- </select>- </div>- <div className="grid grid-cols-2 gap-4">- <div className="form-group">- <label>Metric</label>- <select className="form-select w-full" value={newThreshold.metric}- onChange={e => setNewThreshold(p => ({ ...p, metric: e.target.value }))}>- <option value="cpu">CPU</option>- <option value="memory">Memory</option>- <option value="disk">Disk</option>- </select>- </div>- <div className="form-group">- <label>Duration (seconds)</label>- <Input type="number" value={newThreshold.duration_seconds}- onChange={e => setNewThreshold(p => ({ ...p, duration_seconds: parseInt(e.target.value) || 300 }))} />- </div>- </div>- <div className="grid grid-cols-2 gap-4">- <div className="form-group">- <label>Warning (%)</label>- <Input type="number" value={newThreshold.warning_threshold}- onChange={e => setNewThreshold(p => ({ ...p, warning_threshold: parseFloat(e.target.value) || 80 }))} />- </div>- <div className="form-group">- <label>Critical (%)</label>- <Input type="number" value={newThreshold.critical_threshold}- onChange={e => setNewThreshold(p => ({ ...p, critical_threshold: parseFloat(e.target.value) || 95 }))} />- </div>- </div>- <Button className="w-full" onClick={saveThreshold}>- Save Threshold- </Button>- </div>- </div>- </div>- </div>- )}-- {/* ==================== Anomalies & Forecast ==================== */}- {activeTab === 'anomalies' && (- <div className="space-y-6">- <div className="card">- <div className="card-header"><h2>Anomaly Detection</h2></div>- {anomalies.length > 0 ? (- <div className="overflow-x-auto">- <table className="sk-dtable">- <thead>- <tr>- <th>Server</th>- <th>Metric</th>- <th>Current</th>- <th>Baseline (mean)</th>- <th>Std Dev</th>- <th>Z-Score</th>- <th>Direction</th>- </tr>- </thead>- <tbody>- {anomalies.map((a, i) => (- <tr key={i}>- <td className="font-semibold">{a.server_name}</td>- <td>{METRIC_LABELS[a.metric] || a.metric}</td>- <td className="font-mono text-red-600">{a.current_value}%</td>- <td className="font-mono">{a.mean}%</td>- <td className="font-mono">{a.stddev}</td>- <td className="font-mono font-bold">{a.z_score}</td>- <td>- <Pill kind={a.direction === 'high' ? 'red' : 'cyan'}>- {a.direction === 'high' ? 'Unusually High' : 'Unusually Low'}- </Pill>- </td>- </tr>- ))}- </tbody>- </table>- </div>- ) : (- <div className="card-body py-8 text-center text-gray-500">- <CheckCircle size={36} className="mx-auto text-gray-300 mb-3" />- <p>No anomalies detected. All metrics are within normal ranges.</p>- </div>- )}- </div>-- <div className="card">- <div className="card-header"><h2>Capacity Forecast</h2></div>- <div className="card-body">- <div className="flex gap-4 mb-6">- <div className="form-group flex-1">- <label>Server</label>- <select className="form-select w-full" value={forecastServer}- onChange={e => setForecastServer(e.target.value)}>- <option value="">Select a server...</option>- {servers.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}- </select>- </div>- <div className="form-group">- <label>Metric</label>- <select className="form-select w-full" value={forecastMetric}- onChange={e => setForecastMetric(e.target.value)}>- <option value="disk">Disk</option>- <option value="memory">Memory</option>- <option value="cpu">CPU</option>- </select>- </div>- <div className="form-group flex items-end">- <Button onClick={() => loadForecast()} disabled={!forecastServer}>- <TrendingUp size={16} /> Forecast- </Button>- </div>- </div>-- {forecast && !forecast.error && (- <div className="space-y-6">- <div className="grid grid-cols-1 md:grid-cols-3 gap-4">- <div className="fleet-statbox p-4">- <div className="text-sm text-gray-500">Current</div>- <div className="text-2xl font-bold">{forecast.current_value}%</div>- </div>- <div className="fleet-statbox p-4">- <div className="text-sm text-gray-500">Growth Rate</div>- <div className="text-2xl font-bold">{forecast.growth_rate_per_day}%/day</div>- </div>- <div className="fleet-statbox p-4">- <div className="text-sm text-gray-500">Trend</div>- <div className={`text-2xl font-bold ${forecast.trend === 'increasing' ? 'text-red-600' : forecast.trend === 'decreasing' ? 'text-green-600' : ''}`}>- {forecast.trend}- </div>- </div>- </div>-- {forecast.predictions && (- <div className="grid grid-cols-2 gap-4">- <div className={`fleet-predbox ${forecast.predictions.days_to_90pct === 0 ? 'is-red' : 'is-amber'}`}>- <div className="text-sm font-medium">Reaches 90%</div>- <div className="text-lg font-bold">- {forecast.predictions.date_90pct || 'N/A'}- {forecast.predictions.days_to_90pct != null && forecast.predictions.days_to_90pct > 0 && (- <span className="text-sm font-normal ml-2">({forecast.predictions.days_to_90pct} days)</span>- )}- </div>- </div>- <div className="fleet-predbox is-red">- <div className="text-sm font-medium">Reaches 100%</div>- <div className="text-lg font-bold">- {forecast.predictions.date_100pct || 'N/A'}- {forecast.predictions.days_to_100pct != null && forecast.predictions.days_to_100pct > 0 && (- <span className="text-sm font-normal ml-2">({forecast.predictions.days_to_100pct} days)</span>- )}- </div>- </div>- </div>- )}-- {forecast.trend_data && (- <ResponsiveContainer width="100%" height={300}>- <LineChart data={forecast.trend_data}>- <CartesianGrid strokeDasharray="3 3" stroke="var(--border-color)" />- <XAxis dataKey="date" stroke="var(--text-secondary)" fontSize={11} />- <YAxis stroke="var(--text-secondary)" fontSize={12} unit="%" domain={[0, 100]} />- <Tooltip contentStyle={{ backgroundColor: 'var(--card-bg)', border: '1px solid var(--border-color)' }} />- <Legend />- <Line type="monotone" dataKey="actual" stroke="var(--accent-bright)" strokeWidth={2} dot={false} name="Actual" />- <Line type="monotone" dataKey="trend" stroke="var(--red)" strokeWidth={2} strokeDasharray="5 5" dot={false} name="Trend" />- </LineChart>- </ResponsiveContainer>- )}- </div>- )}-- {forecast?.error && (- <div className="fleet-warnrow text-sm">- {forecast.error}- </div>- )}-- {!forecast && (- <div className="py-8 text-center text-gray-500">- <TrendingUp size={36} className="mx-auto text-gray-300 mb-3" />- <p>Select a server and metric to see capacity predictions.</p>- </div>- )}- </div>- </div>- </div>- )}-- {/* ==================== Fleet Search ==================== */}- {activeTab === 'search' && (- <div className="card">- <div className="card-header"><h2>Fleet Search</h2></div>- <div className="card-body">- <div className="flex gap-3 mb-6">- <div className="flex-1">- <Input- type="text"- placeholder="Search for servers, containers, tags..."- value={searchQuery}- onChange={e => setSearchQuery(e.target.value)}- onKeyDown={e => e.key === 'Enter' && handleSearch()}- />- </div>- <select className="form-select" value={searchType} onChange={e => setSearchType(e.target.value)}>- <option value="any">All Types</option>- <option value="server">Servers</option>- <option value="container">Containers</option>- <option value="tag">Tags</option>- </select>- <Button onClick={handleSearch} disabled={searchQuery.length < 2}>- <Search size={16} /> Search- </Button>- </div>-- {searchResults.length > 0 ? (- <div className="overflow-x-auto">- <table className="sk-dtable">- <thead>- <tr>- <th>Server</th>- <th>Type</th>- <th>Match</th>- <th>Detail</th>- <th>Status</th>- </tr>- </thead>- <tbody>- {searchResults.map((r, i) => (- <tr key={i}>- <td className="font-semibold">{r.server_name}</td>- <td><Pill kind="gray" dot={false}>{r.match_type}</Pill></td>- <td>{r.match_name}</td>- <td className="text-sm text-gray-500">{r.match_detail}</td>- <td>- <Pill kind={r.status === 'online' || r.status === 'running' ? 'green' : 'red'}>- {r.status}- </Pill>- </td>- </tr>- ))}- </tbody>- </table>- </div>- ) : searchQuery.length >= 2 && !loading ? (- <div className="py-8 text-center text-gray-500">- <Search size={36} className="mx-auto text-gray-300 mb-3" />- <p>No results found for "{searchQuery}".</p>- </div>- ) : (- <div className="py-8 text-center text-gray-500">- <Search size={36} className="mx-auto text-gray-300 mb-3" />- <p>Enter a search term to find servers, containers, or tags across your fleet.</p>- </div>- )}- </div>- </div>- )}- </div>- </div>- );-};--export default FleetMonitor;diff --git a/frontend/src/pages/Monitoring.jsx b/frontend/src/pages/Monitoring.jsxindex f64f5aac..5d1e1ff3 100644--- a/frontend/src/pages/Monitoring.jsx+++ b/frontend/src/pages/Monitoring.jsx@@ -2,38 +2,34 @@ import { useEffect, useMemo, useState } from 'react';import { Link } from 'react-router-dom';import useTabParam from '../hooks/useTabParam';import api from '../services/api';-import { formatBytes } from '@/utils/formatBytes';import { useToast } from '../contexts/ToastContext';import EmptyState from '../components/EmptyState';import DoctorPanel from '../components/monitoring/DoctorPanel';+import MonitoringOverview from '../components/monitoring/MonitoringOverview';+import FleetCapacityPanel from '../components/monitoring/FleetCapacityPanel';+import FleetAlertsPanel from '../components/monitoring/FleetAlertsPanel';+import FleetThresholdsPanel from '../components/monitoring/FleetThresholdsPanel';+import ServerScopePicker from '../components/monitoring/ServerScopePicker';+import { useMonitorScope } from '../components/monitoring/useMonitorScope';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { Label } from '@/components/ui/label';import { Switch } from '@/components/ui/switch';-import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';-import { MetricCard, Pill, Gauge } from '@/components/ds';+import { Pill } from '@/components/ds';+import { ProviderBrandIcon } from '../components/icons/ProviderBrands';import { useTopbarActions } from '@/hooks/useTopbarActions';import {- Activity,- ArrowDown,- ArrowUp,- Bell,- Clock,- Cpu,- Gauge as GaugeIcon,- HardDrive,- Mail,- MemoryStick,- PlayCircle,- RefreshCw,- Settings,- Siren,- Timer,- Webhook,- Zap,+ Activity, Bell, Cpu, Gauge as GaugeIcon, HardDrive, MemoryStick,+ PlayCircle, RefreshCw, Settings, Siren,} from 'lucide-react';-const VALID_TABS = ['overview', 'alerts', 'config', 'thresholds', 'doctor'];+// One section per top-bar tab. There is deliberately no second tab strip inside+// the page: the group's own bar (MONITOR_TABS) carries these, the way the+// design mock does — a nav under a nav reads as two competing headers.+const VALID_TABS = ['overview', 'alerts', 'rules', 'capacity', 'doctor'];++// Old deep links from when Alert Rules and Delivery were separate inner tabs.+const TAB_ALIASES = { thresholds: 'rules', config: 'rules', fleet: 'overview', 'fleet-alerts': 'alerts' };const DEFAULT_THRESHOLDS = {cpu_percent: 80,@@ -42,22 +38,28 @@ const DEFAULT_THRESHOLDS = {load_average: 5.0,};+// Brand glyphs, not three copies of the generic webhook icon: Discord, Slack+// and a raw webhook were all rendering the same shape, which made the tiles+// look broken. `brand` maps to the shared Connections icon set so a channel+// wears the same face here as it does everywhere else in the panel.const CHANNEL_META = {- discord: { label: 'Discord', icon: Webhook },- slack: { label: 'Slack', icon: Webhook },- telegram: { label: 'Telegram', icon: Bell },- email: { label: 'Email', icon: Mail },- generic_webhook: { label: 'Webhook', icon: Webhook },+ discord: { label: 'Discord', brand: 'chat_discord' },+ slack: { label: 'Slack', brand: 'chat_slack' },+ telegram: { label: 'Telegram', brand: 'chat_telegram' },+ email: { label: 'Email', brand: 'smtp' },+ generic_webhook: { label: 'Webhook', brand: 'chat_webhook' },};-// Gauge tints follow the Servers list convention (CPU accent / RAM cyan / disk green).-const METRIC_COLORS = {- cpu_percent: 'var(--accent-bright)',- memory_percent: 'var(--cyan)',- disk_percent: 'var(--green)',- load_average: 'var(--violet)',+const RULE_ICONS = {+ cpu_percent: Cpu,+ memory_percent: MemoryStick,+ disk_percent: HardDrive,+ load_average: GaugeIcon,};+const SPEEDTEST_POLL_INTERVAL_MS = 3000;+const SPEEDTEST_POLL_TIMEOUT_MS = 90000;+function formatTimestamp(timestamp) {if (!timestamp) return 'Never';return new Date(timestamp).toLocaleString();@@ -68,29 +70,12 @@ function formatNumber(value, digits = 1) {return value.toFixed(digits);}-function formatMetric(value, unit = '%') {- if (typeof value !== 'number' || Number.isNaN(value)) return '-';- return `${value.toFixed(unit === '' ? 2 : 1)}${unit}`;-}--function formatSpeedValue(value, digits = 1) {- if (typeof value !== 'number' || Number.isNaN(value)) return '—';- return value.toFixed(digits);-}--const SPEEDTEST_POLL_INTERVAL_MS = 3000;-const SPEEDTEST_POLL_TIMEOUT_MS = 90000;-function getSeverityTone(severity) {switch (severity) {- case 'critical':- return 'red';- case 'warning':- return 'amber';- case 'info':- return 'cyan';- default:- return 'gray';+ case 'critical': return 'red';+ case 'warning': return 'amber';+ case 'info': return 'cyan';+ default: return 'gray';}}@@ -104,16 +89,20 @@ const Monitoring = () => {const [savingThresholds, setSavingThresholds] = useState(false);const [checkingAlerts, setCheckingAlerts] = useState(false);const [error, setError] = useState(null);- const [activeTab, setActiveTab] = useTabParam('/monitoring', VALID_TABS);+ const [rawTab] = useTabParam('/monitoring', VALID_TABS);+ const activeTab = TAB_ALIASES[rawTab] || rawTab;- const [configForm, setConfigForm] = useState({- enabled: false,- check_interval: 60,- });+ // Which host every section on this page is describing (URL-backed, so it+ // survives tab changes and shared links).+ const { scope, isHost, server, servers, setScope, label: scopeLabel } = useMonitorScope();+ const [configForm, setConfigForm] = useState({ enabled: false, check_interval: 60 });const [thresholdForm, setThresholdForm] = useState(DEFAULT_THRESHOLDS);const [speedTest, setSpeedTest] = useState(null);const [speedTestRunning, setSpeedTestRunning] = useState(false);+ // Bumped by the top-bar Refresh so the scope-driven panels reload with the+ // host-scoped data instead of each growing a refresh button of its own.+ const [refreshKey, setRefreshKey] = useState(0);const loadSpeedTest = async () => {try {@@ -121,7 +110,7 @@ const Monitoring = () => {setSpeedTest(res);return res;} catch {- // Speed test endpoint is optional — never block the page on it.+ // Optional endpoint — never block the page on it.return null;}};@@ -162,72 +151,37 @@ const Monitoring = () => {const metrics = status?.current_metrics || {};return [{- key: 'cpu_percent',- label: 'CPU usage',- description: 'cpu',- icon: Cpu,- unit: '%',+ key: 'cpu_percent', label: 'CPU usage', unit: '%',current: metrics.cpu?.percent,threshold: thresholdForm.cpu_percent,- persistedThreshold: thresholds.cpu_percent,- gaugePct: metrics.cpu?.percent ?? 0,- mini: [{ k: 'cores', v: metrics.cpu?.cores ?? '-' }],},{- key: 'memory_percent',- label: 'Memory usage',- description: 'memory',- icon: MemoryStick,- unit: '%',+ key: 'memory_percent', label: 'Memory usage', unit: '%',current: metrics.memory?.percent,threshold: thresholdForm.memory_percent,- persistedThreshold: thresholds.memory_percent,- gaugePct: metrics.memory?.percent ?? 0,- mini: [{ k: 'used', v: `${formatBytes(metrics.memory?.used)} / ${formatBytes(metrics.memory?.total)}` }],},{- key: 'disk_percent',- label: 'Disk usage',- description: 'disk',- icon: HardDrive,- unit: '%',+ key: 'disk_percent', label: 'Disk usage', unit: '%',current: metrics.disk?.percent,threshold: thresholdForm.disk_percent,- persistedThreshold: thresholds.disk_percent,- gaugePct: metrics.disk?.percent ?? 0,- mini: [{ k: 'used', v: `${formatBytes(metrics.disk?.used)} / ${formatBytes(metrics.disk?.total)}` }],},{- key: 'load_average',- label: 'Load average',- description: 'load',- icon: GaugeIcon,- unit: '',+ key: 'load_average', label: 'Load average', unit: '',current: metrics.load_average?.['1min'],threshold: thresholdForm.load_average,- persistedThreshold: thresholds.load_average,- gaugePct: thresholds.load_average > 0- ? ((metrics.load_average?.['1min'] ?? 0) / thresholds.load_average) * 100- : 0,- mini: [- { k: '5m', v: formatNumber(metrics.load_average?.['5min'], 2) },- { k: '15m', v: formatNumber(metrics.load_average?.['15min'], 2) },- ],},];- }, [status, thresholdForm, thresholds]);+ }, [status, thresholdForm]);- const notificationChannels = useMemo(() => {- return Object.entries(status?.notifications || {}).map(([key, channel]) => ({+ const notificationChannels = useMemo(() => (+ Object.entries(status?.notifications || {}).map(([key, channel]) => ({key,...channel,- ...(CHANNEL_META[key] || { label: key, icon: Bell }),- }));- }, [status]);+ ...(CHANNEL_META[key] || { label: key, brand: null }),+ }))+ ), [status]);const activeAlerts = status?.active_alerts || [];- const enabledChannelCount = notificationChannels.filter((channel) => channel.enabled && channel.configured).length;- const alertRuleCount = metricRules.length;const handleToggleMonitoring = async () => {try {@@ -253,15 +207,10 @@ const Monitoring = () => {enabled: configForm.enabled,check_interval: Number(configForm.check_interval) || 60,});-if (configForm.enabled !== wasEnabled) {- if (configForm.enabled) {- await api.startMonitoring();- } else {- await api.stopMonitoring();- }+ if (configForm.enabled) await api.startMonitoring();+ else await api.stopMonitoring();}-toast.success('Monitoring delivery saved');await loadData();} catch (err) {@@ -315,11 +264,8 @@ const Monitoring = () => {const res = await loadSpeedTest();const latest = res?.last_result;if (latest?.tested_at && latest.tested_at !== previousTestedAt) {- if (latest.success === false) {- toast.error(latest.error || 'Speed test failed');- } else {- toast.success('Speed test complete');- }+ if (latest.success === false) toast.error(latest.error || 'Speed test failed');+ else toast.success('Speed test complete');return;}}@@ -332,16 +278,17 @@ const Monitoring = () => {};const updateThreshold = (key, value) => {- setThresholdForm((current) => ({- ...current,- [key]: value,- }));+ setThresholdForm((current) => ({ ...current, [key]: value }));};useTopbarActions(() =>(<>- <Button size="sm" variant="outline" onClick={loadData}>+ <Button+ size="sm"+ variant="outline"+ onClick={() => { loadData(); setRefreshKey((k) => k + 1); }}+ ><RefreshCw size={16} />Refresh</Button>@@ -350,21 +297,19 @@ const Monitoring = () => {variant={status?.enabled ? 'destructive' : 'default'}onClick={handleToggleMonitoring}>- {status?.enabled ? (- <>- <Activity size={16} />- Stop Monitoring- </>- ) : (- <>- <PlayCircle size={16} />- Start Monitoring- </>- )}+ {status?.enabled+ ? <><Activity size={16} />Stop Monitoring</>+ : <><PlayCircle size={16} />Start Monitoring</>}</Button>+ <ServerScopePicker+ scope={scope}+ servers={servers}+ onChange={setScope}+ label={scopeLabel}+ /></>),- [status?.enabled]+ [status?.enabled, scope, servers.length, scopeLabel]);if (loading) {@@ -384,197 +329,96 @@ const Monitoring = () => {</div>)}- <Tabs value={activeTab} onValueChange={setActiveTab}>- <TabsList>- <TabsTrigger value="overview">Overview</TabsTrigger>- <TabsTrigger value="thresholds">Alert Rules</TabsTrigger>- <TabsTrigger value="config">Delivery</TabsTrigger>- <TabsTrigger value="alerts">History</TabsTrigger>- <TabsTrigger value="doctor">Doctor</TabsTrigger>- </TabsList>-- <TabsContent value="overview">- <div className="monitoring-overview">- <section className={`monitoring-hero ${status?.enabled ? 'is-active' : ''}`}>- <div className="monitoring-hero__main">- <Pill kind={status?.enabled ? 'green' : 'gray'}>- {status?.enabled ? 'Monitoring active' : 'Monitoring paused'}- </Pill>- <h2>{activeAlerts.length > 0 ? `${activeAlerts.length} active alert${activeAlerts.length !== 1 ? 's' : ''}` : 'No active alerts'}</h2>- <p>- Checks run every {status?.check_interval || configForm.check_interval || 60} seconds.- </p>- </div>- <div className="monitoring-hero__actions">- <Button variant="outline" onClick={handleCheckAlerts} disabled={checkingAlerts}>- <Siren size={16} />- {checkingAlerts ? 'Checking...' : 'Check Now'}- </Button>- </div>- </section>-- <div className="mon-kpis">- <MetricCard- tone={activeAlerts.length > 0 ? 'red' : 'green'}- icon={<Siren size={16} />}- value={activeAlerts.length}- label="Active alerts"- />- <MetricCard- tone="accent"- icon={<GaugeIcon size={16} />}- value={alertRuleCount}- label="Alert rules"- />- <MetricCard- tone="cyan"- icon={<Bell size={16} />}- value={enabledChannelCount}- label="Delivery channels"- >- <div className="sk-kpi__sub"><span>{notificationChannels.length} total</span></div>- </MetricCard>- <MetricCard- tone="violet"- icon={<Clock size={16} />}- value={alertHistory.length}- label="History entries"- />- </div>-- <section>- <div className="mon-section-head">- <h3>Current Metrics</h3>- <Button size="sm" variant="outline" onClick={() => setActiveTab('thresholds')}>- <Settings size={14} />- Rules- </Button>- </div>- <div className="mon-host-grid">- {metricRules.map((rule) => {- const Icon = rule.icon;- const isTriggered = typeof rule.current === 'number' && rule.current > rule.persistedThreshold;- return (- <article key={rule.key} className={`mon-host-card ${isTriggered ? 'is-alerting' : ''}`}>- <div className="mon-host-card__head">- <span className="mon-ico mon-ico--sm">- <Icon size={14} />- </span>- <span className="mon-host-card__name">{rule.label}</span>- <Pill kind={isTriggered ? 'amber' : 'green'}>{isTriggered ? 'alerting' : 'ok'}</Pill>- </div>- <div className="mon-host-card__value">{formatMetric(rule.current, rule.unit)}</div>- <Gauge- value={rule.gaugePct}- color={isTriggered ? 'var(--amber)' : METRIC_COLORS[rule.key]}- />- <div className="mon-host-card__mini">- <span>limit <b>{formatMetric(rule.persistedThreshold, rule.unit)}</b></span>- {rule.mini.map((m) => (- <span key={m.k}>{m.k} <b>{m.v}</b></span>- ))}- </div>- </article>- );- })}- </div>- </section>+ {activeTab === 'overview' && (+ <MonitoringOverview+ scope={scope}+ isHost={isHost}+ scopeLabel={isHost ? 'This server' : (server?.name || scopeLabel)}+ status={status}+ activeAlerts={activeAlerts}+ speedTest={speedTest}+ speedTestRunning={speedTestRunning}+ onRunSpeedTest={handleRunSpeedTest}+ thresholds={thresholds}+ onScopeChange={setScope}+ refreshKey={refreshKey}+ />+ )}- <section className="monitoring-panel mon-speedtest">- <div className="monitoring-panel__header">- <h3>Speed Test</h3>- <Button size="sm" variant="outline" onClick={handleRunSpeedTest} disabled={speedTestRunning}>- <Zap size={14} />- {speedTestRunning ? 'Running...' : 'Run Test'}- </Button>+ {activeTab === 'alerts' && (+ <div className="monitoring-stack">+ <section className="monitoring-panel">+ <div className="monitoring-panel__header">+ <div>+ <h3>This server</h3>+ <span className="mon-panel-sub">+ {activeAlerts.length} firing · {alertHistory.length} in history+ </span></div>- {speedTest?.last_result ? (- <>- <div className="mon-speedtest__grid">- <MetricCard- tone="accent"- icon={<ArrowDown size={16} />}- value={formatSpeedValue(speedTest.last_result.download_mbps)}- label="Download (Mbps)"- />- <MetricCard- tone="cyan"- icon={<ArrowUp size={16} />}- value={formatSpeedValue(speedTest.last_result.upload_mbps)}- label="Upload (Mbps)"- />- <MetricCard- tone="violet"- icon={<Timer size={16} />}- value={formatSpeedValue(speedTest.last_result.latency_ms, 0)}- label="Latency (ms)"- />- </div>- <div className="mon-speedtest__meta">- {speedTestRunning || speedTest.running ? (- <Pill kind="amber">running</Pill>- ) : (- <Pill kind={speedTest.last_result.success === false ? 'red' : 'green'}>- {speedTest.last_result.success === false ? 'failed' : 'ok'}- </Pill>- )}- <span>Tested {formatTimestamp(speedTest.last_result.tested_at)}</span>- {speedTest.last_result.success === false && speedTest.last_result.error && (- <span className="mon-speedtest__error">{speedTest.last_result.error}</span>- )}- </div>- </>- ) : (- <div className="mon-speedtest__empty">- <span>No speed test has been run yet. Run one to measure this server's connection.</span>- </div>- )}- </section>-- {activeAlerts.length > 0 && (- <section className="monitoring-panel monitoring-panel--warning">- <div className="monitoring-panel__header">- <h3>Active Alerts</h3>- <span className="mon-firing-count">{activeAlerts.length} firing</span>- </div>- <div className="mon-alert-list">- {activeAlerts.map((alert, index) => (- <div key={`${alert.type}-${index}`} className="mon-alert-row">+ <Button variant="outline" size="sm" onClick={handleCheckAlerts} disabled={checkingAlerts}>+ <Siren size={14} />+ {checkingAlerts ? 'Checking…' : 'Check now'}+ </Button>+ </div>+ {alertHistory.length === 0 && activeAlerts.length === 0 ? (+ <p className="mon-panel-hint">+ Nothing has crossed a limit yet. Rules live one tab over.+ </p>+ ) : (+ <div className="mon-alert-list">+ {[...activeAlerts.map((a) => ({ ...a, firing: true })), ...alertHistory]+ .map((alert, index) => (+ <article key={`${alert.timestamp || 'now'}-${index}`} className="mon-alert-row"><span className={`mon-sev mon-sev--${alert.severity}`} /><div className="mon-alert-row__body"><div className="mon-alert-row__title">{alert.message}</div>- <div className="mon-alert-row__sub">{alert.type} · {formatNumber(alert.value)} / {alert.threshold}</div>+ <div className="mon-alert-row__sub">+ {alert.type} · {formatNumber(alert.value)} / {alert.threshold}+ </div></div>- <span className="mon-state mon-state--red">firing</span>- </div>+ <div className="mon-alert-row__end">+ <span className={`mon-state mon-state--${alert.firing ? 'red' : getSeverityTone(alert.severity)}`}>+ {alert.firing ? 'firing' : alert.severity}+ </span>+ <span className="mon-alert-row__time">+ {alert.firing ? 'now' : formatTimestamp(alert.timestamp)}+ </span>+ </div>+ </article>))}- </div>- </section>+ </div>)}- </div>- </TabsContent>+ </section>++ {servers.length > 0 && <FleetAlertsPanel scope={scope} refreshKey={refreshKey} />}+ </div>+ )}- <TabsContent value="thresholds">+ {activeTab === 'rules' && (+ <div className="monitoring-stack"><form className="monitoring-panel" onSubmit={handleSaveThresholds}><div className="monitoring-panel__header">- <h3>Alert Rules</h3>- <Button type="submit" disabled={savingThresholds}>- {savingThresholds ? 'Saving...' : 'Save Rules'}+ <div>+ <h3>This server</h3>+ <span className="mon-panel-sub">Limits for the machine running the panel</span>+ </div>+ <Button type="submit" size="sm" disabled={savingThresholds}>+ {savingThresholds ? 'Saving…' : 'Save rules'}</Button></div><div className="metric-rule-grid">{metricRules.map((rule) => {- const Icon = rule.icon;+ const Icon = RULE_ICONS[rule.key] || GaugeIcon;const isTriggered = typeof rule.current === 'number' && rule.current > rule.threshold;return (<article key={rule.key} className={`metric-rule-editor ${isTriggered ? 'is-alerting' : ''}`}><div className="metric-rule-editor__main">- <span className="mon-ico">- <Icon size={15} />- </span>+ <span className="mon-ico"><Icon size={15} /></span><div><h4>{rule.label}</h4>- <span>current {formatMetric(rule.current, rule.unit)}</span>+ <span>+ current {formatNumber(rule.current, rule.unit === '' ? 2 : 1)}{rule.unit}+ </span></div></div><div className="metric-rule-editor__threshold">@@ -583,7 +427,7 @@ const Monitoring = () => {id={`threshold-${rule.key}`}type="number"min={rule.key === 'load_average' ? '0.1' : '1'}- max={rule.key === 'load_average' ? '100' : '100'}+ max="100"step={rule.key === 'load_average' ? '0.1' : '1'}value={rule.threshold}onChange={(e) => updateThreshold(rule.key, e.target.value)}@@ -597,15 +441,20 @@ const Monitoring = () => {})}</div></form>- </TabsContent>- <TabsContent value="config">+ {servers.length > 0 && (+ <FleetThresholdsPanel servers={servers} refreshKey={refreshKey} />+ )}+<div className="monitoring-delivery-layout"><form className="monitoring-panel" onSubmit={handleSaveConfig}><div className="monitoring-panel__header">- <h3>Scheduler</h3>- <Button type="submit" disabled={savingConfig}>- {savingConfig ? 'Saving...' : 'Save Delivery'}+ <div>+ <h3>Scheduler</h3>+ <span className="mon-panel-sub">How often the checks run</span>+ </div>+ <Button type="submit" size="sm" disabled={savingConfig}>+ {savingConfig ? 'Saving…' : 'Save'}</Button></div><div className="monitoring-switch-row">@@ -634,81 +483,56 @@ const Monitoring = () => {<section className="monitoring-panel"><div className="monitoring-panel__header">- <h3>Notification Channels</h3>+ <div>+ <h3>Delivery</h3>+ <span className="mon-panel-sub">Where an alert goes when it fires</span>+ </div><Button size="sm" asChild><Link to="/settings/notifications">- <Settings size={14} />- Configure+ <Settings size={14} /> Configure</Link></Button></div><div className="notification-channel-grid">{notificationChannels.map((channel) => {- const Icon = channel.icon;const ready = channel.enabled && channel.configured;return (- <article key={channel.key} className={`notification-channel-tile ${ready ? 'is-ready' : ''}`}>+ <article+ key={channel.key}+ className={`notification-channel-tile${ready ? ' is-ready' : ''}${channel.configured ? '' : ' is-unset'}`}+ ><span className="mon-ico">- <Icon size={15} />+ {channel.brand+ ? <ProviderBrandIcon provider={channel.brand} size={16} />+ : <Bell size={15} />}</span><div><strong>{channel.label}</strong>- <span>{ready ? 'Enabled' : channel.configured ? 'Configured' : 'Not configured'}</span>+ <span>+ {ready+ ? 'Sending alerts'+ : channel.configured+ ? 'Configured but off'+ : 'Not configured'}+ </span></div>- <Pill kind={ready ? 'green' : 'gray'}>{ready ? 'ready' : 'off'}</Pill>+ <Pill kind={ready ? 'green' : channel.configured ? 'amber' : 'gray'}>+ {ready ? 'on' : 'off'}+ </Pill></article>);})}</div></section></div>- </TabsContent>+ </div>+ )}- <TabsContent value="alerts">- <section className="monitoring-panel">- <div className="monitoring-panel__header">- <h3>Alert History</h3>- <div>- <Button variant="outline" size="sm" onClick={handleCheckAlerts} disabled={checkingAlerts}>- <Siren size={14} />- Check Now- </Button>- <Button variant="outline" size="sm" onClick={loadData}>- <RefreshCw size={14} />- Refresh- </Button>- </div>- </div>- {alertHistory.length === 0 ? (- <EmptyState- icon={Bell}- title="No alerts yet"- description="Alerts will appear here once a threshold is crossed."- />- ) : (- <div className="mon-alert-list">- {alertHistory.map((alert, index) => (- <article key={`${alert.timestamp}-${index}`} className="mon-alert-row">- <span className={`mon-sev mon-sev--${alert.severity}`} />- <div className="mon-alert-row__body">- <div className="mon-alert-row__title">{alert.message}</div>- <div className="mon-alert-row__sub">{alert.type} · {formatNumber(alert.value)} / {alert.threshold}</div>- </div>- <div className="mon-alert-row__end">- <span className={`mon-state mon-state--${getSeverityTone(alert.severity)}`}>{alert.severity}</span>- <span className="mon-alert-row__time">{formatTimestamp(alert.timestamp)}</span>- </div>- </article>- ))}- </div>- )}- </section>- </TabsContent>+ {activeTab === 'capacity' && (+ <FleetCapacityPanel scope={scope} refreshKey={refreshKey} />+ )}- <TabsContent value="doctor">- <DoctorPanel />- </TabsContent>- </Tabs>+ {activeTab === 'doctor' && <DoctorPanel />}</div>);};diff --git a/frontend/src/styles/components/_design-system.scss b/frontend/src/styles/components/_design-system.scssindex 55130f90..76113ccd 100644--- a/frontend/src/styles/components/_design-system.scss+++ b/frontend/src/styles/components/_design-system.scss@@ -184,6 +184,20 @@ $sk-tones: ('accent', 'green', 'cyan', 'amber', 'red', 'violet');&--down { color: var(--red); }&--flat { color: var(--text-faint); }}+ // Trend chart along the bottom edge. The negative margins cancel the tile's+ // padding so the series bleeds to the corners instead of floating in a box+ // — the design mock's `.kpi-spark`.+ &__spark {+ margin: 10px -17px -16px;+ line-height: 0;+ opacity: 0.9;++ svg { display: block; width: 100%; }+ }++ // A tile whose metric is over its configured limit. Amber, not red: it is+ // an "act soon", and the value itself already carries the number.+ &.is-alerting { border-color: rgba(245, 185, 69, 0.35); }}// ------------------------------------------------------------diff --git a/frontend/src/styles/pages/_fleet-monitor.scss b/frontend/src/styles/pages/_fleet-monitor.scssindex 88f85300..fc26cbfc 100644--- a/frontend/src/styles/pages/_fleet-monitor.scss+++ b/frontend/src/styles/pages/_fleet-monitor.scss@@ -1,6 +1,10 @@// ============================================-// FLEET PAGES (Agent Fleet + Fleet Monitor)+// FLEET PAGES (Agent Fleet + the fleet panels on /monitoring)// ============================================+//+// The statbox / predbox / warnrow rules below outlived the standalone Fleet+// Monitor page: the Capacity section on /monitoring still renders them under+// the same class names.// KPI band (Total agents / Online / Offline / Success rate). The rule was lost// in the recovery rebuild, so the tiles stacked full-width.@@ -77,100 +81,9 @@box-shadow: var(--shadow-lg);}-.fleet-heatmap {- width: 100%;-- &__header {- display: grid;- grid-template-columns: 2fr 1fr 1fr 1fr 1fr 1fr;- gap: $space-2;- padding: $space-2 $space-3;- font-size: 0.75rem;- font-weight: 600;- text-transform: uppercase;- color: $text-secondary;- border-bottom: 1px solid $border-subtle;- }-- &__row {- display: grid;- grid-template-columns: 2fr 1fr 1fr 1fr 1fr 1fr;- gap: $space-2;- padding: $space-2 $space-3;- align-items: center;- border-bottom: 1px solid $border-subtle;- transition: background 0.15s;-- &:hover {- background: $bg-hover;- }-- &:last-child {- border-bottom: none;- }- }-- &__server {- display: flex;- align-items: center;- gap: $space-2;- font-weight: 500;- font-size: 0.875rem;- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- }-- &__cell {- text-align: center;- padding: $space-1 $space-2;- border-radius: $radius-sm;- font-size: 0.8125rem;- font-weight: 500;- font-variant-numeric: tabular-nums;- transition: background-color 0.3s;- background: var(--bg-card);-- &.is-empty { background: var(--bg-card); color: inherit; }- &.is-low { background: var(--green); color: inherit; }- &.is-medium { background: var(--amber); color: inherit; }- &.is-high { background: #f97316; color: #fff; }- &.is-critical { background: var(--red); color: #fff; }- }-- &__label {- text-align: center;- }-- &__legend-dot {- display: inline-block;- width: 12px;- height: 12px;- border-radius: $radius-sm;-- &.is-low { background: var(--green); }- &.is-medium { background: var(--amber); }- &.is-high { background: #f97316; }- &.is-critical { background: var(--red); }- }-}--@media (max-width: $breakpoint-md) {- .fleet-heatmap {- &__header,- &__row {- grid-template-columns: 1.5fr 1fr 1fr 1fr;- }-- // Hide containers and status columns on small screens- &__header > :nth-child(5),- &__header > :nth-child(6),- &__row > :nth-child(5),- &__row > :nth-child(6) {- display: none;- }- }-}+// The heatmap grid that used to live here is gone: colour-coded cells were a+// read-only view of the same numbers the Host health cards on /monitoring now+// show, and those cards are clickable — they re-scope the page to that server.// Fleet doctor rollup card (plan 26) — checks-by-status per server on the// Agent Fleet dashboard, consuming the same rows as the Doctor panel.diff --git a/frontend/src/styles/pages/_monitoring.scss b/frontend/src/styles/pages/_monitoring.scssindex dda23f0a..2390c1b3 100644--- a/frontend/src/styles/pages/_monitoring.scss+++ b/frontend/src/styles/pages/_monitoring.scss@@ -35,60 +35,91 @@}}- .monitoring-overview,+ // Every section stacks the same way, so a tab change never shifts the+ // rhythm of the page.+ .mon-overview,+ .monitoring-stack,.monitoring-delivery-layout {display: grid;gap: $space-5;}- // ── hero strip ──────────────────────────────────────────- .monitoring-hero {- display: flex;- justify-content: space-between;- align-items: flex-start;+ // Two equal panels side by side (charts row, alerts + speed test row) —+ // the mock's `dash-grid` with two `span-2` cards.+ .mon-grid2 {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));gap: $space-5;- padding: $space-5 $space-6;- border: 1px solid var(--border-soft);- border-radius: var(--radius);- background: var(--surface);- &.is-active {- border-color: rgba(61, 220, 151, 0.25);- }+ @media (max-width: 1000px) { grid-template-columns: 1fr; }+ }- h2 {- margin: $space-3 0 $space-1;- font-size: 19px;- font-weight: $font-weight-semibold;- letter-spacing: -0.01em;- line-height: 1.15;- }+ // ── section heads + panels ──────────────────────────────+ .mon-section-head {+ display: flex;+ justify-content: space-between;+ align-items: center;+ gap: $space-3;+ margin-bottom: -$space-2; // the grid gap already spaces it off the grid- p {- margin: 0;+ &__meta {font-family: var(--mono);- font-size: 11.5px;+ font-size: 11px;color: var(--text-faint);}+ }- &__actions {- flex: 0 0 auto;- display: flex;- gap: $space-2;- }+ // Caption under a panel heading — says what the panel is showing and,+ // crucially, WHICH host it is showing it for. One line: a wrapped caption+ // pushes the chart down and makes the two panels in a row disagree on where+ // their plots start.+ .mon-panel-sub {+ display: block;+ max-width: 100%;+ font-family: var(--mono);+ font-size: 11px;+ color: var(--text-faint);+ @include truncate();+ }- @media (max-width: 760px) {+ .monitoring-panel__header > div {+ // A heading with a caption stacks and takes the free space; the default+ // row layout is for headers whose second child is a button cluster.+ &:has(> h3) {+ flex: 1 1 auto;+ min-width: 0;flex-direction: column;+ align-items: flex-start;+ gap: 3px;}}- // ── section heads + panels ──────────────────────────────- .mon-section-head {+ // Controls on the right of a panel header never wrap or shrink — letting+ // them do either steals width from the caption and folds a 4-button switch+ // onto two lines.+ .mon-period-switch,+ .mon-legend {+ flex: none;+ flex-wrap: nowrap;+ }++ .mon-legend {display: flex;- justify-content: space-between;- align-items: center;gap: $space-3;- margin-bottom: $space-3;+ font-family: var(--mono);+ font-size: 11px;+ color: var(--text-faint);++ span { display: inline-flex; align-items: center; gap: 5px; }++ i {+ width: 8px;+ height: 8px;+ border-radius: 2px;++ &.is-memory { background: var(--cyan); }+ &.is-disk { background: var(--green); }+ }}.monitoring-panel {@@ -122,59 +153,56 @@}}- .mon-firing-count {- font-family: var(--mono);- font-size: 11px;- color: var(--red);- }-- // ── overview summary band — 4 KPI tiles in a responsive row ───- // (mirrors the shared KpiBand geometry; the class carried no rule after the- // recovery rebuild, so the tiles stacked full-width.)- .mon-kpis {- display: grid;- grid-template-columns: repeat(4, minmax(0, 1fr));- gap: 14px;- margin-bottom: $space-5;-- @media (max-width: 1100px) {- grid-template-columns: repeat(auto-fit, minmax(190px, 1fr));- }- @media (max-width: 560px) {- grid-template-columns: 1fr 1fr;- }- }+ // The KPI band is the shared DS tile (MetricCard + KpiBand) — the+ // monitoring-only copy that lived here was the same geometry twice, so the+ // sparkline slot moved into the primitive instead.- // ── current-metrics host cards (prototype .host-card) ───- .mon-host-grid {+ // ── Host health strip: one card per machine, the panel host first ──+ // This is the ex-Fleet-Monitor heatmap, except each card is a button that+ // re-scopes the whole page rather than a cell you can only read.+ .mon-fleet-grid {display: grid;- grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));+ grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));gap: 14px;}- .mon-host-card {+ .mon-host {+ display: block;+ width: 100%;min-width: 0;- padding: 15px 16px;+ padding: 14px 16px 12px;border: 1px solid var(--border-soft);border-radius: var(--radius);background: var(--surface);- transition: border-color $transition-fast;+ text-align: left;+ cursor: pointer;+ transition: border-color $transition-fast, background $transition-fast;- &:hover {- border-color: var(--border-strong);- }+ &:hover { border-color: var(--border-strong); }- &.is-alerting {- border-color: rgba(245, 185, 69, 0.35);+ &.is-active {+ border-color: var(--accent-dim);+ background: var(--accent-bg);}&__head {display: flex;align-items: center;gap: 9px;- margin-bottom: 12px;+ margin-bottom: 10px;++ .sk-pill { margin-left: auto; flex-shrink: 0; }+ }- .sk-pill { margin-left: auto; }+ &__ico {+ width: 28px;+ height: 28px;+ border-radius: 8px;+ display: grid;+ place-items: center;+ flex-shrink: 0;+ background: var(--surface-3);+ color: var(--text-dim);}&__name {@@ -182,19 +210,32 @@min-width: 0;font-size: 13px;font-weight: $font-weight-semibold;+ color: var(--text);@include truncate();++ small {+ display: block;+ font-family: var(--mono);+ font-size: 10px;+ font-weight: 400;+ color: var(--text-faint);+ @include truncate();+ }}- &__value {- margin-bottom: 10px;- font-family: var(--mono);- font-size: 23px;- font-weight: $font-weight-semibold;- letter-spacing: -0.02em;- line-height: 1;+ &__spark {+ display: block;+ height: 38px;++ svg { width: 100%; height: 100%; }++ &--empty {+ border-bottom: 1px dashed var(--border-soft);+ height: 37px;+ }}- // mono footer stats (prototype .host-mini)+ // mono footer stats (mock `.host-mini`)&__mini {display: flex;justify-content: space-between;@@ -205,11 +246,7 @@color: var(--text-faint);span { white-space: nowrap; }-- b {- color: var(--text-dim);- font-weight: 600;- }+ b { color: var(--text-dim); font-weight: 600; }}}@@ -429,6 +466,10 @@}}+ // A channel with no credentials yet is a to-do, not a failure: dim the+ // brand mark rather than colouring it like a live one.+ &.is-unset .mon-ico { opacity: 0.5; }+> div { min-width: 0; }strong {@@ -444,6 +485,9 @@font-family: var(--mono);font-size: 10.5px;color: var(--text-faint);+ // "Configured but off" is longer than the tile is wide at three+ // across; clip it rather than let it fold and grow the row.+ @include truncate();}}@@ -455,14 +499,58 @@color: var(--text-faint);}- // Speed test card (overview tab)- .mon-speedtest__grid {+ // Speed test — three readings in a row, sized to sit beside the alerts+ // panel rather than take a band of its own.+ .mon-speed-row {display: grid;- grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));+ grid-template-columns: repeat(3, minmax(0, 1fr));gap: $space-3;}- .mon-speedtest__meta {+ .mon-speed {+ min-width: 0;+ padding: 12px 14px;+ border: 1px solid var(--border-soft);+ border-radius: var(--radius);+ background: var(--surface-2);++ // Only the glyph is tinted here — the tile keeps the quiet surface, so+ // three of them side by side don't read as three status badges.+ &__ico {+ display: block;+ margin-bottom: 6px;+ background: none;++ &.is-cpu { color: var(--accent-bright); }+ &.is-memory { color: var(--cyan); }+ &.is-extra { color: var(--violet); }+ }++ &__val {+ display: block;+ font-family: var(--mono);+ font-size: 19px;+ font-weight: $font-weight-semibold;+ letter-spacing: -0.02em;+ line-height: 1;+ color: var(--text);++ small {+ margin-left: 3px;+ font-size: 11px;+ color: var(--text-faint);+ }+ }++ &__label {+ display: block;+ margin-top: 5px;+ font-size: 11.5px;+ color: var(--text-dim);+ }+ }++ .mon-speed-meta {display: flex;flex-wrap: wrap;align-items: center;@@ -476,17 +564,177 @@}}- .mon-speedtest__error {- color: var(--red);- @include truncate();- max-width: 100%;+ // ── fleet-scoped panels (Host health, Capacity, Fleet alerts) ──+ // Folded in from the old standalone Fleet Monitor page; they reuse the+ // panel chrome above so the sections read as one page rather than two+ // stapled together.++ // Small mono caption used for every field label in the fleet panels.+ .mon-field-label {+ display: block;+ margin-bottom: 4px;+ font-family: var(--mono);+ font-size: 10.5px;+ font-weight: $font-weight-semibold;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: var(--text-faint);}- .mon-speedtest__empty {- span {+ .mon-field-hint,+ .mon-panel-hint {+ display: flex;+ align-items: center;+ gap: $space-2;+ margin: 0;+ font-size: $font-size-sm;+ color: var(--text-faint);+ }++ .mon-panel-hint svg { flex-shrink: 0; color: var(--green); }++ // Wide tables keep their own scroller so the panel never widens the page.+ .mon-table-scroll { overflow-x: auto; }++ .mon-row-actions {+ display: flex;+ justify-content: flex-end;+ gap: $space-1;+ white-space: nowrap;+ }++ // Add-a-rule form on the Rules tab: fields in a row, save at the end.+ .mon-threshold-form {+ display: flex;+ flex-wrap: wrap;+ align-items: flex-end;+ gap: $space-3;+ margin-bottom: $space-4;+ padding: $space-4;+ border: 1px solid var(--border-soft);+ border-radius: var(--radius);+ background: var(--surface-2);++ .form-group { margin: 0; min-width: 150px; flex: 1 1 150px; }+ }++ // Comparison / forecast control rows: a servers picker that grows, plus+ // fixed-width selects.+ .mon-compare-controls {+ display: flex;+ flex-wrap: wrap;+ align-items: flex-start;+ gap: $space-4;+ margin-bottom: $space-4;++ .form-group { margin: 0; min-width: 160px; }++ &__servers { flex: 1 1 320px; min-width: 0; }+ }++ .mon-server-picker {+ display: flex;+ flex-wrap: wrap;+ gap: $space-2;+ max-height: 96px;+ overflow-y: auto;+ padding: $space-2;+ border: 1px solid var(--border-soft);+ border-radius: var(--radius);+ background: var(--surface-2);+ }++ .mon-period-switch { display: flex; gap: 4px; align-items: center; }++ .mon-forecast {+ display: flex;+ flex-direction: column;+ gap: $space-4;+ }++ .mon-forecast__stats,+ .mon-forecast__predictions {+ display: grid;+ gap: $space-3;+ }++ .mon-forecast__stats { grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); }+ .mon-forecast__predictions { grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); }++ .mon-forecast strong {+ display: block;+ font-size: $font-size-lg;+ color: var(--text);++ em { font-style: normal; font-size: $font-size-sm; color: var(--text-faint); }+ }++}++// ── server scope picker ──────────────────────────────────────+// Lives in the group top bar and its menu portals to <body>, so neither can be+// nested under .monitoring-page. Names which host every section below is+// describing — the reason Fleet Monitor no longer needs a page of its own.+.mon-scope {+ display: inline-flex;+ align-items: center;+ gap: 7px;+ height: 32px;+ padding: 0 10px;+ max-width: 210px;+ border: 1px solid var(--border);+ border-radius: 8px;+ background: var(--surface-2);+ color: var(--text-dim);+ font-size: 12.5px;+ cursor: pointer;+ transition: border-color 0.14s, color 0.14s;++ &:hover { border-color: var(--border-strong); color: var(--text); }++ &__ico { display: inline-flex; color: var(--accent-bright); flex-shrink: 0; }+ &__label { @include truncate(); }+ &__chev { flex-shrink: 0; opacity: 0.6; }++ &__menu { width: 260px; padding: 5px; }++ &__sep {+ height: 1px;+ margin: 5px 2px;+ background: var(--border-soft);+ }++ &__item {+ display: flex;+ align-items: center;+ gap: 9px;+ width: 100%;+ padding: 7px 9px;+ border: 0;+ border-radius: 7px;+ background: none;+ color: var(--text-dim);+ text-align: left;+ cursor: pointer;++ &:hover { background: var(--surface-3); color: var(--text); }+ &.is-on { color: var(--accent-bright); }++ > span {+ flex: 1;+ min-width: 0;+ font-size: 12.5px;+ @include truncate();+ }++ small {+ display: block;font-family: var(--mono);- font-size: 12px;+ font-size: 10px;color: var(--text-faint);+ @include truncate();}++ svg { flex-shrink: 0; }}}