Files
app/frontend/src/routes/_layout/alerts.tsx
T
stroblmeandClaude Opus 5 2422a9b22b Move the remaining panel explanations into tooltips
A node setting's description comes off the backend JSON schema, so every
node type's panel still printed a paragraph under each field. It moves to
the field label, which is the change that makes the node panel read as a
list rather than a page.

Alerts, Modules and Remote access follow the same shape. A page keeps a
one-line description under its h1 — a page is arrived at rather than
scanned — and the rest goes behind the heading's tooltip.

Verified on the running stack: the tooltip opens on tap in the phone sheet
and on hover on the desktop panel.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015YrQnKV3bnQd4K342y8tKj
2026-08-31 10:38:16 +02:00

530 lines
18 KiB
TypeScript

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<Channel["kind"], [string, string, string][]> = {
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 (
<p className="text-sm text-muted-foreground">
This browser cannot receive notifications. They need HTTPS — over plain
http on a local address, no browser will allow them.
</p>
)
}
return (
<div className="flex flex-wrap items-center justify-between gap-3">
<span className="text-sm text-muted-foreground">
{subscribed
? "This browser is subscribed."
: "This browser is not subscribed yet. Each device subscribes itself."}
</span>
<Button
variant="outline"
size="sm"
disabled={change.isPending}
onClick={() => change.mutate(!subscribed)}
>
{subscribed ? <BellOff /> : <Bell />}
{subscribed ? "Unsubscribe" : "Subscribe"}
</Button>
</div>
)
}
function Alerts() {
const { data } = useQuery({
queryKey: alertsKey,
queryFn: () => AlertsService.readAlertsConfig(),
})
return (
<div className="grid gap-6">
<div className="grid gap-1">
<h1 className="text-2xl">Alerts</h1>
<p className="text-sm text-muted-foreground">
Where the engine goes when something breaks.
</p>
</div>
{data ? <AlertsForm initial={data} /> : null}
</div>
)
}
function AlertsForm({ initial }: { initial: AlertsConfig }) {
const queryClient = useQueryClient()
const { showSuccessToast, showErrorToast } = useCustomToast()
const [draft, setDraft] = useState<AlertsConfig>(initial)
const [saved, setSaved] = useState<AlertsConfig>(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<Channel>) =>
setDraft({
...draft,
channels: channels.map((channel, i) =>
i === index ? { ...channel, ...patch } : channel,
),
})
return (
<>
<div className="flex items-center justify-between gap-3 rounded-lg border border-border bg-card p-4 shadow-e1">
<div className="grid gap-0.5">
<span className="text-sm font-medium">Alerting</span>
<span className="text-sm text-muted-foreground">
{draft.enabled
? "Failures reach the channels below."
: "Switched off — failures only reach the log."}
</span>
</div>
<Switch
checked={draft.enabled ?? true}
aria-label="Alerting enabled"
data-testid="alerts-enabled"
onCheckedChange={(enabled) => setDraft({ ...draft, enabled })}
/>
</div>
<section className="grid gap-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-1">
<h2 className={SECTION}>Channels</h2>
<InfoTip label="Channels">
Somewhere to send to. A setting can hold{" "}
<code className="font-mono">{`{"$secret": "name"}`}</code> instead
of the value itself, and the stored secret is used.
</InfoTip>
</div>
<Button
variant="ghost"
size="sm"
data-testid="add-channel"
onClick={() =>
setDraft({
...draft,
channels: [
...channels,
{
name: `channel-${channels.length + 1}`,
kind: "ntfy",
enabled: true,
config: {},
},
],
})
}
>
<Plus />
Add channel
</Button>
</div>
{channels.length === 0 ? (
<p className="text-sm text-muted-foreground">
No channels yet. Add one to have somewhere to send to.
</p>
) : (
channels.map((channel, index) => (
<div
// Names are what rules point at, but they are edited here, so the
// position is the only thing that stays put while typing.
key={index}
className="grid gap-3 rounded-lg border border-border bg-card p-4 shadow-e1"
data-testid="channel-card"
>
<div className="flex flex-wrap items-center gap-2">
<Input
value={channel.name}
aria-label="Channel name"
className="max-w-48"
onChange={(event) =>
patchChannel(index, { name: event.target.value })
}
/>
<Select
value={channel.kind}
onValueChange={(kind) =>
patchChannel(index, { kind: kind as Channel["kind"] })
}
>
<SelectTrigger className="w-32" aria-label="Channel kind">
<SelectValue />
</SelectTrigger>
<SelectContent>
{KINDS.map((kind) => (
<SelectItem key={kind} value={kind}>
{kind}
</SelectItem>
))}
</SelectContent>
</Select>
<div className="ml-auto flex items-center gap-2">
<Switch
checked={channel.enabled ?? true}
aria-label={`${channel.name} enabled`}
onCheckedChange={(enabled) =>
patchChannel(index, { enabled })
}
/>
<Button
variant="ghost"
size="sm"
disabled={dirty || test.isPending}
title={
dirty
? "Save first — the engine sends through the stored channel"
: "Send one alert through this channel"
}
data-testid="test-channel"
onClick={() => test.mutate(channel.name)}
>
<Send />
Test
</Button>
<Button
variant="ghost"
size="icon-sm"
aria-label={`Remove ${channel.name}`}
className="text-destructive hover:text-destructive"
onClick={() =>
setDraft({
...draft,
channels: channels.filter((_, i) => i !== index),
})
}
>
<Trash2 />
</Button>
</div>
</div>
{channel.kind === "webpush" ? <ThisBrowser /> : null}
<div className="grid gap-3 sm:grid-cols-3">
{FIELDS[channel.kind].map(([key, label, placeholder]) => (
<div key={key} className="grid gap-1.5">
<Label className="text-xs text-muted-foreground">
{label}
</Label>
<Input
value={showSetting(channel.config?.[key])}
placeholder={placeholder}
onChange={(event) =>
patchChannel(index, {
config: {
...channel.config,
[key]: parseSetting(event.target.value),
},
})
}
/>
</div>
))}
</div>
</div>
))
)}
</section>
<section className="grid gap-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-1">
<h2 className={SECTION}>Rules</h2>
<InfoTip label="Rules">
Which failures go to which channels. The same fault repeating is
held back until its cooldown passes.
</InfoTip>
</div>
<Button
variant="ghost"
size="sm"
data-testid="add-rule"
onClick={() =>
setDraft({
...draft,
rules: [
...rules,
{ events: [], channels: [], cooldown_s: 900 },
],
})
}
>
<Plus />
Add rule
</Button>
</div>
{rules.length === 0 ? (
<p className="text-sm text-muted-foreground">
No rules yet, so nothing is sent. A rule picks the failures worth
hearing about and the channels that carry them.
</p>
) : (
rules.map((rule, index) => {
const events = rule.events ?? []
const targets = rule.channels ?? []
const patchRule = (patch: Partial<typeof rule>) =>
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 (
<div
key={index}
className="grid gap-4 rounded-lg border border-border bg-card p-4 shadow-e1"
data-testid="rule-card"
>
<div className="grid gap-2">
<div className="flex items-center justify-between">
<span className={SECTION}>
{events.length === 0
? "On any failure"
: `On ${events.length} of these`}
</span>
<Button
variant="ghost"
size="icon-sm"
aria-label={`Remove rule ${index + 1}`}
className="text-destructive hover:text-destructive"
onClick={() =>
setDraft({
...draft,
rules: rules.filter((_, i) => i !== index),
})
}
>
<Trash2 />
</Button>
</div>
<div className="grid gap-2 sm:grid-cols-2">
{EVENTS.map(([event, label]) => (
<Label
key={event}
className="flex items-center gap-2 text-sm font-normal"
>
<Checkbox
checked={events.includes(event)}
onCheckedChange={() =>
patchRule({ events: toggle(events, event) })
}
/>
{label}
</Label>
))}
</div>
</div>
<div className="grid gap-2">
<span className={SECTION}>Send to</span>
{channels.length === 0 ? (
<p className="text-sm text-muted-foreground">
Add a channel first.
</p>
) : (
<div className="flex flex-wrap gap-4">
{channels.map((channel) => (
<Label
key={channel.name}
className="flex items-center gap-2 text-sm font-normal"
>
<Checkbox
checked={targets.includes(channel.name)}
onCheckedChange={() =>
patchRule({
channels: toggle(targets, channel.name),
})
}
/>
{channel.name}
</Label>
))}
</div>
)}
</div>
<div className="grid max-w-56 gap-1.5">
<Label className="text-xs text-muted-foreground">
Cooldown, in seconds
</Label>
<Input
type="number"
min={0}
value={rule.cooldown_s ?? 900}
aria-label="Cooldown in seconds"
onChange={(event) =>
patchRule({ cooldown_s: Number(event.target.value) })
}
/>
</div>
</div>
)
})
)}
</section>
<div className="flex items-center gap-3">
<Button
disabled={!dirty || save.isPending}
data-testid="save-alerts"
onClick={() => save.mutate(draft)}
>
Save
</Button>
{dirty ? (
<span className="text-sm text-muted-foreground">
Unsaved changes.
</span>
) : null}
</div>
</>
)
}