'use client' // Notifications settings (DESIGN_NOTIFICATIONS.md phase 1): channels with // write-only secrets, rules with the house version contract (every mutating // PATCH sends the expected version; a 409 reloads instead of clobbering), // and a recent-delivery strip. Plan gating surfaces as the server's 403 // "Not available on your plan" toast — the UI never guesses entitlements. import { useCallback, useEffect, useState } from 'react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Switch } from '@/components/ui/switch' import { Badge } from '@/components/ui/badge' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' import { Bell, Mail, Slack, MessageSquare, Send, Trash2, Loader2, Smartphone, X } from 'lucide-react' import { toast } from 'sonner' type Channel = { id: string; kind: string; name: string; enabled: boolean; version: number config: Record; createdAt: string } type Rule = { id: string; name: string; trigger: string; config: { leadHours?: number; targetUserIds?: string[] } channelId: string; channelKind: string; channelName: string cooldownMinutes: number; enabled: boolean; lastFiredAt: string | null; version: number } type NotificationRow = { id: string; title: string; status: string; attempts: number ruleName: string; channelKind: string; sentAt: string | null; createdAt: string } const MASK = '••••••••' const KIND_META: Record = { email: { label: 'Email', icon: Mail, fields: [{ key: 'address', label: 'Address (blank = account email)', placeholder: 'you@example.com' }] }, slack: { label: 'Slack', icon: Slack, fields: [{ key: 'webhookUrl', label: 'Incoming webhook URL', secret: true, placeholder: 'https://hooks.slack.com/services/…' }] }, matrix: { label: 'Matrix', icon: MessageSquare, fields: [ { key: 'homeserver', label: 'Homeserver URL', placeholder: 'https://matrix.example.org' }, { key: 'roomId', label: 'Room ID', placeholder: '!room:example.org' }, { key: 'accessToken', label: 'Access token', secret: true }, ], }, telegram: { label: 'Telegram', icon: Send, fields: [ { key: 'botToken', label: 'Bot token', secret: true }, { key: 'chatId', label: 'Chat ID' }, ], }, signal: { label: 'Signal', icon: Smartphone, fields: [ { key: 'restUrl', label: 'signal-cli REST bridge URL', placeholder: 'https://signal-rest.example.org' }, { key: 'account', label: 'Sender account (phone or uuid)', secret: true }, { key: 'recipient', label: 'Recipient (phone or uuid)' }, ], }, } const TRIGGER_LABELS: Record = { signal_created: 'New signal matches a mailbox watcher', bookmark_due: 'A bookmark is due soon or overdue', share_received: 'Someone shares a bookmark, tag or collection with you', } async function api(path: string, init?: RequestInit): Promise { return fetch(path, { headers: { 'Content-Type': 'application/json' }, cache: 'no-store', ...init }) } export function NotificationsSettings() { const [channels, setChannels] = useState([]) const [rules, setRules] = useState([]) const [history, setHistory] = useState([]) const [loading, setLoading] = useState(true) // Channel form const [chKind, setChKind] = useState('email') const [chName, setChName] = useState('') const [chConfig, setChConfig] = useState>({}) const [savingCh, setSavingCh] = useState(false) // Rule form const [rName, setRName] = useState('') const [rTrigger, setRTrigger] = useState('bookmark_due') const [rChannel, setRChannel] = useState('') const [rLead, setRLead] = useState(24) // Targeted recipients (same-tenant users); deliveries ride each target's // own channel of the rule's kind. const [rTargets, setRTargets] = useState<{ id: string; name: string | null; email: string | null }[]>([]) const [targetQuery, setTargetQuery] = useState('') const [targetResults, setTargetResults] = useState<{ id: string; name: string | null; email: string | null }[]>([]) const [savingR, setSavingR] = useState(false) const [testingId, setTestingId] = useState(null) // Promise-chain shape (house pattern, see admin/client.tsx): setState // lives only inside async callbacks — the SSR lint refuses effects that // can reach a synchronous setState. const reload = useCallback(() => Promise.all([ api('/api/notifications/channels').then(r => r.json()), api('/api/notifications/rules').then(r => r.json()), api('/api/notifications').then(r => r.json()), ]) .then(([ch, ru, hi]) => { if (Array.isArray(ch)) setChannels(ch) if (Array.isArray(ru)) setRules(ru) if (Array.isArray(hi)) setHistory(hi.slice(0, 10)) }) .catch(() => { toast.error('Could not load notification settings') }) .finally(() => { setLoading(false) }), []) useEffect(() => { reload() }, [reload]) const reportError = async (res: Response, fallback: string) => { let msg = fallback try { const data = await res.json() if (data?.error) msg = data.error } catch { /* body was not JSON */ } toast.error(msg) } const addChannel = async () => { if (!chName.trim()) { toast.error('Give the channel a name'); return } setSavingCh(true) try { const res = await api('/api/notifications/channels', { method: 'POST', body: JSON.stringify({ kind: chKind, name: chName.trim(), config: chConfig }), }) if (res.ok) { toast.success('Channel added') setChName(''); setChConfig({}) await reload() } else await reportError(res, 'Could not add the channel') } finally { setSavingCh(false) } } const toggleChannel = async (c: Channel, enabled: boolean) => { const res = await api(`/api/notifications/channels/${c.id}`, { method: 'PATCH', body: JSON.stringify({ enabled, version: c.version }), }) if (res.ok) await reload() else await reportError(res, 'Could not update the channel') } const removeChannel = async (c: Channel) => { const res = await api(`/api/notifications/channels/${c.id}`, { method: 'DELETE' }) if (res.ok) { toast.success('Channel removed'); await reload() } else await reportError(res, 'Could not remove the channel') } const testChannel = async (c: Channel) => { setTestingId(c.id) try { const res = await api(`/api/notifications/channels/${c.id}/test`, { method: 'POST' }) if (res.ok) toast.success('Test message sent') else await reportError(res, 'Test delivery failed') } finally { setTestingId(null) } } const addRule = async () => { if (!rName.trim()) { toast.error('Give the rule a name'); return } if (!rChannel) { toast.error('Pick a channel'); return } setSavingR(true) try { const res = await api('/api/notifications/rules', { method: 'POST', body: JSON.stringify({ name: rName.trim(), trigger: rTrigger, channelId: rChannel, config: { ...(rTrigger === 'bookmark_due' ? { leadHours: rLead } : {}), ...(rTargets.length ? { targetUserIds: rTargets.map(t => t.id) } : {}), }, }), }) if (res.ok) { toast.success('Rule created') setRName('') setRTargets([]) setTargetQuery('') await reload() } else await reportError(res, 'Could not create the rule') } finally { setSavingR(false) } } const toggleRule = async (rule: Rule, enabled: boolean) => { const res = await api(`/api/notifications/rules/${rule.id}`, { method: 'PATCH', body: JSON.stringify({ enabled, version: rule.version }), }) if (res.ok) await reload() else await reportError(res, 'Could not update the rule') } const removeRule = async (rule: Rule) => { const res = await api(`/api/notifications/rules/${rule.id}`, { method: 'DELETE' }) if (res.ok) { toast.success('Rule removed'); await reload() } else await reportError(res, 'Could not remove the rule') } const kindIcon = (kind: string) => { const Icon = KIND_META[kind]?.icon ?? Bell return } if (loading) { return
Loading notifications…
} return (
{/* Channels */}

Channels

Where notifications are delivered. Secrets are stored encrypted and never shown again after saving. Which channel kinds are available depends on your plan.

{channels.length === 0 && (

No channels yet — add one below.

)} {channels.map(c => (
{kindIcon(c.kind)}

{c.name}

{KIND_META[c.kind]?.label ?? c.kind} {c.config?.address ? ` · ${c.config.address}` : ''} {c.config?.homeserver ? ` · ${c.config.homeserver}` : ''}

toggleChannel(c, v)} aria-label="Enable channel" />
))}
) => setChName(e.target.value)} />
{KIND_META[chKind]?.fields.map(f => ( ) => setChConfig(p => ({ ...p, [f.key]: e.target.value }))} /> ))}
{/* Rules */}

