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 (
{result.ok ? "✓" : "✕"} {result.message}
);
}
/** 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 (
{open && (
{complete && summary &&
{description}
}
{children}
)}
);
}
function EventToggle({ label, checked, onChange }: { label: string; checked: boolean; onChange: (on: boolean) => void }) {
return (
onChange(e.target.checked)} />
{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 (
{label}
onChange(Number(e.target.value))} />
{unit}
{hint &&
{hint}
}
);
}
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>({});
const [openChannel, setOpenChannel] = useState(null);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState(null);
const [saving, setSaving] = useState(false);
const [saved, setSaved] = useState(false);
const [saveError, setSaveError] = useState(null);
/** The settings as last loaded or saved, so what has been changed since can be told. */
const [baseline, setBaseline] = useState(null);
const [gotify, setGotify] = useState(DEFAULT_GOTIFY);
const [ntfy, setNtfy] = useState(DEFAULT_NTFY);
const [smtp, setSmtp] = useState(DEFAULT_SMTP);
const [webhook, setWebhook] = useState(DEFAULT_WEBHOOK);
const [webPush, setWebPush] = useState(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(DEFAULT_ROUTING);
const [escalation, setEscalation] = useState(DEFAULT_ESCALATION);
const [notifications, setNotifications] = useState(DEFAULT_NOTIFICATIONS);
const [quietHours, setQuietHours] = useState(DEFAULT_QUIET_HOURS);
const [healthChecks, setHealthChecks] = useState(DEFAULT_HEALTH_CHECKS);
const [digest, setDigest] = useState(DEFAULT_DIGEST);
const [digestPreview, setDigestPreview] = useState<{ title: string; message: string } | null>(null);
const [digestBusy, setDigestBusy] = useState<"preview" | "send" | null>(null);
const [digestResult, setDigestResult] = useState(null);
const [queuedCount, setQueuedCount] = useState(null);
const [flushing, setFlushing] = useState(false);
const [flushResult, setFlushResult] = useState(null);
const [testingGotify, setTestingGotify] = useState(false);
const [testGotifyResult, setTestGotifyResult] = useState(null);
const [testingNtfy, setTestingNtfy] = useState(false);
const [testNtfyResult, setTestNtfyResult] = useState(null);
const [testingSmtp, setTestingSmtp] = useState(false);
const [testSmtpResult, setTestSmtpResult] = useState(null);
const [testingWebhook, setTestingWebhook] = useState(false);
const [testWebhookResult, setTestWebhookResult] = useState(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) {
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 ;
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) => setNotifications((n) => ({ ...n, [key]: on }))} />;
const dailyChecksEnabled = notifications.secretCheck || notifications.tailscaleKeyCheck || notifications.dockerUpdateCheck || notifications.proxmoxBackupCheck || notifications.pbsVerificationCheck || notifications.domainExpiryCheck;
return (
<>
Notifications
{saveError && {saveError} }
{saved && ✓ Settings saved }
{dirty && !saved && Unsaved changes }
{saving ? "Saving…" : "Save Settings"}
{TABS.map((t) => (
{
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" && (
0 ? "bg-green-lt text-green" : "bg-yellow-lt text-yellow"}`}>
{channelsOn} on
)}
))}
{/* ── Channels ── */}
Every notification goes to each channel that is on. Open one to fill it in and send a test.
{channelsOn === 0 &&
No channel is on, so nothing is sent anywhere yet. Set one up below.
}
setGotify((g) => ({ ...g, enabled: on }))}
complete={gotifyComplete}
summary={hostOf(gotify.url)}
open={openChannel === "gotify"}
onOpen={() => setOpenChannel(openChannel === "gotify" ? null : "gotify")}
>
Gotify URL
setGotify((g) => ({ ...g, url: e.target.value }))} />
App token
setGotify((g) => ({ ...g, token: e.target.value }))} />
Priority (1–10)
setGotify((g) => ({ ...g, priority: Number(e.target.value) }))} />
{testingGotify ? "Sending…" : "Send test"}
Send notifications via{" "}
ntfy.sh
{" "}
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")}
>
Topic
setNtfy((n) => ({ ...n, topic: e.target.value }))} />
Access token (optional, for protected topics)
setNtfy((n) => ({ ...n, token: e.target.value }))} />
{testingNtfy ? "Sending…" : "Send test"}
setSmtp((s) => ({ ...s, enabled: on }))}
complete={smtpComplete}
summary={`${smtp.host} → ${smtp.to}`}
open={openChannel === "smtp"}
onOpen={() => setOpenChannel(openChannel === "smtp" ? null : "smtp")}
>
setSmtp((s) => ({ ...s, secure: e.target.checked }))} />
Use TLS/SSL (port 465)
{testingSmtp ? "Sending…" : "Send test"}
POST a JSON payload to any HTTP endpoint. Uses Discord/Slack-compatible {'{ "content": "…" }'} 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")}
>
Webhook URL
setWebhook((w) => ({ ...w, url: e.target.value }))} />
Secret (optional, sent as X-Webhook-Secret header)
setWebhook((w) => ({ ...w, secret: e.target.value }))} />
{testingWebhook ? "Sending…" : "Send test"}
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")}
>
{/* ── What to send ── */}
Which events send a notification, on every channel that is on. Each group keeps its thresholds beside the switch they belong to.
Servers and disks
{toggle("healthAlerts", "Server offline, disk nearly full, or Synology volume/disk problem")}
setHealthChecks((h) => ({ ...h, serverOfflineMinutes: v }))}
/>
setHealthChecks((h) => ({ ...h, diskUsagePercent: v }))}
/>
setHealthChecks((h) => ({ ...h, diskForecastDays: v }))}
/>
Secrets, keys and domains
{toggle("secretCheck", "Secret expiry reminder")}
{toggle("tailscaleKeyCheck", "Tailscale key expiry reminder")}
{toggle("domainExpiryCheck", "Domain registration expiring or expired (daily reminder)")}
setHealthChecks((h) => ({ ...h, domainWarnDays: v }))}
/>
Backups and updates
{toggle("proxmoxBackupCheck", "Proxmox backup failed, a guest has no coverage, or its newest backup is too old")}
setHealthChecks((h) => ({ ...h, backupStaleHours: v }))}
/>
{toggle("pbsVerificationCheck", "Proxmox Backup Server snapshot failed verification")}
{toggle("dockerUpdateCheck", "Docker image update available")}
Integrations and automation
{toggle("integrationFailureAlerts", "Integration/DNS provider failing repeatedly")}
setNotifications((n) => ({ ...n, integrationFailureThreshold: v }))}
/>
{toggle("automationAlerts", "Semaphore template or Gitea workflow run failed")}
{toggle("updateRunResults", "An update run you started finished, or didn't")}
DNS changes
{toggle("dnsAdd", "DNS record added")}
{toggle("dnsUpdate", "DNS record updated")}
{toggle("dnsDelete", "DNS record deleted")}
{/* ── Who hears what ── */}
{/* ── When ── */}
When notifications are sent: the time zone everything here runs in, the daily reminders, hours to keep quiet, and the weekly digest.
Time zone and daily reminders
Time zone
setNotifications((n) => ({ ...n, timezone: e.target.value }))}>
{TIMEZONES.map((tz) => (
{tz}
))}
Used for the daily reminders, quiet hours and the weekly digest below.
Quiet hours
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.
setQuietHours((q) => ({ ...q, enabled: e.target.checked }))} />
Enable quiet hours
A start time later than the end time (e.g. 22:00 → 07:00) is treated as spanning midnight.
{queuedCount !== null && queuedCount > 0 && (
{queuedCount} notification{queuedCount !== 1 ? "s" : ""} currently queued.
{flushing ? "Sending…" : "Flush now"}
)}
{flushResult &&
{flushResult}
}
Weekly digest
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.
setDigest((d) => ({ ...d, enabled: e.target.checked }))} />
Send the weekly digest
{digestBusy === "preview" ? "Gathering…" : "Preview"}
{digestBusy === "send" ? "Sending…" : "Send it now"}
The day and time are saved with the Save button; the preview and "send it now" don't depend on them.
{digestPreview && (
{digestPreview.title}
{digestPreview.message}
)}
>
);
}