Speedtest Tracker, Costs, "Having trouble" on status pages, grouped Integrations and Dashboard

- Speedtest Tracker integration: charts, alerts for a slow line (median of the
  last three tests under a share of what is paid for) and for failing tests.
- Costs page (Records): things paid for by hand plus Hetzner's estimate, totals
  per currency, bills rolled forward into Coming up as Renewals.
- Status pages: a "Having trouble" state for things that answer but have an open
  alert; Speedtest reads as the internet.
- Integrations page and kind picker grouped like the sidebar (one shared types
  file); Notifications "What to send" shown one group at a time; Dashboard
  integration sections follow the menu groups, with tiles for integrations that
  have no widget.
- Docs, tests, and ROLES.md menu table brought up to date.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-26 23:23:46 +01:00
1 parent 78822346b1
commit f86661f6c9
49 files changed
+18156 -238

No files matched your search

+1
View File
@@ -19,6 +19,7 @@ const KINDS: { id: AgendaKind; label: string }[] = [
{ id: "restore", label: "Restore tests" },
{ id: "updates", label: "Updates waiting" },
{ id: "todo", label: "To do" },
{ id: "renewal", label: "Renewals" },
];
const KIND_LABEL = Object.fromEntries(KINDS.map((k) => [k.id, k.label])) as Record<AgendaKind, string>;
+269
View File
@@ -0,0 +1,269 @@
import { useEffect, useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { api, type CostInput, type CostItem, type CostsReport, type CurrentUser } from "../api/client";
import EmptyState from "../components/EmptyState";
import { BlockSkeleton } from "../components/Skeleton";
import { ErrorNotice } from "../components/Notice";
import { confirmDialog } from "../utils/dialogs";
import { formatDate } from "../utils/date";
import { readableError } from "../utils/errors";
import { toast } from "../utils/toast";
const money = (n: number, currency: string) => {
try {
return new Intl.NumberFormat(undefined, { style: "currency", currency }).format(n);
} catch {
return `${n.toFixed(2)} ${currency}`;
}
};
const blank = (currency: string): CostInput => ({ name: "", amount: 0, currency, period: "month", category: "Subscriptions", renewsOn: null, note: null });
function ItemForm({ initial, categories, currencies, saving, onSave, onCancel }: { initial: CostInput; categories: string[]; currencies: string[]; saving: boolean; onSave: (v: CostInput) => void; onCancel: () => void }) {
const [v, setV] = useState<CostInput>(initial);
const [amount, setAmount] = useState(initial.amount > 0 ? String(initial.amount) : "");
const parsed = Number(amount.replace(",", "."));
const valid = v.name.trim() !== "" && Number.isFinite(parsed) && parsed > 0 && /^[A-Za-z]{3}$/.test(v.currency.trim());
return (
<form
className="row g-2 align-items-end mb-3"
onSubmit={(e) => {
e.preventDefault();
if (valid) onSave({ ...v, name: v.name.trim(), amount: parsed, currency: v.currency.trim().toUpperCase(), category: v.category.trim() || "Other", note: (v.note ?? "").trim() === "" ? null : (v.note ?? "").trim() });
}}
>
<div className="col-md-3">
<label className="form-label">What</label>
<input className="form-control" required maxLength={100} placeholder="e.g. tooweb.se domain, VPN, Plex pass" value={v.name} onChange={(e) => setV({ ...v, name: e.target.value })} autoFocus />
</div>
<div className="col-6 col-md-2">
<label className="form-label">Amount</label>
<input className="form-control" required inputMode="decimal" placeholder="9.99" value={amount} onChange={(e) => setAmount(e.target.value)} />
</div>
<div className="col-6 col-md-1">
<label className="form-label">Currency</label>
<input className="form-control text-uppercase" required maxLength={3} list="cost-currencies" value={v.currency} onChange={(e) => setV({ ...v, currency: e.target.value })} />
<datalist id="cost-currencies">
{currencies.map((c) => (
<option key={c} value={c} />
))}
</datalist>
</div>
<div className="col-6 col-md-2">
<label className="form-label">Paid</label>
<select className="form-select" value={v.period} onChange={(e) => setV({ ...v, period: e.target.value as CostInput["period"] })}>
<option value="month">every month</option>
<option value="year">every year</option>
</select>
</div>
<div className="col-6 col-md-2">
<label className="form-label">Kind</label>
<input className="form-control" maxLength={40} list="cost-categories" value={v.category} onChange={(e) => setV({ ...v, category: e.target.value })} />
<datalist id="cost-categories">
{categories.map((c) => (
<option key={c} value={c} />
))}
</datalist>
</div>
<div className="col-md-2">
<label className="form-label">A day it is billed (optional)</label>
<input type="date" className="form-control" value={v.renewsOn ?? ""} onChange={(e) => setV({ ...v, renewsOn: e.target.value === "" ? null : e.target.value })} />
</div>
<div className="col-md-8">
<label className="form-label">Note (optional)</label>
<input className="form-control" maxLength={300} placeholder="where it is paid, what it covers, when to cancel…" value={v.note ?? ""} onChange={(e) => setV({ ...v, note: e.target.value })} />
</div>
<div className="col-md-4 d-flex gap-2">
<button className="btn btn-primary" disabled={!valid || saving}>
{saving ? "Saving…" : "Save"}
</button>
<button type="button" className="btn" disabled={saving} onClick={onCancel}>
Cancel
</button>
</div>
</form>
);
}
/** What the homelab costs: what is paid for by hand, what can be read (Hetzner), the totals per currency and when each is billed next. */
export default function Costs({ user }: { user: CurrentUser }) {
const isAdmin = user.role === "admin";
const [report, setReport] = useState<CostsReport | null>(null);
const [error, setError] = useState<string | null>(null);
const [form, setForm] = useState<{ id: number | null; value: CostInput } | null>(null);
const [saving, setSaving] = useState(false);
function load() {
api.costs
.get()
.then((r) => {
setReport(r);
setError(null);
})
.catch((err) => setError(readableError(err)));
}
useEffect(load, []);
const currencies = useMemo(() => [...new Set([...(report?.totals.map((t) => t.currency) ?? []), "EUR", "SEK", "USD"])], [report]);
const defaultCurrency = report?.totals[0]?.currency ?? "EUR";
async function save(value: CostInput) {
setSaving(true);
try {
if (form?.id != null) await api.costs.update(form.id, value);
else await api.costs.create(value);
toast.success(form?.id != null ? "Saved." : "Added.");
setForm(null);
load();
} catch (err) {
toast.error(readableError(err));
} finally {
setSaving(false);
}
}
async function remove(i: CostItem) {
if (!(await confirmDialog({ title: "Remove from costs", message: `Remove "${i.name}"?`, confirmLabel: "Remove", danger: true }))) return;
try {
await api.costs.remove(i.id);
toast.success("Removed.");
load();
} catch (err) {
toast.error(readableError(err));
}
}
const empty = report && report.items.length === 0 && report.automatic.length === 0;
return (
<>
<div className="d-flex flex-wrap align-items-center gap-3 mb-3">
<div style={{ flex: "1 1 320px", minWidth: 0 }}>
<h2 className="page-title mb-0">Costs</h2>
<div className="text-secondary small mt-1">
What the homelab costs, in one place: what you pay for by hand and what can be read (a Hetzner project&rsquo;s estimate — see <Link to="/hetzner">Hetzner Cloud</Link>). Each currency has its own total; none is converted into another. A day a bill falls on shows under <Link to="/coming-up">Coming up</Link>.
</div>
</div>
{isAdmin && !form && (
<button className="btn btn-primary ms-auto flex-shrink-0" onClick={() => setForm({ id: null, value: blank(defaultCurrency) })}>
Add something you pay for
</button>
)}
</div>
<ErrorNotice error={error} />
{!report && !error && <BlockSkeleton lines={4} />}
{report && report.totals.length > 0 && (
<div className="row g-3 mb-3">
{report.totals.map((t) => (
<div className="col-md-6 col-xl-4" key={t.currency}>
<div className="card h-100">
<div className="card-body">
<div className="text-secondary small">{t.currency} — {t.items} {t.items === 1 ? "item" : "items"}</div>
<div className="h1 mb-0">{money(t.monthly, t.currency)} <span className="h4 text-secondary fw-normal">a month</span></div>
<div className="text-secondary">{money(t.yearly, t.currency)} a year</div>
<div className="mt-3">
{t.categories.map((c) => (
<div key={c.category} className="mb-1">
<div className="d-flex small">
<span>{c.category}</span>
<span className="ms-auto text-secondary">{money(c.monthly, t.currency)}</span>
</div>
<div className="progress progress-sm">
<div className="progress-bar" style={{ width: `${t.monthly > 0 ? Math.max(2, (c.monthly / t.monthly) * 100) : 0}%` }} />
</div>
</div>
))}
</div>
</div>
</div>
</div>
))}
</div>
)}
{form && (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">{form.id != null ? "Change it" : "Add something you pay for"}</h3>
</div>
<div className="card-body">
<ItemForm initial={form.value} categories={report?.categories ?? []} currencies={currencies} saving={saving} onSave={(v) => void save(v)} onCancel={() => setForm(null)} />
<div className="text-secondary small">The amount is what is paid each time, with VAT. The day it is billed is only a starting point: the next time it falls (the same day next month, or next year) is worked out from it.</div>
</div>
</div>
)}
{empty && (
<div className="card">
<div className="card-body">
<EmptyState title="Nothing added yet" hint={isAdmin ? "Add the domains, VPN, licences and subscriptions you pay for; a Hetzner project's estimate is added by itself." : "An administrator adds what is paid for."} />
</div>
</div>
)}
{report && !empty && (
<div className="card">
<div className="table-responsive">
<table className="table table-vcenter card-table">
<thead>
<tr>
<th>What</th>
<th>Kind</th>
<th>Paid</th>
<th>Per month</th>
<th>Billed next</th>
<th />
</tr>
</thead>
<tbody>
{report.automatic.map((a) => (
<tr key={a.key}>
<td>
<strong>{a.name}</strong> <span className="badge bg-blue-lt text-blue">read from {a.source}</span>
<div className="text-secondary small text-break">{a.detail}{a.stale ? " — not read lately, so this may be out of date" : ""}</div>
</td>
<td className="text-secondary">Hosting</td>
<td className="text-secondary">estimate</td>
<td>{money(a.monthly, a.currency)}</td>
<td className="text-secondary">—</td>
<td className="text-end">
<Link to={a.link} className="btn btn-sm">
Open
</Link>
</td>
</tr>
))}
{report.items.map((i) => (
<tr key={i.id}>
<td className="text-break">
<strong>{i.name}</strong>
{i.note && <div className="text-secondary small">{i.note}</div>}
</td>
<td className="text-secondary">{i.category}</td>
<td className="text-secondary">
{money(i.amount, i.currency)} {i.period === "year" ? "a year" : "a month"}
</td>
<td>{money(i.monthly, i.currency)}</td>
<td className="text-secondary">{i.nextRenewal ? formatDate(new Date(`${i.nextRenewal}T12:00:00Z`)) : "—"}</td>
<td className="text-end">
{isAdmin && (
<div className="btn-list justify-content-end flex-nowrap">
<button className="btn btn-sm" onClick={() => setForm({ id: i.id, value: { name: i.name, amount: i.amount, currency: i.currency, period: i.period, category: i.category, renewsOn: i.renewsOn, note: i.note } })}>
Edit
</button>
<button className="btn btn-sm btn-outline-danger" onClick={() => void remove(i)}>
Remove
</button>
</div>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
</>
);
}
+73 -8
View File
@@ -1,5 +1,5 @@
import { useMyWork } from "../hooks/useMyWork";
import { isValidElement, useEffect, useState, type ReactNode } from "react";
import { Fragment, isValidElement, useEffect, useState, type ReactNode } from "react";
import { IconArrowLeft, IconArrowRight, IconEye, IconEyeOff } from "@tabler/icons-react";
import TimeAgo from "../components/TimeAgo";
import WhatChanged from "../components/WhatChanged";
@@ -24,6 +24,7 @@ import StatusStrip from "../components/StatusStrip";
import SetupGuide, { type SetupStep } from "../components/SetupGuide";
import { ErrorNotice } from "../components/Notice";
import { WidgetSkeleton } from "../components/Skeleton";
import { TYPE_GROUPS, TYPE_LABELS, TYPE_PAGES } from "../utils/integrationTypes";
import type { Agenda, Heartbeat } from "../api/client";
const DNS_TYPE_COLORS: Record<string, string> = {
@@ -238,6 +239,16 @@ function WidgetCard({ label, badge, hide, children }: { label: string; badge?: R
);
}
/** What each group of integrations is, in a line — the groups are the sidebar's. */
const GROUP_HINTS: Record<string, string> = {
infrastructure: "The systems your servers and containers run on.",
apps: "The apps you run, and whether each is working.",
backups: "Where backups are kept and checked.",
network: "Network equipment, proxies and address records.",
monitoring: "What watches the rest.",
automation: "Runs, tickets and workflows.",
};
const WIDGETS: { type: IntegrationType; label: string }[] = [
{ type: "proxmox", label: "Proxmox" },
{ type: "synology", label: "Synology NAS" },
@@ -345,6 +356,8 @@ export default function Dashboard({ user }: { user: CurrentUser }) {
const { editing } = useDashboardLayout();
const problemsFirst = useProblemsFirst();
const [integrations, setIntegrations] = useState<IntegrationSummary[] | null>(null);
// How many alerts each integration has open that nobody has put aside, for the tiles of the integrations that have no widget of their own.
const [integrationAlerts, setIntegrationAlerts] = useState<Map<number, { count: number; critical: boolean }>>(new Map());
const [tailscaleSummary, setTailscaleSummary] = useState<TailscaleDevicesResponse["summary"] | null>(null);
const [tailscaleExtra, setTailscaleExtra] = useState<TailscaleExtra | null>(null);
const [giteaSummary, setGiteaSummary] = useState<GiteaSummary | null>(null);
@@ -419,6 +432,20 @@ export default function Dashboard({ user }: { user: CurrentUser }) {
useEffect(() => {
api.integrations.list().then((res) => setIntegrations(res.integrations));
api.alerts
.list()
.then((report) => {
const found = new Map<number, { count: number; critical: boolean }>();
for (const a of report.alerts) {
if (a.silenced || a.severity === "info" || a.target?.type !== "integration") continue;
const entry = found.get(a.target.id) ?? { count: 0, critical: false };
entry.count++;
if (a.severity === "critical") entry.critical = true;
found.set(a.target.id, entry);
}
setIntegrationAlerts(found);
})
.catch(() => {});
}, []);
useEffect(() => {
@@ -1107,12 +1134,11 @@ export default function Dashboard({ user }: { user: CurrentUser }) {
</WidgetCard>
</div>
<SectionHeader
title="Integrations"
hint="Live status widgets for Proxmox, Synology, Semaphore, Tailscale, Gitea, Dockhand, Uptime Kuma, Proxmox Backup Server, and osTicket will appear here as each integration is connected."
/>
<div className="row row-cards">
{WIDGETS.map(({ type, label }) => {
{TYPE_GROUPS.filter((group) => integrations?.some((i) => group.types.includes(i.type))).map((group) => (
<Fragment key={group.id}>
<SectionHeader title={group.label} hint={GROUP_HINTS[group.id]} />
<div className="row row-cards">
{WIDGETS.filter(({ type }) => group.types.includes(type)).map(({ type, label }) => {
const integration = integrations?.find((i) => i.type === type && i.enabled);
const isLiveTailscale = type === "tailscale" && integration && tailscaleSummary;
const isLiveGitea = type === "gitea" && integration && giteaSummary;
@@ -1363,7 +1389,46 @@ export default function Dashboard({ user }: { user: CurrentUser }) {
</WidgetCard>
);
})}
</div>
{/* The integrations with no widget of their own get a small tile: whether they work, how many alerts are open, and where to look. */}
{(integrations ?? [])
.filter((i) => group.types.includes(i.type) && !WIDGETS.some((w) => w.type === i.type))
.sort((a, b) => a.name.localeCompare(b.name))
.map((i) => {
const alerts = integrationAlerts.get(i.id);
const failing = i.enabled && i.health?.status === "failing";
const badge = !i.enabled ? (
<span className="badge bg-secondary-lt text-secondary">Disabled</span>
) : failing || alerts?.critical ? (
<span className="badge bg-red-lt text-red">{failing ? "Failing" : "Needs a look"}</span>
) : alerts ? (
<span className="badge bg-yellow-lt text-yellow">Needs a look</span>
) : i.health?.status === "ok" ? (
<span className="badge bg-green-lt text-green">Working</span>
) : (
<span className="badge bg-secondary-lt text-secondary">Not checked yet</span>
);
return (
<WidgetCard key={i.id} label={i.name === TYPE_LABELS[i.type] ? i.name : `${TYPE_LABELS[i.type]}: ${i.name}`} badge={badge}>
<div className="text-secondary">
{failing
? `Its last ${i.health?.consecutiveFailures ?? 0} calls failed.`
: alerts
? `${alerts.count} open ${alerts.count === 1 ? "alert" : "alerts"}.`
: i.enabled
? "Nothing open."
: "Switched off under Integrations."}
</div>
{i.enabled && (
<div className="mt-2">
<Link to={TYPE_PAGES[i.type]}>Open {TYPE_LABELS[i.type]}</Link>
</div>
)}
</WidgetCard>
);
})}
</div>
</Fragment>
))}
{notSetUp.length > 0 && (
<div className="card mt-4">
+21 -57
View File
@@ -1,4 +1,4 @@
import { useEffect, useState, type CSSProperties, type ReactNode } from "react";
import { Fragment, useEffect, useState, type CSSProperties, type ReactNode } from "react";
import { Link, useSearchParams } from "react-router-dom";
import { api, type CurrentUser, type IntegrationSummary, type IntegrationType } from "../api/client";
import IntegrationForm from "../components/IntegrationForm";
@@ -13,59 +13,7 @@ import { ErrorNotice } from "../components/Notice";
import { toast } from "../utils/toast";
import UptimeRibbon from "../components/UptimeRibbon";
import RunbookEntry from "../components/RunbookEntry";
const TYPE_LABELS: Record<IntegrationType, string> = {
tailscale: "Tailscale",
proxmox: "Proxmox",
synology: "Synology",
semaphore: "Semaphore",
gitea: "Gitea",
dockhand: "Dockhand",
uptimekuma: "Uptime Kuma",
phpipam: "phpIPAM",
pbs: "Proxmox Backup Server",
osticket: "osTicket",
unifi: "UniFi",
npm: "Nginx Proxy Manager",
homeassistant: "Home Assistant",
ups: "UPS",
jellyfin: "Jellyfin",
authentik: "Authentik",
prometheus: "Prometheus",
immich: "Immich",
paperless: "Paperless-ngx",
n8n: "n8n",
netbox: "NetBox",
nextcloud: "Nextcloud",
hetzner: "Hetzner Cloud",
};
/** The page each kind of integration gets once it is connected. */
const TYPE_PAGES: Record<IntegrationType, string> = {
tailscale: "/tailscale",
proxmox: "/proxmox",
synology: "/synology",
semaphore: "/semaphore",
gitea: "/gitea",
dockhand: "/docker",
uptimekuma: "/uptime-kuma",
phpipam: "/ipam",
pbs: "/pbs",
osticket: "/osticket",
unifi: "/network/devices",
npm: "/proxy-hosts",
homeassistant: "/home-assistant",
ups: "/ups",
jellyfin: "/jellyfin",
authentik: "/authentik",
prometheus: "/prometheus",
immich: "/immich",
paperless: "/paperless",
n8n: "/n8n",
netbox: "/netbox",
nextcloud: "/nextcloud",
hetzner: "/hetzner",
};
import { groupOfType, TYPE_GROUPS, TYPE_LABELS, TYPE_PAGES } from "../utils/integrationTypes";
/** "pve.example.lan" out of "https://pve.example.lan:8006/", or the text itself when it isn't an address. */
function hostOf(baseUrl: string): string {
@@ -202,6 +150,14 @@ function IntegrationsList({ user, tabs }: { user: CurrentUser; tabs: ReactNode }
(statusFilter === "disabled" ? !i.enabled : statusFilter === "failing" ? i.enabled && i.health?.status === "failing" : i.enabled && i.health?.status === "ok");
const sortedIntegrations = tableSearch.filtered ? [...tableSearch.filtered].filter(matchesStatus).sort((a, b) => a.name.localeCompare(b.name)) : null;
// The cards in groups, as the sidebar groups their pages (a kind nobody has placed goes under "Other").
const groupedIntegrations = (() => {
const groups = new Map<string, { id: string; label: string; items: IntegrationSummary[] }>();
for (const g of [...TYPE_GROUPS.map(({ id, label }) => ({ id, label })), { id: "other", label: "Other" }]) groups.set(g.id, { ...g, items: [] });
for (const i of sortedIntegrations ?? []) groups.get(groupOfType(i.type).id)!.items.push(i);
return [...groups.values()].filter((g) => g.items.length > 0);
})();
function exportCsv() {
if (!sortedIntegrations) return;
downloadCsv(
@@ -217,8 +173,7 @@ function IntegrationsList({ user, tabs }: { user: CurrentUser; tabs: ReactNode }
<div>
<h2 className="page-title mb-0">Integrations</h2>
<div className="text-secondary small mt-1">
Tailscale, Proxmox, Synology, Semaphore, Gitea, Dockhand, and Uptime Kuma each get their own page
once connected — add and manage credentials here.
Each connected system gets its own page — open it from here or from the sidebar, in the group shown. Add and manage credentials here.
</div>
</div>
{isAdmin && !adding && !editingIntegration && (
@@ -287,7 +242,14 @@ function IntegrationsList({ user, tabs }: { user: CurrentUser; tabs: ReactNode }
</div>
<div className="row row-cards">
{sortedIntegrations?.map((i) => {
{groupedIntegrations.map((group) => (
<Fragment key={group.id}>
<div className="col-12">
<h4 className="mb-0 mt-2">
{group.label} <span className="text-secondary fw-normal small">{group.items.length}</span>
</h4>
</div>
{group.items.map((i) => {
const result = testResults[i.id];
const page = TYPE_PAGES[i.type];
return (
@@ -348,6 +310,8 @@ function IntegrationsList({ user, tabs }: { user: CurrentUser; tabs: ReactNode }
</div>
);
})}
</Fragment>
))}
{sortedIntegrations?.length === 0 && (
<div className="col-12">
<div className="card">
+4
View File
@@ -8,6 +8,7 @@ const REFRESH_MS = 30_000;
const STATE: Record<PublicStatusItem["state"], { label: string; badge: string }> = {
up: { label: "Working", badge: "bg-green-lt text-green" },
trouble: { label: "Having trouble", badge: "bg-yellow-lt text-yellow" },
down: { label: "Not working", badge: "bg-red-lt text-red" },
maintenance: { label: "Being worked on", badge: "bg-blue-lt text-blue" },
unknown: { label: "Can't tell right now", badge: "bg-secondary-lt text-secondary" },
@@ -15,6 +16,7 @@ const STATE: Record<PublicStatusItem["state"], { label: string; badge: string }>
const BANNER: Record<PublicStatus["level"], { alert: string; icon: JSX.Element }> = {
ok: { alert: "alert-success", icon: <IconCircleCheck size={22} /> },
trouble: { alert: "alert-warning", icon: <IconAlertTriangle size={22} /> },
issue: { alert: "alert-danger", icon: <IconAlertTriangle size={22} /> },
maintenance: { alert: "alert-info", icon: <IconTool size={22} /> },
unknown: { alert: "alert-secondary", icon: <IconHelpCircle size={22} /> },
@@ -26,6 +28,8 @@ function headline(page: PublicStatus): string {
switch (page.level) {
case "issue":
return counts.down === 1 ? "One thing isn't working" : `${counts.down} things aren't working`;
case "trouble":
return counts.trouble === 1 ? "One thing is having trouble" : `${counts.trouble} things are having trouble`;
case "maintenance":
return counts.maintenance === 1 ? "One thing is being worked on" : `${counts.maintenance} things are being worked on`;
case "unknown":
+180
View File
@@ -0,0 +1,180 @@
import { useEffect, useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { api, type SpeedtestHistory, type SpeedtestInfo } from "../api/client";
import EmptyState from "../components/EmptyState";
import RangeSelect from "../components/RangeSelect";
import TimeAgo from "../components/TimeAgo";
import TimeChart from "../components/TimeChart";
import { BlockSkeleton } from "../components/Skeleton";
import { ErrorNotice } from "../components/Notice";
import { useChartRange } from "../utils/chartRanges";
import { readableError } from "../utils/errors";
function Badge({ s }: { s: SpeedtestInfo }) {
if (!s.enabled) return <span className="badge bg-secondary-lt text-secondary">Off</span>;
if (!s.state) return <span className="badge bg-secondary-lt text-secondary">Not read yet</span>;
if (!s.fresh) return <span className="badge bg-yellow-lt text-yellow">Can&rsquo;t be read</span>;
if (s.problems.length > 0) return <span className="badge bg-yellow-lt text-yellow">Needs a look</span>;
return <span className="badge bg-green-lt text-green">In order</span>;
}
/** Bits per second as the line is sold: decimal megabits. */
const mbit = (bps: number | null) => (bps === null ? "—" : `${bps / 1e6 >= 100 ? Math.round(bps / 1e6) : (bps / 1e6).toFixed(1)} Mbit/s`);
const share = (bps: number | null, expected: number | null) => (bps === null || expected === null ? null : Math.round((bps / (expected * 1e6)) * 100));
function Tile({ label, value, sub }: { label: string; value: string; sub?: string | null }) {
return (
<div className="col-6 col-lg-3">
<div className="card card-sm h-100">
<div className="card-body">
<div className="text-secondary small">{label}</div>
<div className="h2 mb-0">{value}</div>
{sub && <div className="text-secondary small">{sub}</div>}
</div>
</div>
</div>
);
}
function History({ id, name }: { id: number; name: string }) {
const [days, setDays] = useChartRange(7);
const shown = days > 90 ? 90 : days;
const [history, setHistory] = useState<SpeedtestHistory | null>(null);
const [error, setError] = useState<string | null>(null);
const [to, setTo] = useState(() => Date.now());
useEffect(() => {
let alive = true;
api.speedtest
.history(id, shown)
.then((res) => {
if (!alive) return;
setHistory(res);
setTo(Date.now());
setError(null);
})
.catch((err) => alive && setError(readableError(err)));
return () => {
alive = false;
};
}, [id, shown]);
const from = to - shown * 86_400_000;
const speeds = useMemo(
() => [
{ name: "Download", color: "#4299e1", points: (history?.points ?? []).filter((p) => p.download !== null).map((p) => ({ t: p.t, v: p.download as number })) },
{ name: "Upload", color: "#2fb344", dash: "4 3", points: (history?.points ?? []).filter((p) => p.upload !== null).map((p) => ({ t: p.t, v: p.upload as number })) },
],
[history],
);
const pings = useMemo(() => [{ name: "Ping", color: "#f76707", points: (history?.points ?? []).filter((p) => p.ping !== null).map((p) => ({ t: p.t, v: p.ping as number })) }], [history]);
return (
<div className="mt-3">
<div className="d-flex align-items-center mb-2">
<h4 className="mb-0">How fast it has been</h4>
<div className="ms-auto">
<RangeSelect value={shown} onChange={setDays} only={[1, 7, 30, 90]} />
</div>
</div>
<ErrorNotice error={error} />
{!history && !error && <BlockSkeleton lines={3} />}
{history && (
<>
<TimeChart series={speeds} from={from} to={to} unit="ms" compact label={`${name}: download and upload speed`} empty="No tests in this stretch yet." format={(v) => `${v >= 100 ? Math.round(v) : v.toFixed(1)} Mbit/s`} />
<TimeChart series={pings} from={from} to={to} unit="ms" compact label={`${name}: ping`} empty="No tests in this stretch yet." />
</>
)}
</div>
);
}
function Card({ s }: { s: SpeedtestInfo }) {
const st = s.state;
const latest = st?.latest ?? null;
const dl = s.expected.downloadMbps;
const ul = s.expected.uploadMbps;
return (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">
{s.name} <Badge s={s} />
</h3>
<div className="card-actions text-secondary small">{s.status ? <>read <TimeAgo value={s.status.at} /></> : "not read yet"}</div>
</div>
<div className="card-body">
{s.status && !s.status.ok && <div className="text-yellow mb-2">The last attempt to read it failed: {s.status.error ?? "no answer"}.</div>}
{s.problems.length > 0 && (
<ul className="mb-3">
{s.problems.map((p) => (
<li key={p.key}>{p.message}</li>
))}
</ul>
)}
{st && (
<>
<div className="row g-3">
<Tile label="Download, latest" value={mbit(latest?.download ?? null)} sub={dl !== null && share(latest?.download ?? null, dl) !== null ? `${share(latest?.download ?? null, dl)}% of the ${dl} Mbit/s it is sold at` : null} />
<Tile label="Upload, latest" value={mbit(latest?.upload ?? null)} sub={ul !== null && share(latest?.upload ?? null, ul) !== null ? `${share(latest?.upload ?? null, ul)}% of the ${ul} Mbit/s it is sold at` : null} />
<Tile label="Ping, latest" value={latest?.ping == null ? "—" : `${Math.round(latest.ping)} ms`} sub={latest ? undefined : "no completed test yet"} />
<Tile
label={`The middle of the last ${st.middle.count || 3}`}
value={st.middle.count > 0 ? `${mbit(st.middle.download)} down` : "—"}
sub={st.middle.count > 0 ? `${mbit(st.middle.upload)} up · ${st.middle.ping === null ? "—" : `${Math.round(st.middle.ping)} ms`} — what the alerts judge` : "needs completed tests"}
/>
</div>
<div className="text-secondary small mt-2">
{st.lastTest ? (
<>
Last test <TimeAgo value={st.lastTest.at} /> ({st.lastTest.status}){latest && latest.healthy !== null ? ` · Speedtest Tracker calls it ${latest.healthy ? "healthy" : "not healthy"}` : ""}.{" "}
</>
) : null}
{dl === null && ul === null ? (
<>
Tell the integration what you pay for (<em>download you pay for</em>, <em>upload you pay for</em> under <Link to={`/integrations?editId=${s.id}`}>Integrations</Link>) and a slow line becomes an alert; until then only failing tests are.
</>
) : (
<>An alert is raised when the middle of the last three is under {s.expected.minPercent}% of what you pay for.</>
)}
</div>
<History id={s.id} name={s.name} />
</>
)}
</div>
</div>
);
}
/** Speedtest Tracker: how fast the internet has been, against what it is sold at. */
export default function Speedtest() {
const [data, setData] = useState<SpeedtestInfo[] | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const load = () =>
api.speedtest
.list()
.then((r) => {
setData(r.speedtests);
setError(null);
})
.catch((err) => setError(readableError(err)));
void load();
const t = setInterval(load, 60_000);
return () => clearInterval(t);
}, []);
return (
<>
<h2 className="page-title">Speedtest</h2>
<p className="text-secondary">
What Speedtest Tracker has measured, read every few minutes (see <Link to="/integrations">Integrations</Link>) — this app never starts a test. <strong>The internet slower than it is sold at</strong> and <strong>speed tests that keep failing</strong> are alerts — see <Link to="/alerts">Alerts</Link>.
</p>
<ErrorNotice error={error} />
{!data && !error && <BlockSkeleton lines={4} />}
{data && data.length === 0 && (
<div className="card">
<div className="card-body">
<EmptyState title="No Speedtest Tracker connected" hint="Add one under Integrations with its address and an API token (profile menu → API tokens, with the results:read ability)." />
</div>
</div>
)}
{data?.map((s) => <Card key={s.id} s={s} />)}
</>
);
}
+2 -27
View File
@@ -1,4 +1,5 @@
import { useEffect, useState } from "react";
import { TYPE_LABELS } from "../../utils/integrationTypes";
import { api } from "../../api/client";
import { ErrorNotice } from "../../components/Notice";
import { PageSkeleton } from "../../components/Skeleton";
@@ -12,32 +13,6 @@ const PROVIDER_NAMES: Record<string, string> = {
technitium: "Technitium",
};
const INTEGRATION_NAMES: Record<string, string> = {
tailscale: "Tailscale",
proxmox: "Proxmox",
synology: "Synology",
semaphore: "Semaphore",
gitea: "Gitea",
dockhand: "Dockhand",
uptimekuma: "Uptime Kuma",
phpipam: "phpIPAM",
pbs: "Proxmox Backup Server",
osticket: "osTicket",
unifi: "UniFi",
npm: "Nginx Proxy Manager",
homeassistant: "Home Assistant",
ups: "UPS",
jellyfin: "Jellyfin",
authentik: "Authentik",
prometheus: "Prometheus",
immich: "Immich",
paperless: "Paperless-ngx",
n8n: "n8n",
netbox: "NetBox",
nextcloud: "Nextcloud",
hetzner: "Hetzner Cloud",
};
function ColorList({
names,
colors,
@@ -148,7 +123,7 @@ export default function BadgeSettings() {
<div className="card-body">
<p className="text-secondary">Customize the color of each integration type's badge throughout the app.</p>
<ColorList
names={INTEGRATION_NAMES}
names={TYPE_LABELS}
colors={integrationColors}
onChange={(id, color) => setIntegrationColors((c) => ({ ...c, [id]: color }))}
/>
@@ -90,6 +90,16 @@ const DEFAULT_MONTHLY: MonthlyReportSettings = { enabled: false, quarterly: fals
type TestResult = { ok: boolean; message: string } | null;
type EventKey = { [K in keyof NotificationEvents]: NotificationEvents[K] extends boolean ? K : never }[keyof NotificationEvents];
/** The groups of events on the What to send tab, one shown at a time (`?section=`) so the page is a card long, not five. */
const SECTIONS = [
{ id: "servers", label: "Servers and disks" },
{ id: "secrets", label: "Secrets, keys and domains" },
{ id: "backups", label: "Backups and updates" },
{ id: "integrations", label: "Integrations and automation" },
{ id: "dns", label: "DNS changes" },
] as const;
type SectionId = (typeof SECTIONS)[number]["id"];
const TABS = [
{ id: "channels", label: "Channels" },
{ id: "events", label: "What to send" },
@@ -217,6 +227,8 @@ export default function NotificationSettings() {
const [params, setParams] = useSearchParams();
const tabParam = params.get("tab");
const tab: TabId = TABS.some((t) => t.id === tabParam) ? (tabParam as TabId) : "channels";
const sectionParam = params.get("section");
const section: SectionId = SECTIONS.some((s) => s.id === sectionParam) ? (sectionParam as SectionId) : "servers";
const tabRefs = useRef<Record<string, HTMLButtonElement | null>>({});
const [openChannel, setOpenChannel] = useState<string | null>(null);
@@ -320,6 +332,19 @@ export default function NotificationSettings() {
);
}
function selectSection(id: SectionId) {
setParams(
(prev) => {
const next = new URLSearchParams(prev);
if (id === "servers") next.delete("section");
else next.set("section", id);
next.set("tab", "events");
return next;
},
{ replace: true },
);
}
function onTabKey(e: KeyboardEvent<HTMLButtonElement>) {
const at = TABS.findIndex((t) => t.id === tab);
const to = e.key === "ArrowRight" ? (at + 1) % TABS.length : e.key === "ArrowLeft" ? (at + TABS.length - 1) % TABS.length : e.key === "Home" ? 0 : e.key === "End" ? TABS.length - 1 : -1;
@@ -700,8 +725,17 @@ export default function NotificationSettings() {
{/* ── What to send ── */}
<div role="tabpanel" id="panel-events" aria-labelledby="tab-events" hidden={tab !== "events"} className="pt-3">
<p className="text-secondary">Which events send a notification, on every channel that is on. Each group keeps its thresholds beside the switch they belong to.</p>
<ul className="nav nav-pills mb-3" role="group" aria-label="Groups of notifications">
{SECTIONS.map((s) => (
<li className="nav-item" key={s.id}>
<button type="button" className={`nav-link ${section === s.id ? "active" : ""}`} aria-pressed={section === s.id} onClick={() => selectSection(s.id)}>
{s.label}
</button>
</li>
))}
</ul>
<div className="row row-cards">
<div className="col-md-6">
<div className="col-lg-8" hidden={section !== "servers"}>
<div className="card h-100">
<div className="card-header">
<h3 className="card-title">Servers and disks</h3>
@@ -791,7 +825,7 @@ export default function NotificationSettings() {
</div>
</div>
<div className="col-md-6">
<div className="col-lg-8" hidden={section !== "secrets"}>
<div className="card h-100">
<div className="card-header">
<h3 className="card-title">Secrets, keys and domains</h3>
@@ -814,7 +848,7 @@ export default function NotificationSettings() {
</div>
</div>
<div className="col-md-6">
<div className="col-lg-8" hidden={section !== "backups"}>
<div className="card h-100">
<div className="card-header">
<h3 className="card-title">Backups and updates</h3>
@@ -879,7 +913,7 @@ export default function NotificationSettings() {
</div>
</div>
<div className="col-md-6">
<div className="col-lg-8" hidden={section !== "integrations"}>
<div className="card h-100">
<div className="card-header">
<h3 className="card-title">Integrations and automation</h3>
@@ -902,7 +936,7 @@ export default function NotificationSettings() {
</div>
</div>
<div className="col-md-6">
<div className="col-lg-8" hidden={section !== "dns"}>
<div className="card h-100">
<div className="card-header">
<h3 className="card-title">DNS changes</h3>