feat(notifications): P4 WebUI — channel manager, per-account opt-in, deliveries widget

- API client: notifications surface (getConfig/saveConfig/recent/test) + types.
- Settings → 通知 tab: global channel CRUD (id/name/url/body-template/enabled) +
  global debounce window, per-channel test-send, dirty-tracked save; invalid
  channels (bad slug / non-http URL) are dropped server-side and surfaced.
- Per-account 通用设置: opt-in toggles bound to notifications.channelIds, riding
  the ConfigPage's existing debounced autosave; stale opt-ins preserved.
- Overview: opt-in 最近投递 widget (polls /api/notifications/recent, read-only).
  Hidden-by-default set is now DERIVED from the catalogue (defaultVisible) and
  shared by desktop + mobile reconcile — replaces the hardcoded STATIC_WIDGET_IDS
  so a new opt-in widget can't reappear unbidden on existing mobile dashboards.

Typecheck + build green. Adversarial review: 1 should-fix (mobile hidden-set) +
2 nits found, fixed/triaged, and re-verified clean.
This commit is contained in:
DrSmoothl committed 2026-06-16 19:53:31 +08:00
1 parent c0af18e1c2
commit 0b7fb0c69d
12 files changed
+509 -7

No files matched your search

@@ -6,6 +6,7 @@
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { ToggleSwitch } from '@/components/ui/toggle-switch';
import { NotificationOptIn } from '@/components/config/notification-opt-in';
import type { OneBotConfig, StatusCommandConfig } from '@/types';
interface GeneralSettingsTabProps {
@@ -83,6 +84,11 @@ export function GeneralSettingsTab({ config, onChange }: GeneralSettingsTabProps
</p>
</div>
</div>
<NotificationOptIn
selectedIds={config.notifications?.channelIds ?? []}
onChange={(channelIds) => onChange({ ...config, notifications: { channelIds } })}
/>
</div>
);
}
@@ -0,0 +1,84 @@
// Per-account opt-in to the GLOBAL notification channels. Renders the channels
// defined in 设置 → 通知 as toggles; the selection maps to
// OneBotConfig.notifications.channelIds. Lives inside the account's 通用设置 tab,
// so toggling marks the config dirty and rides the parent's debounced autosave.
import { useEffect, useState } from 'react';
import { Loader2 } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { ToggleSwitch } from '@/components/ui/toggle-switch';
import { useApi } from '@/lib/api';
import type { NotificationChannel } from '@/types';
interface NotificationOptInProps {
selectedIds: string[];
onChange: (channelIds: string[]) => void;
}
export function NotificationOptIn({ selectedIds, onChange }: NotificationOptInProps) {
const api = useApi();
const [channels, setChannels] = useState<NotificationChannel[] | null>(null);
useEffect(() => {
let cancelled = false;
void (async () => {
try {
const cfg = await api.notifications.getConfig();
if (!cancelled) setChannels(cfg.channels);
} catch {
if (!cancelled) setChannels([]);
}
})();
return () => {
cancelled = true;
};
}, [api]);
const toggle = (id: string, on: boolean) => {
const set = new Set(selectedIds);
if (on) set.add(id);
else set.delete(id);
// Order known channels by the global list; keep any stale ids (channel
// deleted globally but still opted-in) at the end rather than dropping them.
const known = (channels ?? []).map((c) => c.id).filter((cid) => set.has(cid));
const extra = selectedIds.filter((sid) => set.has(sid) && !known.includes(sid));
onChange([...known, ...extra]);
};
const selected = new Set(selectedIds);
return (
<div className="flex flex-col gap-3 rounded-lg border bg-card/40 p-4">
<div>
<Label>上下线通知渠道</Label>
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
该账号上线 / 下线时向选中的渠道推送通知。渠道在「设置 → 通知」中全局定义。
</p>
</div>
{channels === null ? (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<Loader2 className="size-3.5 animate-spin" /> 加载渠道…
</div>
) : channels.length === 0 ? (
<p className="text-[11px] text-muted-foreground">还没有全局渠道——先到「设置 → 通知」添加。</p>
) : (
<div className="flex flex-col divide-y">
{channels.map((ch) => (
<div key={ch.id} className="flex items-center justify-between gap-3 py-2 first:pt-0 last:pb-0">
<div className="min-w-0">
<span className="text-sm">{ch.name || ch.id}</span>
{!ch.enabled && <span className="ml-2 text-[10px] text-muted-foreground">(已全局禁用)</span>}
<p className="truncate text-[11px] text-muted-foreground">{ch.url}</p>
</div>
<ToggleSwitch
value={selected.has(ch.id)}
onChange={(v) => toggle(ch.id, v)}
ariaLabel={`为该账号启用渠道 ${ch.name || ch.id}`}
/>
</div>
))}
</div>
)}
</div>
);
}
@@ -0,0 +1,83 @@
// Overview widget: the notification subsystem's in-memory delivery history
// (most-recent-first, lost on restart). Opt-in (hidden by default); polls
// /api/notifications/recent. No per-widget config.
import { useEffect, useState } from 'react';
import { Bell, CheckCircle2, XCircle } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { cn } from '@/lib/utils';
import { useApi } from '@/lib/api';
import { useTheme } from '@/contexts/ThemeContext';
import type { NotificationDeliveryRecord } from '@/types';
const POLL_MS = 15_000;
export function DeliveriesWidget() {
const api = useApi();
const { formatClock } = useTheme();
const [records, setRecords] = useState<NotificationDeliveryRecord[] | null>(null);
useEffect(() => {
let active = true;
const pull = () =>
api.notifications
.recent(50)
.then((r) => {
if (active) setRecords(r);
})
.catch(() => {
if (active) setRecords((prev) => prev ?? []);
});
void pull();
const id = window.setInterval(() => void pull(), POLL_MS);
return () => {
active = false;
window.clearInterval(id);
};
}, [api]);
return (
<Card className="flex h-full flex-col">
<CardHeader className="flex flex-row items-center gap-2 space-y-0">
<CardTitle className="flex items-center gap-2">
<Bell className="size-4 text-primary" /> 最近投递
</CardTitle>
</CardHeader>
<CardContent className="min-h-0 flex-1 overflow-auto">
{records === null ? (
<p className="py-10 text-center text-sm text-muted-foreground">加载中…</p>
) : records.length === 0 ? (
<div className="flex flex-col items-center justify-center gap-2 rounded-xl border border-dashed py-10 text-muted-foreground">
<Bell className="size-8 opacity-40" strokeWidth={1.5} />
<p className="text-sm">暂无投递记录</p>
</div>
) : (
<div className="flex flex-col gap-1 text-[11px]">
{records.map((r, i) => (
<div key={i} className="flex items-center gap-2 rounded px-2 py-1 hover:bg-accent/30">
{r.ok ? (
<CheckCircle2 className="size-3.5 shrink-0 text-emerald-500" />
) : (
<XCircle className="size-3.5 shrink-0 text-destructive" />
)}
<span className="shrink-0 font-mono tabular-nums text-muted-foreground">{formatClock(r.time)}</span>
<span
className={cn(
'shrink-0 font-medium',
r.event === 'online' ? 'text-emerald-600' : 'text-amber-600',
)}
>
{r.event === 'online' ? '上线' : '下线'}
</span>
<span className="shrink-0 font-mono">{r.uin}</span>
<span className="ml-auto min-w-0 truncate text-muted-foreground" title={r.error ?? r.channelId}>
{r.channelId}
{!r.ok && r.error ? ` · ${r.error}` : ''}
</span>
</div>
))}
</div>
)}
</CardContent>
</Card>
);
}
@@ -22,7 +22,7 @@ import { useTheme } from '@/contexts/ThemeContext';
import { reconcileLayoutItems, useLayout } from '@/contexts/LayoutContext';
import { useMediaQuery } from '@/hooks/use-media-query';
import {
CONFIGURABLE_WIDGETS, GRID_COLS, GRID_WIDGETS, MOBILE_WIDGET_IDS, STATIC_WIDGET_IDS, mobileHeightOf,
CONFIGURABLE_WIDGETS, GRID_COLS, GRID_WIDGETS, HIDDEN_BY_DEFAULT_IDS, MOBILE_WIDGET_IDS, mobileHeightOf,
parseAccountConfig, parseAlertsConfig, parseConnectionsConfig, parseHostConfig,
parseLinkConfig, parseNoteConfig, parseSessionsConfig, widgetLabel,
type AccountConfig, type AlertsConfig, type ConnectionsConfig, type HostConfig,
@@ -34,6 +34,7 @@ import {
AccountConfigForm, AlertsConfigForm, ConnectionsConfigForm, HostConfigForm,
LinkConfigForm, LINK_ICON_COMPONENTS, NoteConfigForm, SessionsConfigForm,
} from '@/components/pages/widget-config-forms';
import { DeliveriesWidget } from '@/components/overview/deliveries-widget';
function qqAvatarUrl(uin: string) {
return `/avatar/${encodeURIComponent(uin)}`;
@@ -49,6 +50,7 @@ function renderWidget(block: UiLayoutItem): ReactNode {
case 'note': return <NoteWidget config={parseNoteConfig(block.config)} />;
case 'link': return <LinkWidget config={parseLinkConfig(block.config)} />;
case 'account': return <AccountWidget config={parseAccountConfig(block.config)} />;
case 'deliveries': return <DeliveriesWidget />;
default: return null;
}
}
@@ -78,7 +80,7 @@ export function OverviewPage() {
// Reconcile the mobile order against the live widget catalogue (drop unknown,
// append new as visible) — so a widget added later just appears on phones too.
const mobileItems = useMemo(
() => reconcileLayoutItems(overviewMobile, MOBILE_WIDGET_IDS, [], STATIC_WIDGET_IDS),
() => reconcileLayoutItems(overviewMobile, MOBILE_WIDGET_IDS, [], HIDDEN_BY_DEFAULT_IDS),
[overviewMobile],
);
@@ -1,7 +1,7 @@
import { createContext, useContext, useId, useRef, useState, type ReactNode } from 'react';
import { motion } from 'motion/react';
import {
Accessibility, AlertTriangle, Bug, Check, Clock, Code2, Download, ExternalLink, Github, Image as ImageIcon,
Accessibility, AlertTriangle, Bell, Bug, Check, Clock, Code2, Download, ExternalLink, Github, Image as ImageIcon,
Info, KeyRound, Loader2, Monitor, Moon, Palette, PanelTop, Plus, RefreshCw, RotateCcw, ShieldCheck,
Sparkles, Star, Sun, Tag, Upload, Trash2,
} from 'lucide-react';
@@ -40,12 +40,14 @@ import { useApi } from '@/lib/api';
import { useAppState } from '@/contexts/AppStateContext';
import { cn } from '@/lib/utils';
import { settingsRoute, type SettingsTab } from '@/router';
import { NotificationsPanel } from '@/components/settings/notifications-panel';
const TABS: { key: SettingsTab; label: string; icon: typeof Sun }[] = [
{ key: 'appearance', label: '外观', icon: Palette },
{ key: 'data', label: '数据与格式', icon: RefreshCw },
{ key: 'advanced', label: '高级', icon: Code2 },
{ key: 'account', label: '账号安全', icon: ShieldCheck },
{ key: 'notifications', label: '通知', icon: Bell },
{ key: 'about', label: '关于', icon: Info },
];
@@ -76,6 +78,7 @@ export function SettingsPage() {
{tab === 'data' && <DataPanel />}
{tab === 'advanced' && <AdvancedPanel />}
{tab === 'account' && <AccountPanel />}
{tab === 'notifications' && <NotificationsPanel />}
{tab === 'about' && <AboutPanel />}
</motion.div>
</div>
@@ -0,0 +1,244 @@
// Settings → 通知 tab. Global webhook-channel store (CRUD + per-channel test
// send) and the global debounce window. Channels are global; each account opts
// in from its own Config page. The server total-normalizes on save (a channel
// with an invalid slug id or a non-http(s) URL is dropped), so after 保存 the
// list reflects exactly what was accepted.
import { useEffect, useMemo, useState } from 'react';
import { Bell, Loader2, Plus, Send, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { ToggleSwitch } from '@/components/ui/toggle-switch';
import { useApi } from '@/lib/api';
import { cn } from '@/lib/utils';
import type { NotificationChannel, NotificationsConfig } from '@/types';
const DEFAULT_TEMPLATE = '{nickname}({uin}) {event} @ {time}';
function blankChannel(n: number): NotificationChannel {
return { id: `channel-${n}`, name: '', url: '', bodyTemplate: DEFAULT_TEMPLATE, enabled: true };
}
export function NotificationsPanel() {
const api = useApi();
const [config, setConfig] = useState<NotificationsConfig | null>(null);
const [saved, setSaved] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState<string | null>(null);
const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null);
useEffect(() => {
let cancelled = false;
void (async () => {
try {
const cfg = await api.notifications.getConfig();
if (cancelled) return;
setConfig(cfg);
setSaved(JSON.stringify(cfg));
} catch {
if (!cancelled) setMsg({ kind: 'err', text: '加载通知配置失败' });
} finally {
if (!cancelled) setLoading(false);
}
})();
return () => {
cancelled = true;
};
}, [api]);
const dirty = useMemo(() => (config ? JSON.stringify(config) !== saved : false), [config, saved]);
if (loading || !config) {
return (
<div className="flex items-center gap-2 rounded-lg border bg-card/40 p-6 text-sm text-muted-foreground">
<Loader2 className="size-4 animate-spin" /> 加载中…
</div>
);
}
const patch = (p: Partial<NotificationsConfig>) => setConfig({ ...config, ...p });
const patchChannel = (i: number, p: Partial<NotificationChannel>) =>
setConfig({ ...config, channels: config.channels.map((c, idx) => (idx === i ? { ...c, ...p } : c)) });
const addChannel = () => {
// Avoid a default id colliding with an existing one (e.g. after deletes),
// which the server would dedup-drop on save.
const used = new Set(config.channels.map((c) => c.id));
let n = config.channels.length + 1;
while (used.has(`channel-${n}`)) n += 1;
setConfig({ ...config, channels: [...config.channels, blankChannel(n)] });
};
const removeChannel = (i: number) =>
setConfig({ ...config, channels: config.channels.filter((_, idx) => idx !== i) });
const save = async () => {
setSaving(true);
setMsg(null);
try {
const result = await api.notifications.saveConfig(config);
setConfig(result);
setSaved(JSON.stringify(result));
const dropped = config.channels.length - result.channels.length;
setMsg({
kind: 'ok',
text: dropped > 0 ? `已保存(${dropped} 个无效渠道被丢弃,需有效 slug id + http(s) URL)` : '已保存',
});
} catch {
setMsg({ kind: 'err', text: '保存失败,请检查服务器日志' });
} finally {
setSaving(false);
}
};
const test = async (id: string) => {
setTesting(id);
setMsg(null);
try {
const res = await api.notifications.test(id);
setMsg({ kind: res.success ? 'ok' : 'err', text: res.message ?? (res.success ? '测试发送成功' : '测试发送失败') });
} catch {
setMsg({ kind: 'err', text: '测试请求失败' });
} finally {
setTesting(null);
}
};
return (
<div className="flex flex-col gap-4">
<div className="flex items-start gap-2 rounded-lg border bg-card/40 p-4 text-[11px] leading-relaxed text-muted-foreground">
<Bell className="mt-0.5 size-3.5 shrink-0" />
<p>
账号上线 / 下线时,向启用的渠道 POST 一条渲染后的通知(机械转发,仅去抖防刷屏)。渠道在此全局定义,
每个账号在其「配置」页勾选启用哪些。模板变量:
<code className="font-mono">{'{uin}'}</code> <code className="font-mono">{'{nickname}'}</code>{' '}
<code className="font-mono">{'{event}'}</code>(offline/online) <code className="font-mono">{'{time}'}</code>。
</p>
</div>
{/* Global debounce */}
<div className="flex flex-col gap-1.5 rounded-lg border bg-card/40 p-4">
<Label>去抖窗口(秒)</Label>
<Input
type="number"
min={0}
max={3600}
className="w-32 tabular-nums"
value={config.debounceSeconds}
onChange={(e) => {
const n = Math.trunc(Number(e.target.value));
patch({ debounceSeconds: Number.isFinite(n) ? Math.min(3600, Math.max(0, n)) : 0 });
}}
/>
<p className="text-[11px] leading-relaxed text-muted-foreground">
下线后在该秒数内自愈则不发(抑制闪断);超时才发「下线」,恢复时再发「上线」。<code className="font-mono">0</code> 表示不去抖、立即发。
</p>
</div>
{/* Channels */}
<div className="flex flex-col gap-3">
{config.channels.length === 0 && (
<p className="rounded-lg border border-dashed bg-card/20 p-6 text-center text-sm text-muted-foreground">
还没有渠道。点下方「新增渠道」添加一个 webhook。
</p>
)}
{config.channels.map((ch, i) => (
<div key={i} className="flex flex-col gap-3 rounded-lg border bg-card/40 p-4">
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-2">
<ToggleSwitch
value={ch.enabled}
onChange={(v) => patchChannel(i, { enabled: v })}
ariaLabel={`启用渠道 ${ch.name || ch.id}`}
/>
<span className={cn('text-sm font-medium', ch.enabled ? undefined : 'text-muted-foreground')}>
{ch.name || ch.id || '未命名渠道'}
</span>
</div>
<div className="flex items-center gap-1.5">
<Button
type="button"
variant="outline"
size="sm"
disabled={dirty || testing === ch.id}
title={dirty ? '请先保存再测试' : '向该渠道发送一条测试消息'}
onClick={() => void test(ch.id)}
>
{testing === ch.id ? <Loader2 className="size-3.5 animate-spin" /> : <Send className="size-3.5" />}
测试
</Button>
<Button
type="button"
variant="ghost"
size="sm"
aria-label="删除渠道"
onClick={() => removeChannel(i)}
>
<Trash2 className="size-3.5" />
</Button>
</div>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<div className="flex flex-col gap-1.5">
<Label className="text-xs">渠道 ID(slug,账号据此勾选)</Label>
<Input
value={ch.id}
placeholder="dingtalk"
onChange={(e) => patchChannel(i, { id: e.target.value })}
/>
</div>
<div className="flex flex-col gap-1.5">
<Label className="text-xs">显示名</Label>
<Input
value={ch.name}
placeholder="钉钉群机器人"
onChange={(e) => patchChannel(i, { name: e.target.value })}
/>
</div>
</div>
<div className="flex flex-col gap-1.5">
<Label className="text-xs">Webhook URL(http/https)</Label>
<Input
type="url"
value={ch.url}
placeholder="https://oapi.dingtalk.com/robot/send?access_token=…"
onChange={(e) => patchChannel(i, { url: e.target.value })}
/>
</div>
<div className="flex flex-col gap-1.5">
<Label className="text-xs">Body 模板</Label>
<textarea
value={ch.bodyTemplate}
rows={3}
spellCheck={false}
onChange={(e) => patchChannel(i, { bodyTemplate: e.target.value })}
className={cn(
'w-full rounded-md border border-border bg-transparent px-3 py-2 font-mono text-xs leading-relaxed shadow-xs outline-none transition-[color,box-shadow]',
'placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/40',
)}
/>
</div>
</div>
))}
<Button type="button" variant="outline" size="sm" className="self-start" onClick={addChannel}>
<Plus className="size-3.5" /> 新增渠道
</Button>
</div>
{/* Save bar */}
<div className="flex items-center gap-3 border-t pt-4">
<Button type="button" disabled={!dirty || saving} onClick={() => void save()}>
{saving && <Loader2 className="size-3.5 animate-spin" />} 保存
</Button>
{dirty && <span className="text-[11px] text-muted-foreground">有未保存的更改</span>}
{msg && (
<span className={cn('text-xs', msg.kind === 'ok' ? 'text-emerald-500' : 'text-destructive')}>{msg.text}</span>
)}
</div>
</div>
);
}