Repository Public
1"use client";2import Link from "next/link";3import { useQueryClient } from "@tanstack/react-query";4import { useState, type ReactNode } from "react";5import { apiPost, type Schemas } from "@/api/client";6import { ApiError } from "@/api/errors";7import { invalidatePaths, useApiList } from "@/api/query";8import { NodeLink, useNodeOptions } from "@/features/shared/nodes";9import { useI18n } from "@/i18n";10import { localTimeZone } from "@/lib/format";11import { useSession } from "@/shell/session";12import { Badge, Banner, Button, Checkbox, Combobox, Dialog, EmptyState, Linkified, Segmented, SelectField, StateDot, Tag, TextAreaField, TextField, alertTone, cx, incidentTone, severityTone, useErrorMessage, useToast, type Tone } from "@/ui";13import { summarizeScope, validateSilence, type Scope, type ScopeForm, type ScopeKind, type Severity, type SilenceErrors, type SilenceForm } from "./logic";1415type Alert = Schemas["Alert"];1617export function SeverityBadge({ severity }: { severity: Severity }) {18 const { t } = useI18n();19 return <Badge tone={severityTone(severity)}>{t(`states.severity.${severity}`)}</Badge>;20}21export function AlertStateDot({ alert }: { alert: Pick<Alert, "state" | "severity"> }) {22 const { t } = useI18n();23 return <StateDot tone={alertTone(alert.state, alert.severity)} icon={alert.state === "acknowledged" ? "eye" : alert.state === "pending" ? "pending" : undefined} label={t(`states.alert.${alert.state}`)} />;24}25export function IncidentStateDot({ state }: { state: Schemas["IncidentState"] }) {26 const { t } = useI18n();27 return <StateDot tone={incidentTone(state)} label={t(`states.incident.${state}`)} />;28}29/** Notifications suppressed: said in words with its cause, never implied. */30export function Suppression({ by }: { by: Alert["suppressed_by"] }) {31 const { t } = useI18n();32 if (!by) return <span className="faint">{t("alerts.suppression.none")}</span>;33 return <Badge tone={by === "maintenance" ? "maintenance" : "offline"} icon={by === "maintenance" ? "wrench" : "silence"}>{t(`alerts.suppression.${by}`)}</Badge>;34}3536export function ScopeText({ scope }: { scope: Scope | undefined }) {37 const { t, tn } = useI18n();38 const nodes = useNodeOptions();39 const s = summarizeScope(scope);40 if (s.kind === "all") return <span>{t("alerts.scope.all")}</span>;41 if (s.kind === "empty") return <span className="faint">{t("alerts.scope.empty")}</span>;42 if (s.kind === "tags") return <span className="row-wrap gap-2"><span className="sr-only">{t("alerts.scope.tags")}</span>{s.tags.map((x) => <Tag key={x}>{x}</Tag>)}</span>;43 const shown = s.ids.slice(0, 3);44 return (45 <span className="row-wrap gap-2" title={s.ids.map((id) => nodes.byId.get(id) ?? id).join(", ")}>46 {shown.map((id) => <NodeLink key={id} id={id} alias={nodes.byId.get(id)} />)}47 {s.ids.length > shown.length ? <span className="muted">{tn("alerts.scope.more", s.ids.length - shown.length)}</span> : null}48 </span>49 );50}5152/** Scope editor shared by rules and silences: all nodes / chosen nodes / tags. */53export function ScopeFields<F extends ScopeForm>({ form, onChange, error, disabled }: { form: F; onChange: (patch: Partial<ScopeForm>) => void; error?: string | undefined; disabled?: boolean }) {54 const { t } = useI18n();55 const nodes = useNodeOptions();56 return (57 <fieldset className="mcc-fieldset" disabled={disabled}>58 <legend>{t("alerts.scope.label")}</legend>59 <Segmented<ScopeKind> label={t("alerts.scope.label")} value={form.scopeKind} onChange={(scopeKind) => onChange({ scopeKind })}60 options={[{ value: "all", label: t("alerts.scope.all") }, { value: "nodes", label: t("alerts.scope.nodes") }, { value: "tags", label: t("alerts.scope.tags") }]} />61 {form.scopeKind === "nodes" ? (62 <>63 <Combobox multiple label={t("alerts.scope.pickNodes")} options={nodes.options} value={form.nodeIds} onChange={(nodeIds) => onChange({ nodeIds })} error={error} required />64 {nodes.error ? <span className="mcc-hint" role="status">{nodes.error.notImplemented ? t("alerts.scope.nodesNotAvailable") : t("alerts.scope.nodesError")}</span> : null}65 </>66 ) : null}67 {form.scopeKind === "tags" ? <TextField label={t("alerts.scope.tags")} hint={t("alerts.scope.tagsHint")} value={form.tagsText} onChange={(tagsText) => onChange({ tagsText })} mono error={error} required /> : null}68 </fieldset>69 );70}7172const KIND_TONE: Record<string, Tone> = { fired: "critical", opened: "warning", reopened: "warning", acknowledged: "info", resolved: "ok", suppressed: "offline", comment: "neutral", notified: "info", state_changed: "info", alert_linked: "info", alert_unlinked: "offline", owner_changed: "info" };73const KNOWN_KINDS = ["opened", "fired", "acknowledged", "resolved", "reopened", "comment", "suppressed", "notified", "state_changed", "alert_linked", "alert_unlinked", "owner_changed"] as const;7475/** Chronology of an alert or incident. Bodies are plain text (line breaks kept, URLs linked safely). */76export function Timeline({ events }: { events: readonly Schemas["TimelineEvent"][] }) {77 const { t, fmt } = useI18n();78 if (events.length === 0) return <EmptyState compact icon="history" title={t("alerts.timeline.empty")} />;79 const ordered = [...events].sort((a, b) => Date.parse(a.ts) - Date.parse(b.ts));80 return (81 <ol className="mcc-timeline" data-testid="timeline">82 {ordered.map((e) => {83 const known = (KNOWN_KINDS as readonly string[]).includes(e.kind) ? (e.kind as (typeof KNOWN_KINDS)[number]) : null;84 return (85 <li key={e.id} className={cx(`tone-${KIND_TONE[e.kind] ?? "neutral"}`)} data-kind={e.kind}>86 <span className="pt" aria-hidden="true" />87 <div className="stack-sm">88 <div className="row-wrap gap-2">89 <strong>{known ? t(`alerts.timeline.kind.${known}`) : <span className="mono">{e.kind}</span>}</strong>90 <span className="muted">{e.actor_display_name ?? t("alerts.timeline.system")}</span>91 <time className="meta num" dateTime={e.ts} title={fmt.relative(e.ts)}>{fmt.dateTime(e.ts, { seconds: true })}</time>92 </div>93 {e.body ? <div><Linkified text={e.body} /></div> : null}94 </div>95 </li>96 );97 })}98 </ol>99 );100}101102export function CommentBox({ onSubmit, disabledReason }: { onSubmit: (body: string) => Promise<void>; disabledReason?: string | undefined }) {103 const { t } = useI18n();104 const toast = useToast();105 const explain = useErrorMessage();106 const [body, setBody] = useState("");107 const [busy, setBusy] = useState(false);108 if (disabledReason) return <p className="mcc-hint">{disabledReason}</p>;109 const send = async () => {110 const text = body.trim();111 if (text === "") return;112 setBusy(true);113 try {114 await onSubmit(text);115 setBody("");116 toast({ tone: "ok", title: t("alerts.comment.added") });117 } catch (e) {118 toast({ tone: "critical", ...explain(e) });119 } finally {120 setBusy(false);121 }122 };123 return (124 <form className="stack-sm" onSubmit={(e) => { e.preventDefault(); void send(); }}>125 <TextAreaField label={t("alerts.comment.label")} hint={t("alerts.comment.hint")} value={body} onChange={setBody} maxLength={4000} disabled={busy}126 onKeyDown={(e) => { if ((e.metaKey || e.ctrlKey) && e.key === "Enter") { e.preventDefault(); void send(); } }} data-testid="comment-input" />127 <div className="row"><Button type="submit" icon="comment" loading={busy} disabled={body.trim() === ""} data-testid="comment-submit">{t("alerts.comment.submit")}</Button></div>128 </form>129 );130}131132/** Acknowledge / resolve with an optional comment. */133export function TransitionDialog({ kind, alert, onClose }: { kind: "acknowledge" | "resolve"; alert: Pick<Alert, "id" | "rule_name" | "node_alias">; onClose: () => void }) {134 const { t } = useI18n();135 const qc = useQueryClient();136 const toast = useToast();137 const [comment, setComment] = useState("");138 const [busy, setBusy] = useState(false);139 const [error, setError] = useState<ApiError | null>(null);140 const run = async () => {141 setBusy(true);142 setError(null);143 try {144 const body = comment.trim() ? { comment: comment.trim() } : {};145 if (kind === "acknowledge") await apiPost("/alerts/{id}/acknowledge", { path: { id: alert.id }, body });146 else await apiPost("/alerts/{id}/resolve", { path: { id: alert.id }, body });147 toast({ tone: "ok", title: kind === "acknowledge" ? t("alerts.ack.done") : t("alerts.resolve.done") });148 await invalidatePaths(qc, "/alerts", "/incidents", "/cluster/overview");149 onClose();150 } catch (e) {151 setBusy(false);152 setError(e instanceof ApiError ? e : new ApiError({ status: 0, code: "network", message: "network" }));153 }154 };155 return (156 <Dialog open onClose={onClose} dismissable={!busy} title={kind === "acknowledge" ? t("alerts.ack.title") : t("alerts.resolve.title")}157 description={<>{alert.rule_name}{alert.node_alias ? <> · <span className="mono">{alert.node_alias}</span></> : null}</>}158 footer={<><Button onClick={onClose} disabled={busy}>{t("common.cancel")}</Button><Button variant="primary" loading={busy} onClick={() => void run()} data-testid="transition-confirm">{kind === "acknowledge" ? t("alerts.ack.action") : t("alerts.resolve.action")}</Button></>}>159 <p className="muted">{kind === "acknowledge" ? t("alerts.ack.body") : t("alerts.resolve.body")}</p>160 <TextAreaField label={t("alerts.transition.comment")} value={comment} onChange={setComment} maxLength={4000} disabled={busy} />161 {error ? <MutationError error={error} /> : null}162 </Dialog>163 );164}165166export function MutationError({ error, extra }: { error: ApiError; extra?: ReactNode }) {167 const explain = useErrorMessage();168 const { t } = useI18n();169 const m = explain(error);170 return (171 <Banner tone={error.status === 409 || error.status === 422 || error.status === 400 ? "warning" : "critical"} role="alert">172 <strong>{m.title}</strong>{m.detail ? <> — {m.detail}</> : null}173 {error.code === "conflict" ? <> {t("alerts.error.conflict")}</> : null}174 {extra}175 </Banner>176 );177}178179/** Open an incident, optionally from selected alerts. Owner: self, or any user when users can be listed. */180export function IncidentDialog({ alerts, onClose, onCreated }: { alerts: readonly Pick<Alert, "id" | "rule_name" | "node_alias" | "severity">[]; onClose: () => void; onCreated?: (incident: Schemas["Incident"]) => void }) {181 const { t, tn } = useI18n();182 const qc = useQueryClient();183 const toast = useToast();184 const session = useSession();185 const users = useApiList("/users", { query: { limit: 200 } }, { enabled: session.can("users.manage") });186 const worst: Severity = alerts.some((a) => a.severity === "critical") ? "critical" : alerts.some((a) => a.severity === "warning") || alerts.length === 0 ? "warning" : "info";187 const first = alerts[0];188 const [title, setTitle] = useState(first && alerts.length === 1 ? `${first.rule_name}${first.node_alias ? ` — ${first.node_alias}` : ""}` : "");189 const [severity, setSeverity] = useState<Severity>(worst);190 const [summary, setSummary] = useState("");191 const [owner, setOwner] = useState<string | null>(null);192 const [mine, setMine] = useState(false);193 const [busy, setBusy] = useState(false);194 const [error, setError] = useState<ApiError | null>(null);195 const [missing, setMissing] = useState(false);196 const submit = async () => {197 if (title.trim() === "") { setMissing(true); return; }198 setBusy(true);199 setError(null);200 try {201 const owner_id = users.ready ? owner : mine ? (session.me?.user.id ?? null) : null;202 const incident = await apiPost("/incidents", { body: { title: title.trim(), severity, ...(summary.trim() ? { summary: summary.trim() } : {}), ...(owner_id ? { owner_id } : {}), ...(alerts.length > 0 ? { alert_ids: alerts.map((a) => a.id) } : {}) } });203 toast({ tone: "ok", title: t("alerts.incident.created") });204 await invalidatePaths(qc, "/incidents", "/alerts", "/cluster/overview");205 onCreated?.(incident);206 onClose();207 } catch (e) {208 setBusy(false);209 setError(e instanceof ApiError ? e : new ApiError({ status: 0, code: "network", message: "network" }));210 }211 };212 return (213 <Dialog open onClose={onClose} dismissable={!busy} size="wide" title={t("alerts.incident.createTitle")} description={alerts.length > 0 ? tn("alerts.incident.fromAlerts", alerts.length) : t("alerts.incident.createBody")}214 footer={<><Button onClick={onClose} disabled={busy}>{t("common.cancel")}</Button><Button variant="primary" loading={busy} onClick={() => void submit()} data-testid="incident-create-submit">{t("alerts.incident.create")}</Button></>}>215 <form className="mcc-form" onSubmit={(e) => { e.preventDefault(); void submit(); }}>216 <TextField label={t("alerts.incident.title")} value={title} onChange={setTitle} required maxLength={160} disabled={busy} error={missing && title.trim() === "" ? t("alerts.form.required") : undefined} data-testid="incident-title" />217 <div className="mcc-form-row">218 <SelectField<Severity> label={t("alerts.col.severity")} value={severity} onChange={setSeverity} disabled={busy}219 options={(["critical", "warning", "info"] as const).map((s) => ({ value: s, label: t(`states.severity.${s}`) }))} />220 {users.ready ? (221 <Combobox label={t("alerts.incident.owner")} hint={t("alerts.incident.ownerHint")} value={owner} onChange={setOwner} options={users.items.filter((u) => !u.disabled).map((u) => ({ value: u.id, label: u.display_name, hint: `@${u.handle}` }))} />222 ) : (223 <Checkbox label={t("alerts.incident.assignMe")} checked={mine} onChange={setMine} />224 )}225 </div>226 <TextAreaField label={t("alerts.incident.summary")} value={summary} onChange={setSummary} maxLength={8000} disabled={busy} />227 </form>228 {alerts.length > 0 ? (229 <ul className="al-picked" aria-label={t("alerts.incident.linked")}>230 {alerts.map((a) => <li key={a.id}><SeverityBadge severity={a.severity} /> <span className="truncate">{a.rule_name}</span>{a.node_alias ? <span className="mono muted">{a.node_alias}</span> : null}</li>)}231 </ul>232 ) : null}233 {error ? <MutationError error={error} /> : null}234 </Dialog>235 );236}237238export interface SilencePrefill {239 nodeId?: string | undefined;240 ruleId?: string | undefined;241 reason?: string | undefined;242}243type SilenceCode = NonNullable<SilenceErrors[keyof SilenceErrors]>;244245export function SilenceDialog({ prefill, onClose }: { prefill?: SilencePrefill | undefined; onClose: () => void }) {246 const { t } = useI18n();247 const qc = useQueryClient();248 const toast = useToast();249 const rules = useApiList("/alert-rules", { query: { limit: 200 } });250 const [form, setForm] = useState<SilenceForm>({251 reason: prefill?.reason ?? "", ruleId: prefill?.ruleId ?? null, startsLocal: "", duration: "1", endsLocal: "",252 scopeKind: prefill?.nodeId ? "nodes" : "all", nodeIds: prefill?.nodeId ? [prefill.nodeId] : [], tagsText: "",253 });254 const [errors, setErrors] = useState<SilenceErrors>({});255 const [busy, setBusy] = useState(false);256 const [error, setError] = useState<ApiError | null>(null);257 const patch = (p: Partial<SilenceForm>) => setForm((f) => ({ ...f, ...p }));258 const msg = (code: SilenceCode | undefined) => (code ? t(`alerts.form.${code}`) : undefined);259 const submit = async () => {260 const r = validateSilence(form, Date.now());261 setErrors(r.errors);262 if (!r.body) return;263 setBusy(true);264 setError(null);265 try {266 await apiPost("/silences", { body: r.body });267 toast({ tone: "ok", title: t("alerts.silence.created") });268 await invalidatePaths(qc, "/silences", "/alerts");269 onClose();270 } catch (e) {271 setBusy(false);272 setError(e instanceof ApiError ? e : new ApiError({ status: 0, code: "network", message: "network" }));273 }274 };275 const ruleOptions = rules.items.map((r) => ({ value: r.id, label: r.name, hint: t(`alerts.rule.kind.${r.kind}`) }));276 return (277 <Dialog open onClose={onClose} dismissable={!busy} size="wide" title={t("alerts.silence.createTitle")} description={t("alerts.silence.createBody")}278 footer={<><Button onClick={onClose} disabled={busy}>{t("common.cancel")}</Button><Button variant="primary" icon="silence" loading={busy} onClick={() => void submit()} data-testid="silence-submit">{t("alerts.silence.create")}</Button></>}>279 <form className="mcc-form" onSubmit={(e) => { e.preventDefault(); void submit(); }}>280 <TextAreaField label={t("alerts.silence.reason")} hint={t("alerts.silence.reasonHint")} value={form.reason} onChange={(reason) => patch({ reason })} required maxLength={500} disabled={busy} error={msg(errors.reason)} data-testid="silence-reason" />281 <ScopeFields form={form} onChange={patch} error={msg(errors.scope)} disabled={busy} />282 <Combobox label={t("alerts.silence.rule")} hint={rules.error ? (rules.error.notImplemented ? t("alerts.silence.rulesNotAvailable") : t("alerts.silence.rulesError")) : t("alerts.silence.ruleHint")} value={form.ruleId} onChange={(ruleId) => patch({ ruleId })}283 options={form.ruleId && !ruleOptions.some((o) => o.value === form.ruleId) ? [{ value: form.ruleId, label: form.ruleId }, ...ruleOptions] : ruleOptions} />284 <div className="mcc-form-row">285 <TextField label={t("alerts.silence.starts")} hint={t("alerts.silence.startsHint")} type="datetime-local" value={form.startsLocal} onChange={(startsLocal) => patch({ startsLocal })} disabled={busy} error={msg(errors.starts)} />286 <fieldset className="mcc-fieldset" disabled={busy}>287 <legend>{t("alerts.silence.duration")}</legend>288 <Segmented<SilenceForm["duration"]> label={t("alerts.silence.duration")} value={form.duration} onChange={(duration) => patch({ duration })}289 options={[{ value: "1", label: t("alerts.silence.h1") }, { value: "4", label: t("alerts.silence.h4") }, { value: "24", label: t("alerts.silence.h24") }, { value: "custom", label: t("alerts.silence.custom") }]} />290 </fieldset>291 </div>292 {form.duration === "custom" ? <TextField label={t("alerts.silence.ends")} type="datetime-local" value={form.endsLocal} onChange={(endsLocal) => patch({ endsLocal })} required disabled={busy} error={msg(errors.ends)} /> : null}293 <p className="mcc-hint">{t("alerts.silence.zone", { zone: localTimeZone() })}</p>294 </form>295 {error ? <MutationError error={error} /> : null}296 </Dialog>297 );298}299300export function IncidentLink({ id, children }: { id: string; children?: ReactNode }) {301 const { t } = useI18n();302 return <Link href={`/incidents/${id}`}>{children ?? t("alerts.incident.view")}</Link>;303}304