From 0b7fb0c69d97f74dade8dc59ae0c613f95f20bb2 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 16 Jun 2026 19:53:31 +0800 Subject: [PATCH] =?UTF-8?q?feat(notifications):=20P4=20WebUI=20=E2=80=94?= =?UTF-8?q?=20channel=20manager,=20per-account=20opt-in,=20deliveries=20wi?= =?UTF-8?q?dget?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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. --- .../config/general-settings-tab.tsx | 6 + .../components/config/notification-opt-in.tsx | 84 ++++++ .../components/overview/deliveries-widget.tsx | 83 ++++++ .../src/components/pages/overview-page.tsx | 6 +- .../src/components/pages/settings-page.tsx | 5 +- .../settings/notifications-panel.tsx | 244 ++++++++++++++++++ packages/webui/src/lib/api/client.ts | 23 +- packages/webui/src/lib/api/types.ts | 14 + packages/webui/src/lib/dashboard-layout.ts | 10 +- packages/webui/src/lib/onebot-config.ts | 10 + packages/webui/src/router/index.tsx | 2 +- packages/webui/src/types.ts | 29 +++ 12 files changed, 509 insertions(+), 7 deletions(-) create mode 100644 packages/webui/src/components/config/notification-opt-in.tsx create mode 100644 packages/webui/src/components/overview/deliveries-widget.tsx create mode 100644 packages/webui/src/components/settings/notifications-panel.tsx diff --git a/packages/webui/src/components/config/general-settings-tab.tsx b/packages/webui/src/components/config/general-settings-tab.tsx index 727c1a30..124a392a 100644 --- a/packages/webui/src/components/config/general-settings-tab.tsx +++ b/packages/webui/src/components/config/general-settings-tab.tsx @@ -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

+ + onChange({ ...config, notifications: { channelIds } })} + /> ); } diff --git a/packages/webui/src/components/config/notification-opt-in.tsx b/packages/webui/src/components/config/notification-opt-in.tsx new file mode 100644 index 00000000..3c472b41 --- /dev/null +++ b/packages/webui/src/components/config/notification-opt-in.tsx @@ -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(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 ( +
+
+ +

+ 该账号上线 / 下线时向选中的渠道推送通知。渠道在「设置 → 通知」中全局定义。 +

+
+ + {channels === null ? ( +
+ 加载渠道… +
+ ) : channels.length === 0 ? ( +

还没有全局渠道——先到「设置 → 通知」添加。

+ ) : ( +
+ {channels.map((ch) => ( +
+
+ {ch.name || ch.id} + {!ch.enabled && (已全局禁用)} +

{ch.url}

+
+ toggle(ch.id, v)} + ariaLabel={`为该账号启用渠道 ${ch.name || ch.id}`} + /> +
+ ))} +
+ )} +
+ ); +} diff --git a/packages/webui/src/components/overview/deliveries-widget.tsx b/packages/webui/src/components/overview/deliveries-widget.tsx new file mode 100644 index 00000000..89a252ed --- /dev/null +++ b/packages/webui/src/components/overview/deliveries-widget.tsx @@ -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(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 ( + + + + 最近投递 + + + + {records === null ? ( +

加载中…

+ ) : records.length === 0 ? ( +
+ +

暂无投递记录

+
+ ) : ( +
+ {records.map((r, i) => ( +
+ {r.ok ? ( + + ) : ( + + )} + {formatClock(r.time)} + + {r.event === 'online' ? '上线' : '下线'} + + {r.uin} + + {r.channelId} + {!r.ok && r.error ? ` · ${r.error}` : ''} + +
+ ))} +
+ )} +
+
+ ); +} diff --git a/packages/webui/src/components/pages/overview-page.tsx b/packages/webui/src/components/pages/overview-page.tsx index 586d2042..10eda4ca 100644 --- a/packages/webui/src/components/pages/overview-page.tsx +++ b/packages/webui/src/components/pages/overview-page.tsx @@ -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 ; case 'link': return ; case 'account': return ; + case 'deliveries': return ; 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], ); diff --git a/packages/webui/src/components/pages/settings-page.tsx b/packages/webui/src/components/pages/settings-page.tsx index 3f366a0a..2ee74e48 100644 --- a/packages/webui/src/components/pages/settings-page.tsx +++ b/packages/webui/src/components/pages/settings-page.tsx @@ -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' && } {tab === 'advanced' && } {tab === 'account' && } + {tab === 'notifications' && } {tab === 'about' && } diff --git a/packages/webui/src/components/settings/notifications-panel.tsx b/packages/webui/src/components/settings/notifications-panel.tsx new file mode 100644 index 00000000..64eeafcd --- /dev/null +++ b/packages/webui/src/components/settings/notifications-panel.tsx @@ -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(null); + const [saved, setSaved] = useState(''); + const [loading, setLoading] = useState(true); + const [saving, setSaving] = useState(false); + const [testing, setTesting] = useState(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 ( +
+ 加载中… +
+ ); + } + + const patch = (p: Partial) => setConfig({ ...config, ...p }); + const patchChannel = (i: number, p: Partial) => + 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 ( +
+
+ +

+ 账号上线 / 下线时,向启用的渠道 POST 一条渲染后的通知(机械转发,仅去抖防刷屏)。渠道在此全局定义, + 每个账号在其「配置」页勾选启用哪些。模板变量: + {'{uin}'} {'{nickname}'}{' '} + {'{event}'}(offline/online) {'{time}'}。 +

+
+ + {/* Global debounce */} +
+ + { + const n = Math.trunc(Number(e.target.value)); + patch({ debounceSeconds: Number.isFinite(n) ? Math.min(3600, Math.max(0, n)) : 0 }); + }} + /> +

+ 下线后在该秒数内自愈则不发(抑制闪断);超时才发「下线」,恢复时再发「上线」。0 表示不去抖、立即发。 +

+
+ + {/* Channels */} +
+ {config.channels.length === 0 && ( +

+ 还没有渠道。点下方「新增渠道」添加一个 webhook。 +

+ )} + + {config.channels.map((ch, i) => ( +
+
+
+ patchChannel(i, { enabled: v })} + ariaLabel={`启用渠道 ${ch.name || ch.id}`} + /> + + {ch.name || ch.id || '未命名渠道'} + +
+
+ + +
+
+ +
+
+ + patchChannel(i, { id: e.target.value })} + /> +
+
+ + patchChannel(i, { name: e.target.value })} + /> +
+
+ +
+ + patchChannel(i, { url: e.target.value })} + /> +
+ +
+ +