Rules

When something happens in your brain, notify a channel. Each rule fires at most once per fact and respects its cooldown.

{rules.length === 0 &&

No rules yet.

} {rules.map(rule => (

{rule.name}

{TRIGGER_LABELS[rule.trigger] ?? rule.trigger} {rule.trigger === 'bookmark_due' && rule.config?.leadHours != null ? ` (within ${rule.config.leadHours}h)` : ''} {Array.isArray(rule.config?.targetUserIds) && rule.config.targetUserIds.length > 0 ? ` (+${rule.config.targetUserIds.length} targeted)` : ''} {' → '} {kindIcon(rule.channelKind)}{rule.channelName}

toggleRule(rule, v)} aria-label="Enable rule" />
))}
) => setRName(e.target.value)} />
{rTrigger === 'bookmark_due' && ( )}
{rTargets.map(tgt => ( {tgt.name ?? tgt.email ?? tgt.id.slice(0, 8)} ))} {rTargets.length > 0 && also notify (via their own channels)}
) => { const q = e.target.value setTargetQuery(q) if (q.trim().length < 2) { setTargetResults([]); return } api(`/api/users/search?q=${encodeURIComponent(q)}`) .then(r => (r.ok ? r.json() : [])) .then((rows: { id: string; name: string | null; email: string | null }[]) => setTargetResults(rows.filter(u => !rTargets.some(t => t.id === u.id)).slice(0, 6))) .catch(() => setTargetResults([])) }} /> {targetResults.map(u => ( ))}
{/* Recent deliveries */}

Recent notifications

{history.length === 0 &&

Nothing sent yet.

} {history.map(n => (
{n.status} {n.title} {n.ruleName}
))}
) }