release gate / check (push) Failing after 6m54s
When something happens in the brain, tell the user (PLAN_PRICING_TIERS step 3). The engine is a SCANNER, not a hook system: producers are never instrumented; exactly-once comes solely from UNIQUE(ruleId,dedupeKey) + ON CONFLICT DO NOTHING, so rescans are free and restarts are safe. Schema (migration 013 + schema.sql, converge-verified): NotificationChannel (secrets encrypted at rest via internal/crypto, the IMAP-password format), NotificationRule (one channel per rule in phase 1, cooldown, version column), Notification (dedupe ledger + delivery state: pending/sent/failed/suppressed, attempts, backoff timestamp). internal/notify: two triggers — signal_created (fires only for signals newer than the rule, never retro-notifying history) and bookmark_due (lead-hours window, dedupe key carries the UTC due date so moving a dueDate re-notifies and same-day rescans do not). Delivery claims rows in one short transaction (FOR UPDATE SKIP LOCKED, batch 10) so multiple app instances never double-send; exponential backoff to 5 attempts; per-rule cooldown; per-owner pending cap. Channels: email (internal/mailer, falls back to the account email), Slack webhook, Matrix room, Telegram bot — webhooks dial through netguard inside outbound.Reserve budgets. The plan gate re-checks at delivery: a downgraded tenant's rows become 'suppressed' instead of sending. Signal-app delivery deliberately absent (needs a daemon; see plan doc hard truths). API: channel/rule CRUD with the house version contract (409 on stale base), write-only secrets (masked in every response; a PATCH echoing the mask keeps the stored value), test-send endpoint with its own budget, owner-scoped delivery history. Channel kinds gate on the ENTITLEMENT CATALOG (403 'Not available on your plan') — never on TIER, per the tenancy invariant. Web: Settings -> Notifications tab (channels with per-kind forms and Test button, rule builder, recent-delivery strip). Data loading uses the house promise-chain shape; setState only in async callbacks (SSR lint). Fixes along the way: mailer send budget raised 5->20/min (shared by resets and notifications; 5/min would throttle a hosted instance) and outbound gains ResetBudget() wired into the test harness — the global 'smtp' window made password-reset and notification tests collide when the package ran as a whole. Tests: full channel/rule/engine integration pass (masking + encryption round-trip, masked-PATCH preservation, version contract, plan gating via a forced 'free' tenant, dedupe across rescans, cooldown, real SMTP and webhook delivery via loopback fakes, backoff recording, downgrade suppression, history). Full suite green with -race; web lint/SSR-eslint/ build clean. Docs: API.md endpoint table, RUNNING.md, AGENTS.md invariants, DESIGN_NOTIFICATIONS.md (local).
323 lines
14 KiB
TypeScript
323 lines
14 KiB
TypeScript
'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 } from 'lucide-react'
|
|
import { toast } from 'sonner'
|
|
|
|
type Channel = {
|
|
id: string; kind: string; name: string; enabled: boolean; version: number
|
|
config: Record<string, string>; createdAt: string
|
|
}
|
|
type Rule = {
|
|
id: string; name: string; trigger: string; config: { leadHours?: number }
|
|
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<string, { label: string; icon: typeof Mail; fields: { key: string; label: string; secret?: boolean; placeholder?: string }[] }> = {
|
|
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' },
|
|
],
|
|
},
|
|
}
|
|
|
|
const TRIGGER_LABELS: Record<string, string> = {
|
|
signal_created: 'New signal matches a mailbox watcher',
|
|
bookmark_due: 'A bookmark is due soon or overdue',
|
|
}
|
|
|
|
async function api(path: string, init?: RequestInit): Promise<Response> {
|
|
return fetch(path, { headers: { 'Content-Type': 'application/json' }, cache: 'no-store', ...init })
|
|
}
|
|
|
|
export function NotificationsSettings() {
|
|
const [channels, setChannels] = useState<Channel[]>([])
|
|
const [rules, setRules] = useState<Rule[]>([])
|
|
const [history, setHistory] = useState<NotificationRow[]>([])
|
|
const [loading, setLoading] = useState(true)
|
|
|
|
// Channel form
|
|
const [chKind, setChKind] = useState('email')
|
|
const [chName, setChName] = useState('')
|
|
const [chConfig, setChConfig] = useState<Record<string, string>>({})
|
|
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)
|
|
const [savingR, setSavingR] = useState(false)
|
|
const [testingId, setTestingId] = useState<string | null>(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 } : {},
|
|
}),
|
|
})
|
|
if (res.ok) {
|
|
toast.success('Rule created')
|
|
setRName('')
|
|
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 <Icon className="h-3.5 w-3.5" />
|
|
}
|
|
|
|
if (loading) {
|
|
return <div className="flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="h-4 w-4 animate-spin" /> Loading notifications…</div>
|
|
}
|
|
|
|
return (
|
|
<div className="space-y-6">
|
|
{/* Channels */}
|
|
<div className="rounded-lg border p-4 space-y-3">
|
|
<h3 className="font-medium flex items-center gap-2"><Bell className="h-4 w-4" /> Channels</h3>
|
|
<p className="text-xs text-muted-foreground">
|
|
Where notifications are delivered. Secrets are stored encrypted and never shown again after saving.
|
|
Which channel kinds are available depends on your plan.
|
|
</p>
|
|
|
|
{channels.length === 0 && (
|
|
<p className="text-sm text-muted-foreground">No channels yet — add one below.</p>
|
|
)}
|
|
{channels.map(c => (
|
|
<div key={c.id} className="flex items-center gap-3 rounded-md border p-3">
|
|
<span className="text-muted-foreground">{kindIcon(c.kind)}</span>
|
|
<div className="min-w-0 flex-1">
|
|
<p className="text-sm font-medium truncate">{c.name}</p>
|
|
<p className="text-xs text-muted-foreground">
|
|
{KIND_META[c.kind]?.label ?? c.kind}
|
|
{c.config?.address ? ` · ${c.config.address}` : ''}
|
|
{c.config?.homeserver ? ` · ${c.config.homeserver}` : ''}
|
|
</p>
|
|
</div>
|
|
<Button size="sm" variant="outline" onClick={() => testChannel(c)} disabled={testingId === c.id}>
|
|
{testingId === c.id ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : 'Test'}
|
|
</Button>
|
|
<Switch checked={c.enabled} onCheckedChange={(v: boolean) => toggleChannel(c, v)} aria-label="Enable channel" />
|
|
<Button size="sm" variant="ghost" onClick={() => removeChannel(c)} aria-label="Remove channel">
|
|
<Trash2 className="h-3.5 w-3.5 text-muted-foreground" />
|
|
</Button>
|
|
</div>
|
|
))}
|
|
|
|
<div className="space-y-2 border-t pt-3">
|
|
<div className="flex gap-2">
|
|
<Select value={chKind} onValueChange={(v: string) => { setChKind(v); setChConfig({}) }}>
|
|
<SelectTrigger className="w-40" aria-label="Channel kind"><SelectValue /></SelectTrigger>
|
|
<SelectContent>
|
|
{Object.entries(KIND_META).map(([k, m]) => (
|
|
<SelectItem key={k} value={k}>{m.label}</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
<Input placeholder="Channel name" value={chName}
|
|
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setChName(e.target.value)} />
|
|
</div>
|
|
{KIND_META[chKind]?.fields.map(f => (
|
|
<Input key={f.key} type={f.secret ? 'password' : 'text'} placeholder={f.placeholder ?? f.label}
|
|
aria-label={f.label} value={chConfig[f.key] ?? ''}
|
|
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setChConfig(p => ({ ...p, [f.key]: e.target.value }))} />
|
|
))}
|
|
<Button onClick={addChannel} loading={savingCh} size="sm">Add channel</Button>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Rules */}
|
|
<div className="rounded-lg border p-4 space-y-3">
|
|
<h3 className="font-medium flex items-center gap-2"><Bell className="h-4 w-4" /> Rules</h3>
|
|
<p className="text-xs text-muted-foreground">
|
|
When something happens in your brain, notify a channel. Each rule fires at most once per
|
|
fact and respects its cooldown.
|
|
</p>
|
|
|
|
{rules.length === 0 && <p className="text-sm text-muted-foreground">No rules yet.</p>}
|
|
{rules.map(rule => (
|
|
<div key={rule.id} className="flex items-center gap-3 rounded-md border p-3">
|
|
<div className="min-w-0 flex-1">
|
|
<p className="text-sm font-medium truncate">{rule.name}</p>
|
|
<p className="text-xs text-muted-foreground truncate">
|
|
{TRIGGER_LABELS[rule.trigger] ?? rule.trigger}
|
|
{rule.trigger === 'bookmark_due' && rule.config?.leadHours != null ? ` (within ${rule.config.leadHours}h)` : ''}
|
|
{' → '}
|
|
<span className="inline-flex items-center gap-1">{kindIcon(rule.channelKind)}{rule.channelName}</span>
|
|
</p>
|
|
</div>
|
|
<Switch checked={rule.enabled} onCheckedChange={(v: boolean) => toggleRule(rule, v)} aria-label="Enable rule" />
|
|
<Button size="sm" variant="ghost" onClick={() => removeRule(rule)} aria-label="Remove rule">
|
|
<Trash2 className="h-3.5 w-3.5 text-muted-foreground" />
|
|
</Button>
|
|
</div>
|
|
))}
|
|
|
|
<div className="space-y-2 border-t pt-3">
|
|
<Input placeholder="Rule name" value={rName}
|
|
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setRName(e.target.value)} />
|
|
<div className="flex gap-2">
|
|
<Select value={rTrigger} onValueChange={(v: string) => setRTrigger(v)}>
|
|
<SelectTrigger className="flex-1" aria-label="Trigger"><SelectValue /></SelectTrigger>
|
|
<SelectContent>
|
|
{Object.entries(TRIGGER_LABELS).map(([k, label]) => (
|
|
<SelectItem key={k} value={k}>{label}</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
<Select value={rChannel} onValueChange={(v: string) => setRChannel(v)}>
|
|
<SelectTrigger className="flex-1" aria-label="Channel"><SelectValue placeholder="Channel" /></SelectTrigger>
|
|
<SelectContent>
|
|
{channels.map(c => (
|
|
<SelectItem key={c.id} value={c.id}>{c.name} ({KIND_META[c.kind]?.label ?? c.kind})</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
{rTrigger === 'bookmark_due' && (
|
|
<label className="flex items-center gap-2 text-xs text-muted-foreground">
|
|
Notify within
|
|
<Input type="number" min={0} max={720} className="w-24" value={rLead}
|
|
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setRLead(parseInt(e.target.value) || 0)} />
|
|
hours of the due date
|
|
</label>
|
|
)}
|
|
<Button onClick={addRule} loading={savingR} size="sm">Create rule</Button>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Recent deliveries */}
|
|
<div className="rounded-lg border p-4 space-y-3">
|
|
<h3 className="font-medium">Recent notifications</h3>
|
|
{history.length === 0 && <p className="text-sm text-muted-foreground">Nothing sent yet.</p>}
|
|
{history.map(n => (
|
|
<div key={n.id} className="flex items-center gap-2 text-sm">
|
|
<Badge variant={n.status === 'sent' ? 'default' : n.status === 'failed' ? 'destructive' : 'secondary'}>
|
|
{n.status}
|
|
</Badge>
|
|
<span className="truncate flex-1">{n.title}</span>
|
|
<span className="text-xs text-muted-foreground shrink-0">{n.ruleName}</span>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|