Files
Homelab-manager/web/src/pages/settings/NotificationSettings.tsx
T
bobbanandClaude Sonnet 5.5 43fc5e0272 Notification routing rules, per-browser push wishes, escalation of unacknowledged alerts
- Routing: rules pick channels by kind, severity and server tags (first match wins, none = nobody); mixed batches split per route; recoveries follow their alert; quiet-hours digest keeps each notification's audience
- Push: each subscribed browser can ask for a minimum severity and some kinds
- Escalation: up to three timed steps re-notify alerts nobody has acknowledged, through chosen channels and an optional extra email; an acknowledgement stops them
- Fix ntfy: titles with an em dash made every ntfy send fail (header not Latin-1); now RFC 2047 encoded

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-18 19:44:45 +02:00

948 lines
42 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { useSearchParams } from "react-router-dom";
import {
api,
type AppSettings,
type GotifySettings,
type NtfySettings,
type SmtpSettings,
type WebhookSettings,
type WebPushSettings,
type RoutingSettings,
type EscalationSettings,
type NotificationEvents,
type DigestSettings,
type QuietHoursSettings,
type HealthCheckSettings,
} from "../../api/client";
import { readableError } from "../../utils/errors";
import { ErrorNotice } from "../../components/Notice";
import { PageSkeleton } from "../../components/Skeleton";
import PushDevices from "../../components/PushDevices";
import RoutingEditor from "../../components/RoutingEditor";
const TIMEZONES = [
"UTC",
"Europe/Stockholm",
"Europe/London",
"Europe/Berlin",
"Europe/Paris",
"Europe/Oslo",
"Europe/Helsinki",
"Europe/Amsterdam",
"Europe/Copenhagen",
"America/New_York",
"America/Chicago",
"America/Denver",
"America/Los_Angeles",
"America/Toronto",
"America/Sao_Paulo",
"Asia/Tokyo",
"Asia/Shanghai",
"Asia/Singapore",
"Asia/Dubai",
"Australia/Sydney",
];
const DEFAULT_GOTIFY: GotifySettings = { enabled: false, url: "", token: "", priority: 5 };
const DEFAULT_NTFY: NtfySettings = { enabled: false, url: "https://ntfy.sh", topic: "", token: "", priority: 3 };
const DEFAULT_SMTP: SmtpSettings = { enabled: false, host: "", port: 587, secure: false, username: "", password: "", from: "", to: "" };
const DEFAULT_WEBHOOK: WebhookSettings = { enabled: false, url: "", secret: "" };
const DEFAULT_WEBPUSH: WebPushSettings = { enabled: false, contact: "" };
const DEFAULT_ROUTING: RoutingSettings = { rules: [] };
const DEFAULT_ESCALATION: EscalationSettings = { enabled: false, steps: [] };
const DEFAULT_NOTIFICATIONS: NotificationEvents = {
dnsAdd: true,
dnsUpdate: true,
dnsDelete: true,
secretCheck: true,
tailscaleKeyCheck: true,
dockerUpdateCheck: true,
proxmoxBackupCheck: true,
pbsVerificationCheck: true,
healthAlerts: true,
automationAlerts: true,
updateRunResults: true,
domainExpiryCheck: true,
secretCheckTime: "08:00",
timezone: "UTC",
integrationFailureAlerts: true,
integrationFailureThreshold: 3,
};
const DEFAULT_QUIET_HOURS: QuietHoursSettings = { enabled: false, start: "22:00", end: "07:00" };
const DEFAULT_DIGEST: DigestSettings = { enabled: false, day: 1, time: "08:00" };
// Monday first, as a week reads; the numbers are what the server keeps (0 = Sunday).
const DIGEST_DAYS: { value: number; label: string }[] = [
{ value: 1, label: "Monday" },
{ value: 2, label: "Tuesday" },
{ value: 3, label: "Wednesday" },
{ value: 4, label: "Thursday" },
{ value: 5, label: "Friday" },
{ value: 6, label: "Saturday" },
{ value: 0, label: "Sunday" },
];
const DEFAULT_HEALTH_CHECKS: HealthCheckSettings = { serverOfflineMinutes: 60, diskUsagePercent: 90, domainWarnDays: 30, diskForecastDays: 14, backupStaleHours: 48 };
type TestResult = { ok: boolean; message: string } | null;
type EventKey = { [K in keyof NotificationEvents]: NotificationEvents[K] extends boolean ? K : never }[keyof NotificationEvents];
const TABS = [
{ id: "channels", label: "Channels" },
{ id: "events", label: "What to send" },
{ id: "routing", label: "Who hears what" },
{ id: "when", label: "When" },
] as const;
type TabId = (typeof TABS)[number]["id"];
function TestBadge({ result }: { result: TestResult }) {
if (!result) return null;
return (
<div className={`alert ${result.ok ? "alert-success" : "alert-danger"} mb-0 mt-2 py-2`}>
{result.ok ? "✓" : "✕"} {result.message}
</div>
);
}
/** The host of an address, for a channel's one-line summary — never the whole address, which can carry a token. */
function hostOf(address: string): string {
try {
return new URL(address).host;
} catch {
return address;
}
}
/** One channel in the list: its name, whether it is on and filled in, and (opened) its settings. */
function ChannelRow({
name,
description,
enabled,
onToggle,
summary,
complete,
open,
onOpen,
children,
}: {
name: string;
description: ReactNode;
enabled: boolean;
onToggle: (on: boolean) => void;
/** What it is set to send to, once filled in ("elsa.lab", "my-topic"). */
summary: string;
complete: boolean;
open: boolean;
onOpen: () => void;
children: ReactNode;
}) {
const panelId = `channel-${name.replace(/\W+/g, "-").toLowerCase()}`;
return (
<div className="card mb-2">
<div className="card-body py-3">
<div className="d-flex align-items-center gap-3">
<label className="form-check form-switch mb-0">
<input type="checkbox" className="form-check-input" checked={enabled} onChange={(e) => onToggle(e.target.checked)} />
<span className="visually-hidden">Send notifications through {name}</span>
</label>
<div className="flex-fill" style={{ minWidth: 0 }}>
<div className="fw-bold">
{name}{" "}
{enabled && complete && <span className="badge bg-green-lt text-green">On</span>}
{enabled && !complete && <span className="badge bg-yellow-lt text-yellow">On, but not filled in</span>}
{!enabled && complete && <span className="badge bg-secondary-lt text-secondary">Off</span>}
{!enabled && !complete && <span className="badge bg-secondary-lt text-secondary">Not set up</span>}
</div>
<div className="text-secondary small text-truncate">{complete && summary ? summary : description}</div>
</div>
<button type="button" className="btn btn-sm btn-outline-secondary" aria-expanded={open} aria-controls={panelId} onClick={onOpen}>
{open ? "Close" : complete ? "Edit" : "Set up"}
</button>
</div>
</div>
{open && (
<div id={panelId} className="card-body border-top">
{complete && summary && <p className="text-secondary">{description}</p>}
{children}
</div>
)}
</div>
);
}
function EventToggle({ label, checked, onChange }: { label: string; checked: boolean; onChange: (on: boolean) => void }) {
return (
<label className="form-check mb-2">
<input type="checkbox" className="form-check-input" checked={checked} onChange={(e) => onChange(e.target.checked)} />
<span className="form-check-label">{label}</span>
</label>
);
}
function NumberField({
label,
value,
min,
max,
unit,
hint,
disabled,
onChange,
}: {
label: string;
value: number;
min: number;
max: number;
unit: string;
hint?: ReactNode;
disabled?: boolean;
onChange: (value: number) => void;
}) {
return (
<div className="mt-3">
<label className="form-label">{label}</label>
<div className="input-group">
<input type="number" className="form-control" min={min} max={max} value={value} disabled={disabled} onChange={(e) => onChange(Number(e.target.value))} />
<span className="input-group-text">{unit}</span>
</div>
{hint && <div className="form-hint">{hint}</div>}
</div>
);
}
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 tabRefs = useRef<Record<string, HTMLButtonElement | null>>({});
const [openChannel, setOpenChannel] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const [saved, setSaved] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
/** The settings as last loaded or saved, so what has been changed since can be told. */
const [baseline, setBaseline] = useState<string | null>(null);
const [gotify, setGotify] = useState<GotifySettings>(DEFAULT_GOTIFY);
const [ntfy, setNtfy] = useState<NtfySettings>(DEFAULT_NTFY);
const [smtp, setSmtp] = useState<SmtpSettings>(DEFAULT_SMTP);
const [webhook, setWebhook] = useState<WebhookSettings>(DEFAULT_WEBHOOK);
const [webPush, setWebPush] = useState<WebPushSettings>(DEFAULT_WEBPUSH);
// Whether push is on as saved: people can only add their browsers once the server knows it is on.
const [webPushSaved, setWebPushSaved] = useState(false);
const [routing, setRouting] = useState<RoutingSettings>(DEFAULT_ROUTING);
const [escalation, setEscalation] = useState<EscalationSettings>(DEFAULT_ESCALATION);
const [notifications, setNotifications] = useState<NotificationEvents>(DEFAULT_NOTIFICATIONS);
const [quietHours, setQuietHours] = useState<QuietHoursSettings>(DEFAULT_QUIET_HOURS);
const [healthChecks, setHealthChecks] = useState<HealthCheckSettings>(DEFAULT_HEALTH_CHECKS);
const [digest, setDigest] = useState<DigestSettings>(DEFAULT_DIGEST);
const [digestPreview, setDigestPreview] = useState<{ title: string; message: string } | null>(null);
const [digestBusy, setDigestBusy] = useState<"preview" | "send" | null>(null);
const [digestResult, setDigestResult] = useState<TestResult>(null);
const [queuedCount, setQueuedCount] = useState<number | null>(null);
const [flushing, setFlushing] = useState(false);
const [flushResult, setFlushResult] = useState<string | null>(null);
const [testingGotify, setTestingGotify] = useState(false);
const [testGotifyResult, setTestGotifyResult] = useState<TestResult>(null);
const [testingNtfy, setTestingNtfy] = useState(false);
const [testNtfyResult, setTestNtfyResult] = useState<TestResult>(null);
const [testingSmtp, setTestingSmtp] = useState(false);
const [testSmtpResult, setTestSmtpResult] = useState<TestResult>(null);
const [testingWebhook, setTestingWebhook] = useState(false);
const [testWebhookResult, setTestWebhookResult] = useState<TestResult>(null);
const snapshot = JSON.stringify({ gotify, ntfy, smtp, webhook, webPush, routing, escalation, notifications, quietHours, healthChecks, digest });
const dirty = baseline !== null && snapshot !== baseline;
useEffect(() => {
api.settings
.get()
.then((res: { settings: AppSettings }) => {
const s = res.settings;
setGotify(s.gotify);
setNtfy(s.ntfy);
setSmtp(s.smtp);
setWebhook(s.webhook);
const wp = s.webPush ?? DEFAULT_WEBPUSH;
setWebPush(wp);
setWebPushSaved(wp.enabled);
const rt = s.routing ?? DEFAULT_ROUTING;
const es = s.escalation ?? DEFAULT_ESCALATION;
setRouting(rt);
setEscalation(es);
setNotifications(s.notifications);
setQuietHours(s.quietHours);
setHealthChecks(s.healthChecks);
const d = s.digest ?? DEFAULT_DIGEST;
setDigest(d);
setBaseline(JSON.stringify({ gotify: s.gotify, ntfy: s.ntfy, smtp: s.smtp, webhook: s.webhook, webPush: wp, routing: rt, escalation: es, notifications: s.notifications, quietHours: s.quietHours, healthChecks: s.healthChecks, digest: d }));
})
.catch((err) => setLoadError(err instanceof Error ? err.message : String(err)))
.finally(() => setLoading(false));
api.settings
.quietHoursQueue()
.then((res) => setQueuedCount(res.count))
.catch(() => {});
}, []);
// The browser asks before the tab is closed or reloaded with changes that haven't been saved.
useEffect(() => {
if (!dirty) return;
const warn = (e: BeforeUnloadEvent) => {
e.preventDefault();
e.returnValue = "";
};
window.addEventListener("beforeunload", warn);
return () => window.removeEventListener("beforeunload", warn);
}, [dirty]);
function selectTab(id: TabId) {
setParams(
(prev) => {
const next = new URLSearchParams(prev);
if (id === "channels") next.delete("tab");
else next.set("tab", id);
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;
if (to === -1) return;
e.preventDefault();
selectTab(TABS[to].id);
tabRefs.current[TABS[to].id]?.focus();
}
async function handleSave() {
setSaving(true);
setSaveError(null);
setSaved(false);
try {
await api.settings.update({ gotify, ntfy, smtp, webhook, webPush, routing, escalation, notifications, quietHours, healthChecks, digest });
setBaseline(snapshot);
setWebPushSaved(webPush.enabled);
setSaved(true);
setTimeout(() => setSaved(false), 3000);
} catch (err) {
setSaveError(err instanceof Error ? err.message : String(err));
} finally {
setSaving(false);
}
}
async function handleDigestPreview() {
setDigestBusy("preview");
setDigestResult(null);
try {
const res = await api.settings.digestPreview();
setDigestPreview({ title: res.title, message: res.message });
} catch (err) {
setDigestResult({ ok: false, message: err instanceof Error ? err.message : String(err) });
} finally {
setDigestBusy(null);
}
}
async function handleDigestSend() {
setDigestBusy("send");
setDigestResult(null);
try {
const res = await api.settings.digestSend();
setDigestResult({ ok: true, message: `Sent through ${res.channels} channel${res.channels === 1 ? "" : "s"}.` });
} catch (err) {
setDigestResult({ ok: false, message: readableError(err) });
} finally {
setDigestBusy(null);
}
}
async function handleFlushNow() {
setFlushing(true);
setFlushResult(null);
try {
const res = await api.settings.flushQuietHours();
setFlushResult(res.flushed > 0 ? `Sent a digest of ${res.flushed} queued notification${res.flushed !== 1 ? "s" : ""}.` : "Nothing was queued.");
setQueuedCount(0);
} catch (err) {
setFlushResult(err instanceof Error ? err.message : String(err));
} finally {
setFlushing(false);
}
}
async function handleTestGotify() {
setTestingGotify(true);
setTestGotifyResult(null);
try {
await api.settings.testGotify(gotify);
setTestGotifyResult({ ok: true, message: "Notification sent successfully." });
} catch (err) {
setTestGotifyResult({ ok: false, message: err instanceof Error ? err.message : String(err) });
} finally {
setTestingGotify(false);
}
}
async function handleTestNtfy() {
setTestingNtfy(true);
setTestNtfyResult(null);
try {
await api.settings.testNtfy(ntfy);
setTestNtfyResult({ ok: true, message: "Notification sent successfully." });
} catch (err) {
setTestNtfyResult({ ok: false, message: err instanceof Error ? err.message : String(err) });
} finally {
setTestingNtfy(false);
}
}
async function handleTestSmtp() {
setTestingSmtp(true);
setTestSmtpResult(null);
try {
await api.settings.testSmtp(smtp);
setTestSmtpResult({ ok: true, message: "Test email sent successfully." });
} catch (err) {
setTestSmtpResult({ ok: false, message: err instanceof Error ? err.message : String(err) });
} finally {
setTestingSmtp(false);
}
}
async function handleTestWebhook() {
setTestingWebhook(true);
setTestWebhookResult(null);
try {
await api.settings.testWebhook(webhook);
setTestWebhookResult({ ok: true, message: "Webhook delivered successfully." });
} catch (err) {
setTestWebhookResult({ ok: false, message: err instanceof Error ? err.message : String(err) });
} finally {
setTestingWebhook(false);
}
}
if (loading) return <PageSkeleton />;
const gotifyComplete = !!(gotify.url && gotify.token);
const ntfyComplete = !!(ntfy.url && ntfy.topic);
const smtpComplete = !!(smtp.host && smtp.from && smtp.to);
const webhookComplete = !!webhook.url;
const channelsOn = [gotify.enabled && gotifyComplete, ntfy.enabled && ntfyComplete, smtp.enabled && smtpComplete, webhook.enabled && webhookComplete, webPush.enabled].filter(Boolean).length;
const toggle = (key: EventKey, label: string) => <EventToggle key={key} label={label} checked={notifications[key]} onChange={(on) => setNotifications((n) => ({ ...n, [key]: on }))} />;
const dailyChecksEnabled = notifications.secretCheck || notifications.tailscaleKeyCheck || notifications.dockerUpdateCheck || notifications.proxmoxBackupCheck || notifications.pbsVerificationCheck || notifications.domainExpiryCheck;
return (
<>
<div className="settings-savebar">
<div className="d-flex flex-wrap align-items-center justify-content-between gap-2">
<h3 className="mb-0">Notifications</h3>
<div className="d-flex align-items-center gap-2">
{saveError && <span className="text-danger small">{saveError}</span>}
{saved && <span className="text-success small">✓ Settings saved</span>}
{dirty && !saved && <span className="badge bg-yellow-lt text-yellow">Unsaved changes</span>}
<button className="btn btn-primary" onClick={handleSave} disabled={saving || !dirty}>
{saving ? "Saving…" : "Save Settings"}
</button>
</div>
</div>
<ul className="nav nav-tabs mt-3" role="tablist" aria-label="Notification settings">
{TABS.map((t) => (
<li className="nav-item" role="presentation" key={t.id}>
<button
type="button"
role="tab"
id={`tab-${t.id}`}
ref={(el) => {
tabRefs.current[t.id] = el;
}}
className={`nav-link ${tab === t.id ? "active" : ""}`}
aria-selected={tab === t.id}
aria-controls={`panel-${t.id}`}
tabIndex={tab === t.id ? 0 : -1}
onClick={() => selectTab(t.id)}
onKeyDown={onTabKey}
>
{t.label}
{t.id === "channels" && (
<span className={`badge ms-2 ${channelsOn > 0 ? "bg-green-lt text-green" : "bg-yellow-lt text-yellow"}`}>
{channelsOn} on
</span>
)}
</button>
</li>
))}
</ul>
</div>
<ErrorNotice error={loadError} />
{/* ── Channels ── */}
<div role="tabpanel" id="panel-channels" aria-labelledby="tab-channels" hidden={tab !== "channels"} className="pt-3">
<p className="text-secondary">Every notification goes to each channel that is on. Open one to fill it in and send a test.</p>
{channelsOn === 0 && <div className="alert alert-warning">No channel is on, so nothing is sent anywhere yet. Set one up below.</div>}
<ChannelRow
name="Gotify"
description="Send push notifications to a self-hosted Gotify instance."
enabled={gotify.enabled}
onToggle={(on) => setGotify((g) => ({ ...g, enabled: on }))}
complete={gotifyComplete}
summary={hostOf(gotify.url)}
open={openChannel === "gotify"}
onOpen={() => setOpenChannel(openChannel === "gotify" ? null : "gotify")}
>
<div className="mb-2">
<label className="form-label">Gotify URL</label>
<input className="form-control" placeholder="http://gotify.example.com" value={gotify.url} onChange={(e) => setGotify((g) => ({ ...g, url: e.target.value }))} />
</div>
<div className="mb-2">
<label className="form-label">App token</label>
<input type="password" className="form-control" placeholder="Your Gotify app token" value={gotify.token} onChange={(e) => setGotify((g) => ({ ...g, token: e.target.value }))} />
</div>
<div className="mb-2">
<label className="form-label">Priority (1–10)</label>
<input type="number" min={1} max={10} className="form-control" value={gotify.priority} onChange={(e) => setGotify((g) => ({ ...g, priority: Number(e.target.value) }))} />
</div>
<button className="btn btn-outline-secondary" onClick={handleTestGotify} disabled={testingGotify || !gotify.url || !gotify.token}>
{testingGotify ? "Sending…" : "Send test"}
</button>
<TestBadge result={testGotifyResult} />
</ChannelRow>
<ChannelRow
name="ntfy"
description={
<>
Send notifications via{" "}
<a href="https://ntfy.sh" target="_blank" rel="noreferrer">
ntfy.sh
</a>{" "}
or a self-hosted instance.
</>
}
enabled={ntfy.enabled}
onToggle={(on) => setNtfy((n) => ({ ...n, enabled: on }))}
complete={ntfyComplete}
summary={`${hostOf(ntfy.url)} · topic ${ntfy.topic}`}
open={openChannel === "ntfy"}
onOpen={() => setOpenChannel(openChannel === "ntfy" ? null : "ntfy")}
>
<div className="row g-2 mb-2">
<div className="col-8">
<label className="form-label">Server URL</label>
<input className="form-control" placeholder="https://ntfy.sh" value={ntfy.url} onChange={(e) => setNtfy((n) => ({ ...n, url: e.target.value }))} />
</div>
<div className="col-4">
<label className="form-label">Priority (1–5)</label>
<input type="number" min={1} max={5} className="form-control" value={ntfy.priority} onChange={(e) => setNtfy((n) => ({ ...n, priority: Number(e.target.value) }))} />
</div>
</div>
<div className="mb-2">
<label className="form-label">Topic</label>
<input className="form-control" placeholder="your-topic" value={ntfy.topic} onChange={(e) => setNtfy((n) => ({ ...n, topic: e.target.value }))} />
</div>
<div className="mb-2">
<label className="form-label">Access token (optional, for protected topics)</label>
<input type="password" className="form-control" value={ntfy.token} onChange={(e) => setNtfy((n) => ({ ...n, token: e.target.value }))} />
</div>
<button className="btn btn-outline-secondary" onClick={handleTestNtfy} disabled={testingNtfy || !ntfy.url || !ntfy.topic}>
{testingNtfy ? "Sending…" : "Send test"}
</button>
<TestBadge result={testNtfyResult} />
</ChannelRow>
<ChannelRow
name="Email (SMTP)"
description="Send notifications via email using any SMTP server."
enabled={smtp.enabled}
onToggle={(on) => setSmtp((s) => ({ ...s, enabled: on }))}
complete={smtpComplete}
summary={`${smtp.host} → ${smtp.to}`}
open={openChannel === "smtp"}
onOpen={() => setOpenChannel(openChannel === "smtp" ? null : "smtp")}
>
<div className="row g-2 mb-2">
<div className="col-8">
<label className="form-label">SMTP host</label>
<input className="form-control" placeholder="smtp.example.com" value={smtp.host} onChange={(e) => setSmtp((s) => ({ ...s, host: e.target.value }))} />
</div>
<div className="col-4">
<label className="form-label">Port</label>
<input type="number" className="form-control" placeholder="587" value={smtp.port} onChange={(e) => setSmtp((s) => ({ ...s, port: Number(e.target.value) }))} />
</div>
</div>
<label className="form-check mb-3">
<input type="checkbox" className="form-check-input" checked={smtp.secure} onChange={(e) => setSmtp((s) => ({ ...s, secure: e.target.checked }))} />
<span className="form-check-label">Use TLS/SSL (port 465)</span>
</label>
<div className="row g-2 mb-2">
<div className="col-6">
<label className="form-label">Username (optional)</label>
<input className="form-control" value={smtp.username} onChange={(e) => setSmtp((s) => ({ ...s, username: e.target.value }))} />
</div>
<div className="col-6">
<label className="form-label">Password (optional)</label>
<input type="password" className="form-control" value={smtp.password} onChange={(e) => setSmtp((s) => ({ ...s, password: e.target.value }))} />
</div>
</div>
<div className="row g-2 mb-3">
<div className="col-6">
<label className="form-label">From</label>
<input type="email" className="form-control" placeholder="homelab@example.com" value={smtp.from} onChange={(e) => setSmtp((s) => ({ ...s, from: e.target.value }))} />
</div>
<div className="col-6">
<label className="form-label">To</label>
<input type="email" className="form-control" placeholder="you@example.com" value={smtp.to} onChange={(e) => setSmtp((s) => ({ ...s, to: e.target.value }))} />
</div>
</div>
<button className="btn btn-outline-secondary" onClick={handleTestSmtp} disabled={testingSmtp || !smtp.host || !smtp.from || !smtp.to}>
{testingSmtp ? "Sending…" : "Send test"}
</button>
<TestBadge result={testSmtpResult} />
</ChannelRow>
<ChannelRow
name="Webhook"
description={
<>
POST a JSON payload to any HTTP endpoint. Uses Discord/Slack-compatible <code>{'{ "content": "…" }'}</code> format.
</>
}
enabled={webhook.enabled}
onToggle={(on) => setWebhook((w) => ({ ...w, enabled: on }))}
complete={webhookComplete}
summary={hostOf(webhook.url)}
open={openChannel === "webhook"}
onOpen={() => setOpenChannel(openChannel === "webhook" ? null : "webhook")}
>
<div className="mb-2">
<label className="form-label">Webhook URL</label>
<input type="url" className="form-control" placeholder="https://discord.com/api/webhooks/…" value={webhook.url} onChange={(e) => setWebhook((w) => ({ ...w, url: e.target.value }))} />
</div>
<div className="mb-3">
<label className="form-label">Secret (optional, sent as X-Webhook-Secret header)</label>
<input type="password" className="form-control" value={webhook.secret} onChange={(e) => setWebhook((w) => ({ ...w, secret: e.target.value }))} />
</div>
<button className="btn btn-outline-secondary" onClick={handleTestWebhook} disabled={testingWebhook || !webhook.url}>
{testingWebhook ? "Sending…" : "Send test"}
</button>
<TestBadge result={testWebhookResult} />
</ChannelRow>
<ChannelRow
name="Phone and browser"
description={<>Push notifications to a phone or browser that asks for them, with no app or account. They need this page to be opened over https.</>}
enabled={webPush.enabled}
onToggle={(on) => setWebPush((w) => ({ ...w, enabled: on }))}
complete
summary="Web push"
open={openChannel === "webpush"}
onOpen={() => setOpenChannel(openChannel === "webpush" ? null : "webpush")}
>
<div className="mb-3">
<label className="form-label">Contact (optional)</label>
<input
className="form-control"
maxLength={200}
placeholder="you@example.com"
value={webPush.contact}
onChange={(e) => setWebPush((w) => ({ ...w, contact: e.target.value }))}
/>
<div className="form-hint text-secondary small">Given to the browsers&rsquo; push services (Google, Mozilla, Apple) so they can reach you if this misbehaves. An email address or an https address.</div>
</div>
<PushDevices serverEnabled={webPushSaved} />
</ChannelRow>
</div>
{/* ── 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>
<div className="row row-cards">
<div className="col-md-6">
<div className="card h-100">
<div className="card-header">
<h3 className="card-title">Servers and disks</h3>
</div>
<div className="card-body">
{toggle("healthAlerts", "Server offline, disk nearly full, or Synology volume/disk problem")}
<NumberField
label="Server offline after"
value={healthChecks.serverOfflineMinutes}
min={15}
max={10080}
unit="min"
hint="Agents report every 15 min by default."
disabled={!notifications.healthAlerts}
onChange={(v) => setHealthChecks((h) => ({ ...h, serverOfflineMinutes: v }))}
/>
<NumberField
label="Disk usage alert at"
value={healthChecks.diskUsagePercent}
min={50}
max={99}
unit="%"
hint="Servers, Proxmox storage, Synology volumes. Checked every 15 min; a recovery notice follows."
disabled={!notifications.healthAlerts}
onChange={(v) => setHealthChecks((h) => ({ ...h, diskUsagePercent: v }))}
/>
<NumberField
label="Warn when a disk will fill within"
value={healthChecks.diskForecastDays}
min={0}
max={90}
unit="days"
hint="From each agent server's own history, shown on the Alerts page and dashboard (not sent as a notification). Needs a few days of steady growth to say anything. 0 turns it off."
onChange={(v) => setHealthChecks((h) => ({ ...h, diskForecastDays: v }))}
/>
</div>
</div>
</div>
<div className="col-md-6">
<div className="card h-100">
<div className="card-header">
<h3 className="card-title">Secrets, keys and domains</h3>
</div>
<div className="card-body">
{toggle("secretCheck", "Secret expiry reminder")}
{toggle("tailscaleKeyCheck", "Tailscale key expiry reminder")}
{toggle("domainExpiryCheck", "Domain registration expiring or expired (daily reminder)")}
<NumberField
label="Domain expiry warning"
value={healthChecks.domainWarnDays}
min={1}
max={365}
unit="days before"
hint="Reminded daily from then until it's renewed."
disabled={!notifications.domainExpiryCheck}
onChange={(v) => setHealthChecks((h) => ({ ...h, domainWarnDays: v }))}
/>
</div>
</div>
</div>
<div className="col-md-6">
<div className="card h-100">
<div className="card-header">
<h3 className="card-title">Backups and updates</h3>
</div>
<div className="card-body">
{toggle("proxmoxBackupCheck", "Proxmox backup failed, a guest has no coverage, or its newest backup is too old")}
<NumberField
label="A guest's backup is too old after"
value={healthChecks.backupStaleHours}
min={0}
max={2160}
unit="hours"
hint="Shown on the Alerts page for every guest whose newest backup (on Proxmox or a Backup Server) is older than this, and sent once a day with the other backup messages. A server can have its own limit. 0 turns it off."
onChange={(v) => setHealthChecks((h) => ({ ...h, backupStaleHours: v }))}
/>
{toggle("pbsVerificationCheck", "Proxmox Backup Server snapshot failed verification")}
{toggle("dockerUpdateCheck", "Docker image update available")}
</div>
</div>
</div>
<div className="col-md-6">
<div className="card h-100">
<div className="card-header">
<h3 className="card-title">Integrations and automation</h3>
</div>
<div className="card-body">
{toggle("integrationFailureAlerts", "Integration/DNS provider failing repeatedly")}
<NumberField
label="Alert after"
value={notifications.integrationFailureThreshold}
min={1}
max={20}
unit="consecutive failures"
hint="Based on the Diagnostic Log. A recovery notice is sent once it succeeds again."
disabled={!notifications.integrationFailureAlerts}
onChange={(v) => setNotifications((n) => ({ ...n, integrationFailureThreshold: v }))}
/>
<div className="mt-3">{toggle("automationAlerts", "Semaphore template or Gitea workflow run failed")}</div>
<div className="mt-3">{toggle("updateRunResults", "An update run you started finished, or didn't")}</div>
</div>
</div>
</div>
<div className="col-md-6">
<div className="card h-100">
<div className="card-header">
<h3 className="card-title">DNS changes</h3>
</div>
<div className="card-body">
{toggle("dnsAdd", "DNS record added")}
{toggle("dnsUpdate", "DNS record updated")}
{toggle("dnsDelete", "DNS record deleted")}
</div>
</div>
</div>
</div>
</div>
{/* ── Who hears what ── */}
<div role="tabpanel" id="panel-routing" aria-labelledby="tab-routing" hidden={tab !== "routing"} className="pt-3">
<RoutingEditor
routing={routing}
onRouting={setRouting}
escalation={escalation}
onEscalation={setEscalation}
channelsOn={{ gotify: gotify.enabled && gotifyComplete, ntfy: ntfy.enabled && ntfyComplete, smtp: smtp.enabled && smtpComplete, webhook: webhook.enabled && webhookComplete, webPush: webPush.enabled }}
/>
</div>
{/* ── When ── */}
<div role="tabpanel" id="panel-when" aria-labelledby="tab-when" hidden={tab !== "when"} className="pt-3">
<p className="text-secondary">When notifications are sent: the time zone everything here runs in, the daily reminders, hours to keep quiet, and the weekly digest.</p>
<div className="row row-cards">
<div className="col-md-6">
<div className="card h-100">
<div className="card-header">
<h3 className="card-title">Time zone and daily reminders</h3>
</div>
<div className="card-body">
<div className="mb-3">
<label className="form-label" htmlFor="notify-tz">
Time zone
</label>
<select id="notify-tz" className="form-select" value={notifications.timezone} onChange={(e) => setNotifications((n) => ({ ...n, timezone: e.target.value }))}>
{TIMEZONES.map((tz) => (
<option key={tz} value={tz}>
{tz}
</option>
))}
</select>
<div className="form-hint">Used for the daily reminders, quiet hours and the weekly digest below.</div>
</div>
<div>
<label className="form-label" htmlFor="notify-daily">
Daily reminder time
</label>
<input
id="notify-daily"
type="time"
className="form-control"
value={notifications.secretCheckTime}
disabled={!dailyChecksEnabled}
onChange={(e) => setNotifications((n) => ({ ...n, secretCheckTime: e.target.value }))}
/>
<div className="form-hint">
Shared by the secret, Tailscale key, Docker update, Proxmox backup, Proxmox Backup Server, and domain expiry reminders (switched on under What to send).
</div>
</div>
</div>
</div>
</div>
<div className="col-md-6">
<div className="card h-100">
<div className="card-header">
<h3 className="card-title">Quiet hours</h3>
</div>
<div className="card-body">
<p className="text-secondary">
Notifications that fire during this window are held instead of sent immediately, then delivered as one digest at the end time (in the time zone
set here). Scheduled daily reminders already only fire once at a time you pick, so this mainly affects instant ones — DNS changes and integration
failure/recovery alerts.
</p>
<label className="form-check mb-3">
<input type="checkbox" className="form-check-input" checked={quietHours.enabled} onChange={(e) => setQuietHours((q) => ({ ...q, enabled: e.target.checked }))} />
<span className="form-check-label">Enable quiet hours</span>
</label>
<div className="row g-2 mb-2">
<div className="col-6">
<label className="form-label">Start</label>
<input type="time" className="form-control" value={quietHours.start} disabled={!quietHours.enabled} onChange={(e) => setQuietHours((q) => ({ ...q, start: e.target.value }))} />
</div>
<div className="col-6">
<label className="form-label">End</label>
<input type="time" className="form-control" value={quietHours.end} disabled={!quietHours.enabled} onChange={(e) => setQuietHours((q) => ({ ...q, end: e.target.value }))} />
</div>
</div>
<div className="form-hint mb-3">A start time later than the end time (e.g. 22:00 → 07:00) is treated as spanning midnight.</div>
{queuedCount !== null && queuedCount > 0 && (
<div className="alert alert-info d-flex align-items-center justify-content-between mb-0">
<span>
{queuedCount} notification{queuedCount !== 1 ? "s" : ""} currently queued.
</span>
<button className="btn btn-sm btn-outline-secondary" onClick={handleFlushNow} disabled={flushing}>
{flushing ? "Sending…" : "Flush now"}
</button>
</div>
)}
{flushResult && <div className="text-secondary small mt-2">{flushResult}</div>}
</div>
</div>
</div>
<div className="col-12">
<div className="card">
<div className="card-header">
<h3 className="card-title">Weekly digest</h3>
</div>
<div className="card-body">
<p className="text-secondary">
One message a week through the channels that are on, in the time zone set here: what is wrong now, what was down and for how long, what happened,
disks heading for full, things about to expire, updates waiting and maintenance coming up. A topic with nothing to say is left out, and a quiet week
says so in one line. Quiet hours hold it like any other notification.
</p>
<label className="form-check mb-3">
<input type="checkbox" className="form-check-input" checked={digest.enabled} onChange={(e) => setDigest((d) => ({ ...d, enabled: e.target.checked }))} />
<span className="form-check-label">Send the weekly digest</span>
</label>
<div className="row g-2 mb-3" style={{ maxWidth: 420 }}>
<div className="col-6">
<label className="form-label" htmlFor="digest-day">
Day
</label>
<select id="digest-day" className="form-select" value={digest.day} disabled={!digest.enabled} onChange={(e) => setDigest((d) => ({ ...d, day: Number(e.target.value) }))}>
{DIGEST_DAYS.map((d) => (
<option key={d.value} value={d.value}>
{d.label}
</option>
))}
</select>
</div>
<div className="col-6">
<label className="form-label" htmlFor="digest-time">
Time
</label>
<input id="digest-time" type="time" className="form-control" value={digest.time} disabled={!digest.enabled} onChange={(e) => setDigest((d) => ({ ...d, time: e.target.value }))} />
</div>
</div>
<div className="btn-list">
<button type="button" className="btn btn-outline-secondary" onClick={handleDigestPreview} disabled={digestBusy !== null}>
{digestBusy === "preview" ? "Gathering…" : "Preview"}
</button>
<button type="button" className="btn btn-outline-secondary" onClick={handleDigestSend} disabled={digestBusy !== null}>
{digestBusy === "send" ? "Sending…" : "Send it now"}
</button>
</div>
<div className="form-hint mt-2">The day and time are saved with the Save button; the preview and "send it now" don't depend on them.</div>
<TestBadge result={digestResult} />
{digestPreview && (
<div className="mt-3">
<div className="fw-bold">{digestPreview.title}</div>
<pre className="border rounded p-2 mt-1 mb-0" style={{ whiteSpace: "pre-wrap", fontSize: "0.8125rem" }}>
{digestPreview.message}
</pre>
</div>
)}
</div>
</div>
</div>
</div>
</div>
</>
);
}