"use client"; /** * Per-channel reliability status surface (v1.4.15 Phase B3). * * Shows for each configured Telegram / ntfy / Web Push channel: * - State badge (Active / Auto-disabled / Sending paused / Manually off) * - Last successful send timestamp * - Last failure + reason * - Consecutive failure counter * - "Re-enable" button when auto-disabled * - "Send test" button (delegates to per-channel test endpoints that * already exist for Telegram, ntfy, Web Push). * * Pulls data from `GET /api/notifications/status`. Re-enable hits * `POST /api/notifications/status`, which clears `disabledReason` + * `consecutiveFailures`, then the user can fire a test send via the * channel's existing test endpoint. */ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { AlertCircle, Bell, CheckCircle2, Clock, Loader2, RotateCw, Send, } from "lucide-react"; import { Badge } from "@/components/ui/badge"; import { EmptyState } from "@/components/ui/empty-state"; import { Button } from "@/components/ui/button"; import { useAuth } from "@/hooks/use-auth"; import { useMounted } from "@/hooks/use-mounted"; import { SettingsCard } from "@/components/settings/settings-card"; import { SettingsCardHeader } from "@/components/settings/_card-header"; import { useFormatters, useTranslations } from "@/lib/i18n/context"; import { queryKeys } from "@/lib/query-keys"; import { apiFetchRaw, apiGet, apiPost } from "@/lib/api/api-fetch"; type ChannelType = "TELEGRAM" | "NTFY" | "WEB_PUSH" | "APNS"; type ChannelState = "active" | "auto_disabled" | "manually_disabled" | "sending_paused"; interface ChannelStatus { id: string; type: ChannelType; label: string; enabled: boolean; state: ChannelState; disabledReason: string | null; consecutiveFailures: number; lastSuccessAt: string | null; lastFailureAt: string | null; lastFailureReason: string | null; nextRetryAt: string | null; } const TEST_ENDPOINTS: Record = { TELEGRAM: "/api/settings/telegram/test", NTFY: "/api/settings/ntfy/test", WEB_PUSH: "/api/notifications/web-push/test", APNS: "/api/notifications/apns/test", }; export function NotificationStatusCard() { const hydrated = useMounted(); const { isAuthenticated } = useAuth(); const { t } = useTranslations(); const fmt = useFormatters(); const queryClient = useQueryClient(); const { data, isLoading } = useQuery({ queryKey: queryKeys.notificationsStatus(), queryFn: async () => { const data = await apiGet<{ channels: ChannelStatus[] }>( "/api/notifications/status", ); return data.channels; }, enabled: isAuthenticated, refetchInterval: 30_000, }); const reEnable = useMutation({ mutationFn: async (channelId: string) => { await apiPost("/api/notifications/status", { channelId }); }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: queryKeys.notificationsStatus(), }); }, }); const test = useMutation({ mutationFn: async (channel: ChannelStatus) => { const res = await apiFetchRaw(TEST_ENDPOINTS[channel.type], { method: "POST", }); if (!res.ok) { const json = await res.json().catch(() => ({})); throw new Error((json as { error?: string }).error ?? "test_failed"); } }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: queryKeys.notificationsStatus(), }); }, }); // SSR and the first client paint must render the SAME tree shape. `useAuth` // reads a client TanStack query, so `isAuthenticated` is `false` on the // server (renders `null`) but `true` on the hydrating client (would render // the loading card) โ€” different shapes โ†’ React #418 hydration mismatch. // Gate every auth/loading-dependent branch behind the post-mount probe so // both passes render `null`; the real content lands as an ordinary // post-hydration client update, not a hydration-time branch. if (!hydrated || !isAuthenticated) return null; // The header paints in every state, so resolving the channel list does not // move the page under the cursor. if (isLoading) { return ( ); } // Defensive: the status endpoint returns `{ channels, events }` where // `events` is an object map, not an array. A stale or shape-drifted // payload (or a cache read that kept the whole object instead of the // `.channels` slice) must never reach `.map` on a non-array โ€” guard the // type here rather than white-screening the whole notifications panel. const channels = Array.isArray(data) ? data : []; if (channels.length === 0) { return ( ); } return (
    {channels.map((ch) => ( fmt.dateTime(iso)} t={t} onReEnable={() => reEnable.mutate(ch.id)} onTest={() => test.mutate(ch)} reEnablePending={reEnable.isPending} testPending={test.isPending} /> ))}
); } function ChannelRow({ channel, formatDateTime, t, onReEnable, onTest, reEnablePending, testPending, }: { channel: ChannelStatus; formatDateTime: (iso: string | Date) => string; t: (key: string, vars?: Record) => string; onReEnable: () => void; onTest: () => void; reEnablePending: boolean; testPending: boolean; }) { const stateBadge = stateBadgeFor(channel.state, t); return (
  • {channel.label} {stateBadge.icon} {stateBadge.label}
    {channel.lastSuccessAt && (
    {t("settings.notificationStatus.lastSuccess")}:
    {" "}
    {formatDateTime(channel.lastSuccessAt)}
    )} {channel.lastFailureAt && (
    {t("settings.notificationStatus.lastFailure")}:
    {" "}
    {formatDateTime(channel.lastFailureAt)} {channel.lastFailureReason ? ` ยท ${channel.lastFailureReason}` : ""}
    )} {channel.consecutiveFailures > 0 && (
    {t("settings.notificationStatus.consecutiveFailures")}:
    {" "}
    {channel.consecutiveFailures}
    )} {channel.disabledReason && (
    {t("settings.notificationStatus.disabledReason")}:
    {" "}
    {channel.disabledReason}
    )} {channel.state === "sending_paused" && channel.nextRetryAt && (
    {t("settings.notificationStatus.nextRetry")}:
    {" "}
    {formatDateTime(channel.nextRetryAt)}
    )}
    {/* v1.4.15 H4 design: action buttons hit the WCAG 2.5.5 44 px floor on mobile via `min-h-11`. Settings is the most-touched mobile surface; `size="sm"` here clips to ~32 px which the maintainer flagged as too small on the iPad/iPhone PWA shell. */}
    {channel.state === "auto_disabled" && ( )}
  • ); } function stateBadgeFor( state: ChannelState, t: (key: string) => string, ): { label: string; variant: "default" | "outline" | "destructive" | "secondary"; className: string; icon: React.ReactNode; } { switch (state) { case "active": return { label: t("settings.notificationStatus.stateActive"), variant: "default", className: "border-success/30 bg-success/15 text-success", icon: , }; case "auto_disabled": return { label: t("settings.notificationStatus.stateAutoDisabled"), variant: "destructive", className: "", icon: , }; case "sending_paused": return { label: t("settings.notificationStatus.stateSendingPaused"), variant: "outline", className: "border-warning/40 text-warning", icon: , }; case "manually_disabled": return { label: t("settings.notificationStatus.stateManuallyDisabled"), variant: "secondary", className: "", icon: , }; } }