Skip to content

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.

feat(monitoring): on-demand server speed test card

Juan Denise7e2de486fe5
diff --git a/backend/app/api/speed_test.py b/backend/app/api/speed_test.py
new file mode 100644
index 00000000..666aea26
--- /dev/null
+++ b/backend/app/api/speed_test.py
@@ -0,0 +1,35 @@
+"""REST surface for the on-demand server speed test.
+
+Mounted at /api/v1/speedtest (registered in app/__init__.py).
+"""
+from flask import Blueprint, jsonify
+
+from ..middleware.rbac import admin_required, viewer_required
+from ..services.speed_test_service import SPEEDTEST_JOB_KIND, SpeedTestService
+
+speedtest_bp = Blueprint('speedtest', __name__)
+
+
+@speedtest_bp.route('', methods=['GET'])
+@speedtest_bp.route('/', methods=['GET'])
+@viewer_required
+def get_speed_test():
+ """Last stored result + status of any in-flight speed test job."""
+ try:
+ return jsonify(SpeedTestService.get_status())
+ except Exception as exc: # noqa: BLE001 — surface as a clean JSON error
+ return jsonify({'error': str(exc)}), 500
+
+
+@speedtest_bp.route('/run', methods=['POST'])
+@admin_required
+def run_speed_test():
+ """Enqueue a one-off speed test job. Rejects if one is already in flight."""
+ try:
+ if SpeedTestService.is_running():
+ return jsonify({'error': 'A speed test is already in progress.'}), 409
+ from app.jobs.service import JobService
+ job = JobService.enqueue(SPEEDTEST_JOB_KIND, payload={}, max_attempts=1)
+ return jsonify({'job_id': job.id}), 202
+ except Exception as exc: # noqa: BLE001
+ return jsonify({'error': str(exc)}), 500
diff --git a/backend/app/services/speed_test_service.py b/backend/app/services/speed_test_service.py
new file mode 100644
index 00000000..527cf2eb
--- /dev/null
+++ b/backend/app/services/speed_test_service.py
@@ -0,0 +1,255 @@
+"""On-demand server speed test (download / upload / latency).
+
+Best-effort, tiered measurement:
+ 1. If an Ookla ``speedtest`` or python ``speedtest-cli`` binary is available,
+ shell out to it and parse its JSON output.
+ 2. Otherwise a pure-Python fallback: latency via timed TCP connects to a
+ well-known anycast host, download via a timed GET of ~10 MB from a public
+ speed endpoint, upload via a timed POST of ~2 MB of random bytes
+ (upload is best-effort — if it fails the result still carries
+ download + latency with ``upload_mbps=None``).
+
+Runs asynchronously as a unified Job (kind ``monitoring.speedtest.run``); the
+handler persists the last result under the ``speedtest_last_result`` setting so
+the Monitoring page can show it without re-running the test.
+"""
+import json
+import logging
+import os
+import socket
+import subprocess
+import time
+from datetime import datetime
+
+import requests
+
+from app.utils.system import is_command_available
+
+logger = logging.getLogger(__name__)
+
+SPEEDTEST_JOB_KIND = 'monitoring.speedtest.run'
+LAST_RESULT_KEY = 'speedtest_last_result'
+
+# Fallback-tier tunables.
+LATENCY_HOST = '1.1.1.1'
+LATENCY_PORT = 443
+LATENCY_SAMPLES = 3
+LATENCY_TIMEOUT = 5 # seconds per connect
+DOWNLOAD_URL = 'https://speed.cloudflare.com/__down?bytes=10000000'
+DOWNLOAD_BYTES = 10_000_000
+UPLOAD_URL = 'https://speed.cloudflare.com/__up'
+UPLOAD_BYTES = 2_000_000
+HTTP_TIMEOUT = (10, 60) # (connect, read) seconds
+CLI_TIMEOUT = 120 # seconds for the speedtest binary
+
+
+class SpeedTestService:
+
+ # ------------------------------------------------------------------ #
+ # Public entry points
+ # ------------------------------------------------------------------ #
+
+ @classmethod
+ def run_test(cls):
+ """Run a speed test and return a normalized result dict.
+
+ Never raises — any failure returns ``{'success': False, 'error': ...}``.
+ """
+ try:
+ cli_result = cls._run_cli_test()
+ if cli_result is not None:
+ return cli_result
+ return cls._run_fallback_test()
+ except Exception as exc: # noqa: BLE001 — hard guarantee, see docstring
+ logger.exception('Speed test failed unexpectedly')
+ return {
+ 'success': False,
+ 'error': str(exc),
+ 'tested_at': datetime.utcnow().isoformat() + 'Z',
+ }
+
+ @classmethod
+ def get_status(cls):
+ """Last stored result + whether a speed test job is currently in flight."""
+ from app.jobs.models import Job
+
+ last_result = None
+ try:
+ from app.services.settings_service import SettingsService
+ raw = SettingsService.get(LAST_RESULT_KEY)
+ if raw:
+ last_result = json.loads(raw) if isinstance(raw, str) else raw
+ except Exception: # pragma: no cover — corrupt setting should not 500
+ logger.warning('Could not parse stored speed test result', exc_info=True)
+
+ active = Job.query.filter(
+ Job.kind == SPEEDTEST_JOB_KIND,
+ Job.status.in_((Job.STATUS_PENDING, Job.STATUS_RUNNING)),
+ ).order_by(Job.created_at.desc()).first()
+
+ return {
+ 'last_result': last_result,
+ 'running': active is not None,
+ 'job': active.to_dict() if active else None,
+ }
+
+ @classmethod
+ def is_running(cls):
+ from app.jobs.models import Job
+ return Job.query.filter(
+ Job.kind == SPEEDTEST_JOB_KIND,
+ Job.status.in_((Job.STATUS_PENDING, Job.STATUS_RUNNING)),
+ ).first() is not None
+
+ # ------------------------------------------------------------------ #
+ # Tier 1 — speedtest CLI
+ # ------------------------------------------------------------------ #
+
+ @classmethod
+ def _run_cli_test(cls):
+ """Run the system speedtest binary if present; None if unavailable."""
+ if is_command_available('speedtest'):
+ cmd = ['speedtest', '--format=json', '--accept-license', '--accept-gdpr']
+ flavor = 'ookla'
+ elif is_command_available('speedtest-cli'):
+ cmd = ['speedtest-cli', '--json']
+ flavor = 'python'
+ else:
+ return None
+
+ try:
+ proc = subprocess.run(
+ cmd, capture_output=True, text=True, timeout=CLI_TIMEOUT
+ )
+ if proc.returncode != 0:
+ logger.warning('speedtest CLI exited %s: %s',
+ proc.returncode, (proc.stderr or '')[:500])
+ return None # fall through to the pure-Python tier
+ data = json.loads(proc.stdout)
+ except (subprocess.SubprocessError, OSError, json.JSONDecodeError) as exc:
+ logger.warning('speedtest CLI failed (%s); using fallback', exc)
+ return None
+
+ if flavor == 'ookla':
+ # Ookla reports bandwidth in bytes/second.
+ download = (data.get('download') or {}).get('bandwidth')
+ upload = (data.get('upload') or {}).get('bandwidth')
+ latency = (data.get('ping') or {}).get('latency')
+ download_mbps = round(download * 8 / 1e6, 2) if download else None
+ upload_mbps = round(upload * 8 / 1e6, 2) if upload else None
+ else:
+ # speedtest-cli reports bits/second.
+ download = data.get('download')
+ upload = data.get('upload')
+ latency = data.get('ping')
+ download_mbps = round(download / 1e6, 2) if download else None
+ upload_mbps = round(upload / 1e6, 2) if upload else None
+
+ if download_mbps is None and latency is None:
+ return None # useless output — try the fallback tier
+
+ return {
+ 'success': True,
+ 'method': 'cli',
+ 'download_mbps': download_mbps,
+ 'upload_mbps': upload_mbps,
+ 'latency_ms': round(latency, 2) if latency is not None else None,
+ 'tested_at': datetime.utcnow().isoformat() + 'Z',
+ }
+
+ # ------------------------------------------------------------------ #
+ # Tier 2 — pure-Python fallback
+ # ------------------------------------------------------------------ #
+
+ @classmethod
+ def _measure_latency(cls):
+ """Median-ish latency: best of N timed TCP connects, in ms."""
+ samples = []
+ for _ in range(LATENCY_SAMPLES):
+ try:
+ start = time.perf_counter()
+ sock = socket.create_connection(
+ (LATENCY_HOST, LATENCY_PORT), timeout=LATENCY_TIMEOUT
+ )
+ samples.append((time.perf_counter() - start) * 1000.0)
+ sock.close()
+ except OSError:
+ continue
+ if not samples:
+ return None
+ return round(min(samples), 2)
+
+ @classmethod
+ def _measure_download(cls):
+ """Timed GET of ~10 MB; returns Mbps or None."""
+ try:
+ start = time.perf_counter()
+ resp = requests.get(DOWNLOAD_URL, timeout=HTTP_TIMEOUT, stream=True)
+ resp.raise_for_status()
+ total = 0
+ for chunk in resp.iter_content(chunk_size=65536):
+ total += len(chunk)
+ elapsed = time.perf_counter() - start
+ if total <= 0 or elapsed <= 0:
+ return None
+ return round(total * 8 / elapsed / 1e6, 2)
+ except requests.RequestException:
+ logger.warning('Fallback download measurement failed', exc_info=True)
+ return None
+
+ @classmethod
+ def _measure_upload(cls):
+ """Timed POST of ~2 MB random bytes; best-effort, returns Mbps or None."""
+ try:
+ payload = os.urandom(UPLOAD_BYTES)
+ start = time.perf_counter()
+ resp = requests.post(UPLOAD_URL, data=payload, timeout=HTTP_TIMEOUT)
+ resp.raise_for_status()
+ elapsed = time.perf_counter() - start
+ if elapsed <= 0:
+ return None
+ return round(len(payload) * 8 / elapsed / 1e6, 2)
+ except requests.RequestException:
+ logger.info('Fallback upload measurement failed (best-effort)')
+ return None
+
+ @classmethod
+ def _run_fallback_test(cls):
+ latency_ms = cls._measure_latency()
+ download_mbps = cls._measure_download()
+ upload_mbps = cls._measure_upload()
+
+ if download_mbps is None and latency_ms is None:
+ return {
+ 'success': False,
+ 'error': 'Speed test failed: could not reach any measurement endpoint.',
+ 'tested_at': datetime.utcnow().isoformat() + 'Z',
+ }
+
+ return {
+ 'success': True,
+ 'method': 'fallback',
+ 'download_mbps': download_mbps,
+ 'upload_mbps': upload_mbps,
+ 'latency_ms': latency_ms,
+ 'tested_at': datetime.utcnow().isoformat() + 'Z',
+ }
+
+ # ------------------------------------------------------------------ #
+ # Job plumbing
+ # ------------------------------------------------------------------ #
+
+ @classmethod
+ def run_speed_test_job(cls, job):
+ """Job handler for ``monitoring.speedtest.run``."""
+ result = cls.run_test()
+ from app.services.settings_service import SettingsService
+ SettingsService.set(LAST_RESULT_KEY, json.dumps(result))
+ return result
+
+ @classmethod
+ def register_jobs(cls):
+ """Register the speed test handler with the job registry.
+ Called once at app startup (see app/__init__.py)."""
+ from app.jobs import registry
+ registry.register(SPEEDTEST_JOB_KIND, cls.run_speed_test_job, replace=True)
diff --git a/backend/tests/test_speed_test.py b/backend/tests/test_speed_test.py
new file mode 100644
index 00000000..00e34d11
--- /dev/null
+++ b/backend/tests/test_speed_test.py
@@ -0,0 +1,297 @@
+"""Tests for the on-demand server speed test (service tiers + API).
+
+All network access is stubbed — the suite stays offline.
+"""
+import json
+
+import pytest
+
+from app.services import speed_test_service as sts_module
+from app.services.speed_test_service import (
+ LAST_RESULT_KEY,
+ SPEEDTEST_JOB_KIND,
+ SpeedTestService,
+)
+
+
+class _FakeProc:
+ def __init__(self, returncode=0, stdout='', stderr=''):
+ self.returncode = returncode
+ self.stdout = stdout
+ self.stderr = stderr
+
+
+class _FakeResponse:
+ def __init__(self, body=b'', status=200):
+ self._body = body
+ self.status_code = status
+
+ def raise_for_status(self):
+ if self.status_code >= 400:
+ raise sts_module.requests.HTTPError(f'HTTP {self.status_code}')
+
+ def iter_content(self, chunk_size=65536):
+ for i in range(0, len(self._body), chunk_size):
+ yield self._body[i:i + chunk_size]
+
+
+class _FakeSocket:
+ def close(self):
+ pass
+
+
+def no_cli(monkeypatch):
+ """Pretend no speedtest binary exists — forces the pure-Python tier."""
+ monkeypatch.setattr(sts_module, 'is_command_available', lambda cmd: False)
+
+
+# ── fallback tier ────────────────────────────────────────────────────────────
+
+def test_fallback_full_success(no_cli, monkeypatch):
+ monkeypatch.setattr(
+ sts_module.socket, 'create_connection',
+ lambda addr, timeout=None: _FakeSocket(),
+ )
+ monkeypatch.setattr(
+ sts_module.requests, 'get',
+ lambda url, timeout=None, stream=False: _FakeResponse(b'x' * 1_000_000),
+ )
+ monkeypatch.setattr(
+ sts_module.requests, 'post',
+ lambda url, data=None, timeout=None: _FakeResponse(),
+ )
+
+ result = SpeedTestService.run_test()
+
+ assert result['success'] is True
+ assert result['method'] == 'fallback'
+ assert result['download_mbps'] > 0
+ assert result['upload_mbps'] > 0
+ assert result['latency_ms'] is not None and result['latency_ms'] >= 0
+ assert result['tested_at']
+
+
+def test_fallback_upload_failure_is_best_effort(no_cli, monkeypatch):
+ monkeypatch.setattr(
+ sts_module.socket, 'create_connection',
+ lambda addr, timeout=None: _FakeSocket(),
+ )
+ monkeypatch.setattr(
+ sts_module.requests, 'get',
+ lambda url, timeout=None, stream=False: _FakeResponse(b'x' * 500_000),
+ )
+
+ def _post_fails(url, data=None, timeout=None):
+ raise sts_module.requests.ConnectionError('upload endpoint unreachable')
+
+ monkeypatch.setattr(sts_module.requests, 'post', _post_fails)
+
+ result = SpeedTestService.run_test()
+
+ assert result['success'] is True
+ assert result['download_mbps'] > 0
+ assert result['upload_mbps'] is None # best-effort
+
+
+def test_fallback_total_failure_returns_error(no_cli, monkeypatch):
+ def _connect_fails(addr, timeout=None):
+ raise OSError('network down')
+
+ def _get_fails(url, timeout=None, stream=False):
+ raise sts_module.requests.ConnectionError('no route')
+
+ def _post_fails(url, data=None, timeout=None):
+ raise sts_module.requests.ConnectionError('no route')
+
+ monkeypatch.setattr(sts_module.socket, 'create_connection', _connect_fails)
+ monkeypatch.setattr(sts_module.requests, 'get', _get_fails)
+ monkeypatch.setattr(sts_module.requests, 'post', _post_fails)
+
+ result = SpeedTestService.run_test()
+
+ assert result['success'] is False
+ assert 'error' in result
+
+
+# ── CLI tier ─────────────────────────────────────────────────────────────────
+
+def test_cli_ookla_json_parsed(monkeypatch):
+ monkeypatch.setattr(
+ sts_module, 'is_command_available', lambda cmd: cmd == 'speedtest'
+ )
+ ookla = json.dumps({
+ 'download': {'bandwidth': 12_500_000}, # bytes/s -> 100 Mbps
+ 'upload': {'bandwidth': 2_500_000}, # bytes/s -> 20 Mbps
+ 'ping': {'latency': 8.42},
+ })
+ monkeypatch.setattr(
+ sts_module.subprocess, 'run',
+ lambda cmd, capture_output=True, text=True, timeout=None: _FakeProc(0, ookla),
+ )
+
+ result = SpeedTestService.run_test()
+
+ assert result['success'] is True
+ assert result['method'] == 'cli'
+ assert result['download_mbps'] == 100.0
+ assert result['upload_mbps'] == 20.0
+ assert result['latency_ms'] == 8.42
+
+
+def test_cli_python_speedtest_cli_json_parsed(monkeypatch):
+ monkeypatch.setattr(
+ sts_module, 'is_command_available', lambda cmd: cmd == 'speedtest-cli'
+ )
+ legacy = json.dumps({
+ 'download': 50_000_000.0, # bits/s -> 50 Mbps
+ 'upload': 10_000_000.0, # bits/s -> 10 Mbps
+ 'ping': 22.5,
+ })
+ monkeypatch.setattr(
+ sts_module.subprocess, 'run',
+ lambda cmd, capture_output=True, text=True, timeout=None: _FakeProc(0, legacy),
+ )
+
+ result = SpeedTestService.run_test()
+
+ assert result['success'] is True
+ assert result['method'] == 'cli'
+ assert result['download_mbps'] == 50.0
+ assert result['upload_mbps'] == 10.0
+ assert result['latency_ms'] == 22.5
+
+
+def test_cli_failure_falls_back_to_python_tier(monkeypatch):
+ monkeypatch.setattr(
+ sts_module, 'is_command_available', lambda cmd: cmd == 'speedtest'
+ )
+ monkeypatch.setattr(
+ sts_module.subprocess, 'run',
+ lambda cmd, capture_output=True, text=True, timeout=None: _FakeProc(1, '', 'boom'),
+ )
+ monkeypatch.setattr(
+ sts_module.socket, 'create_connection',
+ lambda addr, timeout=None: _FakeSocket(),
+ )
+ monkeypatch.setattr(
+ sts_module.requests, 'get',
+ lambda url, timeout=None, stream=False: _FakeResponse(b'x' * 100_000),
+ )
+ monkeypatch.setattr(
+ sts_module.requests, 'post',
+ lambda url, data=None, timeout=None: _FakeResponse(),
+ )
+
+ result = SpeedTestService.run_test()
+
+ assert result['success'] is True
+ assert result['method'] == 'fallback'
+
+
+# ── job handler ──────────────────────────────────────────────────────────────
+
+def test_job_handler_stores_last_result(app, monkeypatch):
+ from app.services.settings_service import SettingsService
+
+ fixed = {
+ 'success': True, 'method': 'fallback', 'download_mbps': 42.0,
+ 'upload_mbps': 7.5, 'latency_ms': 12.0, 'tested_at': '2026-07-03T00:00:00Z',
+ }
+ monkeypatch.setattr(SpeedTestService, 'run_test', classmethod(lambda cls: fixed))
+
+ class _JobStub:
+ def get_payload(self):
+ return {}
+
+ result = SpeedTestService.run_speed_test_job(_JobStub())
+
+ assert result == fixed
+ stored = SettingsService.get(LAST_RESULT_KEY)
+ assert json.loads(stored) == fixed
+
+
+def test_register_jobs_registers_handler(app):
+ from app.jobs import registry
+
+ SpeedTestService.register_jobs()
+ assert registry.get(SPEEDTEST_JOB_KIND) is not None
+
+
+# ── API ──────────────────────────────────────────────────────────────────────
+
+def st_client(app):
+ """Test client with the speedtest blueprint mounted (registration in
+ app/__init__.py is wired separately)."""
+ from app.api.speed_test import speedtest_bp
+ if 'speedtest' not in app.blueprints:
+ app.register_blueprint(speedtest_bp, url_prefix='/api/v1/speedtest')
+ return app.test_client()
+
+
+def test_get_returns_last_result_and_running_flag(st_client, auth_headers, app):
+ from app.services.settings_service import SettingsService
+
+ fixed = {'success': True, 'method': 'cli', 'download_mbps': 90.0,
+ 'upload_mbps': 30.0, 'latency_ms': 5.0,
+ 'tested_at': '2026-07-03T01:00:00Z'}
+ SettingsService.set(LAST_RESULT_KEY, json.dumps(fixed))
+
+ resp = st_client.get('/api/v1/speedtest', headers=auth_headers)
+
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data['last_result'] == fixed
+ assert data['running'] is False
+ assert data['job'] is None
+
+
+def test_get_with_no_result_yet(st_client, auth_headers):
+ resp = st_client.get('/api/v1/speedtest', headers=auth_headers)
+
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data['last_result'] is None
+ assert data['running'] is False
+
+
+def test_run_enqueues_job(st_client, auth_headers, monkeypatch):
+ from app.jobs.service import JobService
+
+ enqueued = []
+
+ class _FakeJob:
+ id = 'job-123'
+
+ def _fake_enqueue(kind, payload=None, max_attempts=3, **kwargs):
+ enqueued.append((kind, payload, max_attempts))
+ return _FakeJob()
+
+ monkeypatch.setattr(JobService, 'enqueue', staticmethod(_fake_enqueue))
+
+ resp = st_client.post('/api/v1/speedtest/run', headers=auth_headers)
+
+ assert resp.status_code == 202
+ assert resp.get_json() == {'job_id': 'job-123'}
+ assert enqueued == [(SPEEDTEST_JOB_KIND, {}, 1)]
+
+
+def test_run_rejects_when_already_running(st_client, auth_headers, app):
+ from app import db
+ from app.jobs.models import Job
+
+ job = Job(kind=SPEEDTEST_JOB_KIND, status=Job.STATUS_RUNNING)
+ job.set_payload({})
+ db.session.add(job)
+ db.session.commit()
+
+ resp = st_client.post('/api/v1/speedtest/run', headers=auth_headers)
+
+ assert resp.status_code == 409
+ assert 'error' in resp.get_json()
+
+
+def test_endpoints_require_auth(st_client):
+ assert st_client.get('/api/v1/speedtest').status_code == 401
+ assert st_client.post('/api/v1/speedtest/run').status_code == 401
diff --git a/frontend/src/pages/Monitoring.jsx b/frontend/src/pages/Monitoring.jsx
index cffd4018..4322131c 100644
--- a/frontend/src/pages/Monitoring.jsx
+++ b/frontend/src/pages/Monitoring.jsx
@@ -14,6 +14,8 @@ import { MetricCard, Pill, Gauge } from '@/components/ds';
import { useTopbarActions } from '@/hooks/useTopbarActions';
import {
Activity,
+ ArrowDown,
+ ArrowUp,
Bell,
Clock,
Cpu,
@@ -25,7 +27,9 @@ import {
RefreshCw,
Settings,
Siren,
+ Timer,
Webhook,
+ Zap,
} from 'lucide-react';
const VALID_TABS = ['overview', 'alerts', 'config', 'thresholds'];
@@ -68,6 +72,14 @@ function formatMetric(value, unit = '%') {
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':
@@ -99,6 +111,19 @@ const Monitoring = () => {
});
const [thresholdForm, setThresholdForm] = useState(DEFAULT_THRESHOLDS);
+ const [speedTest, setSpeedTest] = useState(null);
+ const [speedTestRunning, setSpeedTestRunning] = useState(false);
+
+ const loadSpeedTest = async () => {
+ try {
+ const res = await api.getSpeedTest();
+ setSpeedTest(res);
+ return res;
+ } catch {
+ // Speed test endpoint is optional — never block the page on it.
+ return null;
+ }
+ };
const loadData = async () => {
try {
@@ -129,6 +154,7 @@ const Monitoring = () => {
useEffect(() => {
loadData();
+ loadSpeedTest();
}, []);
const metricRules = useMemo(() => {
@@ -277,6 +303,33 @@ const Monitoring = () => {
}
};
+ const handleRunSpeedTest = async () => {
+ try {
+ setSpeedTestRunning(true);
+ await api.runSpeedTest();
+ const previousTestedAt = speedTest?.last_result?.tested_at || null;
+ const deadline = Date.now() + SPEEDTEST_POLL_TIMEOUT_MS;
+ while (Date.now() < deadline) {
+ await new Promise((resolve) => setTimeout(resolve, SPEEDTEST_POLL_INTERVAL_MS));
+ 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');
+ }
+ return;
+ }
+ }
+ toast.warning('Speed test is still running — refresh in a moment');
+ } catch (err) {
+ toast.error(err.message || 'Failed to start speed test');
+ } finally {
+ setSpeedTestRunning(false);
+ }
+ };
+
const updateThreshold = (key, value) => {
setThresholdForm((current) => ({
...current,
@@ -425,6 +478,57 @@ const Monitoring = () => {
</div>
</section>
+ <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>
+ </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&apos;s connection.</span>
+ </div>
+ )}
+ </section>
+
{activeAlerts.length > 0 && (
<section className="monitoring-panel monitoring-panel--warning">
<div className="monitoring-panel__header">
diff --git a/frontend/src/services/api/speedtest.js b/frontend/src/services/api/speedtest.js
new file mode 100644
index 00000000..a4b975d1
--- /dev/null
+++ b/frontend/src/services/api/speedtest.js
@@ -0,0 +1,9 @@
+// Server speed test API — backs the Monitoring overview card.
+
+export async function getSpeedTest() {
+ return this.request('/speedtest');
+}
+
+export async function runSpeedTest() {
+ return this.request('/speedtest/run', { method: 'POST' });
+}
diff --git a/frontend/src/styles/pages/_monitoring.scss b/frontend/src/styles/pages/_monitoring.scss
index 77368b8c..5545dfe8 100644
--- a/frontend/src/styles/pages/_monitoring.scss
+++ b/frontend/src/styles/pages/_monitoring.scss
@@ -447,4 +447,39 @@
font-size: 11px;
color: var(--text-faint);
}
+
+ // Speed test card (overview tab)
+ .mon-speedtest__grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
+ gap: $space-3;
+ }
+
+ .mon-speedtest__meta {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: $space-3;
+ margin-top: $space-3;
+
+ span {
+ font-family: var(--mono);
+ font-size: 11px;
+ color: var(--text-faint);
+ }
+ }
+
+ .mon-speedtest__error {
+ color: var(--red);
+ @include truncate();
+ max-width: 100%;
+ }
+
+ .mon-speedtest__empty {
+ span {
+ font-family: var(--mono);
+ font-size: 12px;
+ color: var(--text-faint);
+ }
+ }
}