import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query" import { createFileRoute } from "@tanstack/react-router" import { Bell, BellOff, Plus, Send, Trash2 } from "lucide-react" import { useState } from "react" import { type AlertsConfig, AlertsService, type Channel } from "@/client" import { InfoTip } from "@/components/Flow/SidePanel" import { Button } from "@/components/ui/button" import { Checkbox } from "@/components/ui/checkbox" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select" import { Switch } from "@/components/ui/switch" import useCustomToast from "@/hooks/useCustomToast" import * as webpush from "@/lib/webpush" import { handleError } from "@/utils" export const Route = createFileRoute("/_layout/alerts")({ component: Alerts, head: () => ({ meta: [ { title: "Alerts - Fluksio", }, ], }), }) const alertsKey = ["alerts", "config"] const SECTION = "text-xs font-medium uppercase tracking-[0.5px] text-muted-foreground" /** What the engine can alert on. Mirrors `ALERTING_EVENTS` in the backend, and * `backend/tests/flow/test_alerts.py` reads this list to fail when the two * drift apart. A rule with none of them ticked still covers everything, * including any event added there later. */ const EVENTS: [string, string][] = [ ["node_error", "A node failed"], ["node_health", "A connection dropped"], ["flow_quarantined", "A flow was quarantined"], ["task_crashed", "A background task crashed"], ["engine_degraded", "The engine is struggling"], ["cascade_dropped", "Work was given up on"], ["queue_unavailable", "The queue is unreachable"], ["run_finished", "A run failed"], ] /** The settings each kind of channel needs, in the order they read best. */ const FIELDS: Record = { ntfy: [ ["server", "Server", "https://ntfy.sh"], ["topic", "Topic", "your-topic"], ["token", "Token", "only for a protected topic"], ], smtp: [["to", "Send to", "someone@example.com"]], webhook: [["url", "URL", "https://example.com/hook"]], // The message has to be one a flow declares, like anything a dashboard // writes to. A notification widget bound to it is what shows the alert. dashboard: [["message", "Message", "house.notice"]], // Nothing to configure: it goes to whichever browsers subscribed here, which // is a button rather than a setting. webpush: [], } const KINDS: Channel["kind"][] = [ "ntfy", "smtp", "webhook", "dashboard", "webpush", ] /** A setting may hold a `{"$secret": "name"}` reference rather than a literal, * so text that parses as JSON is stored as JSON and survives a round trip. */ function parseSetting(text: string): unknown { if (text.startsWith("{")) { try { return JSON.parse(text) } catch { return text } } return text } function showSetting(value: unknown): string { if (value === undefined || value === null) return "" return typeof value === "string" ? value : JSON.stringify(value) } /** * The one channel whose setting is on the device rather than in the config: * a browser has to ask its own permission, and what it hands back is stored * against this instance. */ function ThisBrowser() { const { showSuccessToast, showErrorToast } = useCustomToast() const { data: subscribed, refetch } = useQuery({ queryKey: ["alerts", "webpush", "this-browser"], queryFn: async () => (await webpush.current()) !== null, enabled: webpush.supported(), }) const change = useMutation({ mutationFn: async (wanted: boolean) => wanted ? webpush.subscribe() : webpush.unsubscribe(), onSuccess: (_result, wanted) => { showSuccessToast( wanted ? "This browser will be notified" : "This browser will no longer be notified", ) refetch() }, onError: (error: Error) => showErrorToast(error.message), }) if (!webpush.supported()) { return (

This browser cannot receive notifications. They need HTTPS — over plain http on a local address, no browser will allow them.

) } return (
{subscribed ? "This browser is subscribed." : "This browser is not subscribed yet. Each device subscribes itself."}
) } function Alerts() { const { data } = useQuery({ queryKey: alertsKey, queryFn: () => AlertsService.readAlertsConfig(), }) return (

Alerts

Where the engine goes when something breaks.

{data ? : null}
) } function AlertsForm({ initial }: { initial: AlertsConfig }) { const queryClient = useQueryClient() const { showSuccessToast, showErrorToast } = useCustomToast() const [draft, setDraft] = useState(initial) const [saved, setSaved] = useState(initial) const save = useMutation({ mutationFn: (config: AlertsConfig) => AlertsService.saveAlertsConfig({ requestBody: config }), onSuccess: (config) => { showSuccessToast("Alerting updated") setDraft(config) setSaved(config) queryClient.invalidateQueries({ queryKey: alertsKey }) }, onError: handleError.bind(showErrorToast), }) const test = useMutation({ mutationFn: (channelName: string) => AlertsService.testChannel({ channelName }), onSuccess: (message) => showSuccessToast(message.message), onError: handleError.bind(showErrorToast), }) const channels = draft.channels ?? [] const rules = draft.rules ?? [] const dirty = JSON.stringify(draft) !== JSON.stringify(saved) const patchChannel = (index: number, patch: Partial) => setDraft({ ...draft, channels: channels.map((channel, i) => i === index ? { ...channel, ...patch } : channel, ), }) return ( <>
Alerting {draft.enabled ? "Failures reach the channels below." : "Switched off — failures only reach the log."}
setDraft({ ...draft, enabled })} />

Channels

Somewhere to send to. A setting can hold{" "} {`{"$secret": "name"}`} instead of the value itself, and the stored secret is used.
{channels.length === 0 ? (

No channels yet. Add one to have somewhere to send to.

) : ( channels.map((channel, index) => (
patchChannel(index, { name: event.target.value }) } />
patchChannel(index, { enabled }) } />
{channel.kind === "webpush" ? : null}
{FIELDS[channel.kind].map(([key, label, placeholder]) => (
patchChannel(index, { config: { ...channel.config, [key]: parseSetting(event.target.value), }, }) } />
))}
)) )}

Rules

Which failures go to which channels. The same fault repeating is held back until its cooldown passes.
{rules.length === 0 ? (

No rules yet, so nothing is sent. A rule picks the failures worth hearing about and the channels that carry them.

) : ( rules.map((rule, index) => { const events = rule.events ?? [] const targets = rule.channels ?? [] const patchRule = (patch: Partial) => setDraft({ ...draft, rules: rules.map((r, i) => i === index ? { ...r, ...patch } : r, ), }) const toggle = (list: string[], value: string) => list.includes(value) ? list.filter((item) => item !== value) : [...list, value] return (
{events.length === 0 ? "On any failure" : `On ${events.length} of these`}
{EVENTS.map(([event, label]) => ( ))}
Send to {channels.length === 0 ? (

Add a channel first.

) : (
{channels.map((channel) => ( ))}
)}
patchRule({ cooldown_s: Number(event.target.value) }) } />
) }) )}
{dirty ? ( Unsaved changes. ) : null}
) }