feat(webui): global-config settings tab + /api/global-config

Adds a '全局配置' Settings tab that edits config/snowluma.json — the rkey
fallback-server list and the deployment-wide musicSignUrl — backed by a new
bearer-gated GET/POST /api/global-config (load/saveGlobalSettings, then
oneBotManager.reloadGlobalSettings to hot-apply to live instances).

The panel reuses the established settings-panel idiom (Input/Button/Label,
debounced auto-save, flash); rkey servers are an inline add/remove list with
client-side http(s) validation hints. It deliberately does not reconcile inputs
from the server's normalized response (would erase a half-typed URL); a
load-failure shows an error+retry, and the save toast says '无效项已忽略' when
the server would drop an entry.

Removes the now-dead per-UIN musicSignUrl form (moved to global in Phase 2).
Phase 3 of the global-settings split (nav grouping is Phase 4).
This commit is contained in:
DrSmoothl committed 2026-06-28 22:16:07 +08:00
1 parent ea1c5ff9eb
commit 196f98e97c
9 files changed
+283 -22

No files matched your search

+27
View File
@@ -3,6 +3,7 @@ import { serveStatic } from '@hono/node-server/serve-static';
import type { HookManager, HookProcessInfo } from '@snowluma/bridge'; import type { HookManager, HookProcessInfo } from '@snowluma/bridge';
import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '@snowluma/common/logger'; import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '@snowluma/common/logger';
import { loadOneBotConfig, saveOneBotConfig } from '@snowluma/onebot/config'; import { loadOneBotConfig, saveOneBotConfig } from '@snowluma/onebot/config';
import { loadGlobalSettings, saveGlobalSettings } from '@snowluma/onebot/global-config';
import type { OneBotManager } from '@snowluma/onebot/manager'; import type { OneBotManager } from '@snowluma/onebot/manager';
import type { OneBotConfig, JsonObject as OneBotJsonObject } from '@snowluma/onebot/types'; import type { OneBotConfig, JsonObject as OneBotJsonObject } from '@snowluma/onebot/types';
import { readRuntimeConfig, updateRuntimeConfig, resolveRuntimeEnvOverrides } from '@snowluma/common/runtime'; import { readRuntimeConfig, updateRuntimeConfig, resolveRuntimeEnvOverrides } from '@snowluma/common/runtime';
@@ -1247,6 +1248,32 @@ export async function initWebUI(
}); });
}); });
// ─── Global deployment config (config/snowluma.json) ─────────────────────
// All-accounts SnowLuma knobs (rkey fallback servers + musicSignUrl). Saving
// section-merges + normalizes server-side, then hot-reloads every instance.
app.get('/api/global-config', (c) => c.json({ config: loadGlobalSettings() }));
app.post('/api/global-config', async (c) => {
const declaredLen = Number(c.req.header('content-length'));
if (Number.isFinite(declaredLen) && declaredLen > 512 * 1024) {
return c.json({ success: false, message: '配置过大' }, 413);
}
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
try {
const config = saveGlobalSettings(body);
oneBotManager.reloadGlobalSettings();
return c.json({ success: true, config });
} catch (err) {
log.warn('save global config failed: %s', err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500);
}
});
// ─── WebUI customization config (config/ui.json) ───────────────────────── // ─── WebUI customization config (config/ui.json) ─────────────────────────
// Appearance (A) + layout (C). The full config is bearer-gated; only the // Appearance (A) + layout (C). The full config is bearer-gated; only the
// cosmetic appearance subset is exposed unauthenticated for the login page. // cosmetic appearance subset is exposed unauthenticated for the login page.
@@ -1,7 +1,8 @@
// "通用设置" tab — fields that apply to the whole OneBotInstance rather // "通用设置" tab — per-account fields that apply to the whole OneBotInstance
// than any specific adapter: the music-sign service URL and the built-in // rather than any specific adapter: the built-in `#sl` status command and the
// `#sl` status command. Edits here mark the config dirty and are // notification opt-in. Edits here mark the config dirty and are auto-saved with
// auto-saved with debounce by the parent ConfigPage. // debounce by the parent ConfigPage. (Deployment-wide knobs like the music-sign
// URL live in Settings → 全局配置, not here.)
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label'; import { Label } from '@/components/ui/label';
@@ -21,19 +22,6 @@ export function GeneralSettingsTab({ config, onChange }: GeneralSettingsTabProps
return ( return (
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<div className="flex flex-col gap-1.5 rounded-lg border bg-card/40 p-4">
<Label>音乐签名服务 URL</Label>
<Input
type="url"
placeholder="留空则不启用"
value={config.musicSignUrl ?? ''}
onChange={(e) => onChange({ ...config, musicSignUrl: e.target.value || undefined })}
/>
<p className="text-[11px] leading-relaxed text-muted-foreground">
用于音乐分享卡片签名。未配置时音乐相关消息段会回落为普通文本。
</p>
</div>
<div className="flex flex-col gap-4 rounded-lg border bg-card/40 p-4"> <div className="flex flex-col gap-4 rounded-lg border bg-card/40 p-4">
<div className="flex items-start justify-between gap-3"> <div className="flex items-start justify-between gap-3">
<div className="min-w-0"> <div className="min-w-0">
@@ -3,7 +3,7 @@ import { motion } from 'motion/react';
import { import {
Accessibility, AlertTriangle, Bell, 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, Server, ShieldCheck, Info, KeyRound, Loader2, Monitor, Moon, Palette, PanelTop, Plus, RefreshCw, RotateCcw, Server, ShieldCheck,
Sparkles, Star, Sun, Tag, Upload, Trash2, SlidersHorizontal, Sparkles, Star, Sun, Tag, Upload, Trash2,
} from 'lucide-react'; } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'; import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
@@ -42,6 +42,7 @@ import { useAppState } from '@/contexts/AppStateContext';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { settingsRoute, type SettingsTab } from '@/router'; import { settingsRoute, type SettingsTab } from '@/router';
import { NotificationsPanel } from '@/components/settings/notifications-panel'; import { NotificationsPanel } from '@/components/settings/notifications-panel';
import { GlobalConfigPanel } from '@/components/settings/global-config-panel';
import { SystemPanel } from '@/components/settings/system-panel'; import { SystemPanel } from '@/components/settings/system-panel';
const TABS: { key: SettingsTab; label: string; icon: typeof Sun }[] = [ const TABS: { key: SettingsTab; label: string; icon: typeof Sun }[] = [
@@ -51,6 +52,7 @@ const TABS: { key: SettingsTab; label: string; icon: typeof Sun }[] = [
{ key: 'account', label: '账号安全', icon: ShieldCheck }, { key: 'account', label: '账号安全', icon: ShieldCheck },
{ key: 'system', label: '服务', icon: Server }, { key: 'system', label: '服务', icon: Server },
{ key: 'notifications', label: '通知', icon: Bell }, { key: 'notifications', label: '通知', icon: Bell },
{ key: 'globalConfig', label: '全局配置', icon: SlidersHorizontal },
{ key: 'about', label: '关于', icon: Info }, { key: 'about', label: '关于', icon: Info },
]; ];
@@ -83,6 +85,7 @@ export function SettingsPage() {
{tab === 'account' && <AccountPanel />} {tab === 'account' && <AccountPanel />}
{tab === 'system' && <SystemPanel />} {tab === 'system' && <SystemPanel />}
{tab === 'notifications' && <NotificationsPanel />} {tab === 'notifications' && <NotificationsPanel />}
{tab === 'globalConfig' && <GlobalConfigPanel />}
{tab === 'about' && <AboutPanel />} {tab === 'about' && <AboutPanel />}
</motion.div> </motion.div>
</div> </div>
@@ -0,0 +1,210 @@
// Settings → 全局配置 tab. Deployment-wide SnowLuma knobs (config/snowluma.json):
// rkey fallback servers + the music-card signing URL. Same UX as the other
// settings panels — debounced auto-save, no explicit save button. Unlike the
// channel editor these are typed inline, so the server's normalized result is
// NOT written back onto the inputs while editing (that would erase a half-typed
// URL); the store reconciles on the next load. Invalid entries are flagged
// client-side and simply dropped by the server on save.
import { useCallback, useEffect, useRef, useState } from 'react';
import { AlertTriangle, KeyRound, Loader2, Music, Plus, RefreshCw, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useApi } from '@/lib/api';
import { cn } from '@/lib/utils';
import type { GlobalSettings } from '@/types';
const MUSIC_SIGN_DEFAULT = 'https://ss.xingzhige.com/music_card/card';
function isHttpUrl(value: string): boolean {
try {
const u = new URL(value);
return (u.protocol === 'http:' || u.protocol === 'https:') && u.host.length > 0;
} catch {
return false;
}
}
export function GlobalConfigPanel() {
const api = useApi();
const [config, setConfig] = useState<GlobalSettings | null>(null);
const [loading, setLoading] = useState(true);
const [loadFailed, setLoadFailed] = useState(false);
const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null);
const saveTimer = useRef<number | null>(null);
const msgTimer = useRef<number | null>(null);
const saveGen = useRef(0);
const load = useCallback(async () => {
setLoading(true);
setLoadFailed(false);
try {
setConfig(await api.globalConfig.get());
} catch {
setLoadFailed(true);
} finally {
setLoading(false);
}
}, [api]);
useEffect(() => {
void load();
}, [load]);
useEffect(
() => () => {
if (saveTimer.current) clearTimeout(saveTimer.current);
if (msgTimer.current) clearTimeout(msgTimer.current);
},
[],
);
const flash = (kind: 'ok' | 'err', text: string) => {
setMsg({ kind, text });
if (msgTimer.current) clearTimeout(msgTimer.current);
msgTimer.current = window.setTimeout(() => setMsg(null), 2400);
};
/** Apply locally + debounced auto-save. Deliberately does NOT reconcile the
* inputs from the server's normalized response (it would wipe a half-typed
* URL); a generation guard just confirms the latest save. */
const commit = (next: GlobalSettings) => {
setConfig(next);
const gen = ++saveGen.current;
if (saveTimer.current) clearTimeout(saveTimer.current);
saveTimer.current = window.setTimeout(() => {
void api.globalConfig
.save(next)
.then(() => {
if (saveGen.current !== gen) return;
// The server drops invalid (non-http) entries; say so rather than a
// bare "已保存" next to a still-visible rejected value.
const dropped = next.rkey.fallbackServers.some((s) => s.trim() && !isHttpUrl(s.trim()))
|| (next.musicSignUrl.trim().length > 0 && !isHttpUrl(next.musicSignUrl.trim()));
flash('ok', dropped ? '已保存(无效项已忽略)' : '已保存');
})
.catch(() => {
if (saveGen.current !== gen) return;
flash('err', '保存失败,请检查服务器日志');
});
}, 500);
};
if (loading) {
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>
);
}
if (loadFailed || !config) {
return (
<div className="flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed py-16 text-muted-foreground">
<AlertTriangle className="size-8 opacity-40" strokeWidth={1.5} />
<p className="text-sm">加载全局配置失败</p>
<Button variant="outline" size="sm" onClick={() => void load()}>
<RefreshCw className="size-3.5" /> 重试
</Button>
</div>
);
}
const servers = config.rkey.fallbackServers;
const setServers = (next: string[]) => commit({ ...config, rkey: { fallbackServers: next } });
return (
<div className="flex flex-col gap-4">
{/* rkey fallback servers */}
<div className="flex flex-col gap-4 rounded-xl border bg-card/40 p-4">
<div className="flex items-start gap-2 text-[11px] leading-relaxed text-muted-foreground">
<KeyRound className="mt-0.5 size-3.5 shrink-0" />
<p>
图片 / 文件下载链接需要服务器签发的 <code className="font-mono">rkey</code>。SnowLuma 默认走内核获取;
当内核在你的环境下持续取不到时,会按顺序向这里配置的 HTTP 端点回退。
<strong className="font-medium text-foreground/80">默认留空=关闭</strong>,不配置就不会联系任何第三方。
建议填你自建的端点。
</p>
</div>
<div className="flex flex-col gap-2 border-t pt-3">
<div className="flex items-center justify-between">
<Label>rkey 回退服务器</Label>
<Button variant="outline" size="sm" onClick={() => setServers([...servers, ''])}>
<Plus className="size-3.5" /> 添加
</Button>
</div>
{servers.length === 0 ? (
<p className="rounded-lg border border-dashed px-3 py-4 text-center text-xs text-muted-foreground">
未配置回退服务器(rkey 回退已关闭)
</p>
) : (
<div className="flex flex-col gap-2">
{servers.map((url, i) => {
const invalid = url.trim().length > 0 && !isHttpUrl(url.trim());
return (
<div key={i} className="flex items-center gap-2">
<Input
type="url"
inputMode="url"
spellCheck={false}
placeholder="https://your-rkey-server.example/rkeys"
value={url}
aria-invalid={invalid}
className={cn('font-mono text-xs', invalid && 'border-destructive focus-visible:ring-destructive')}
onChange={(e) => setServers(servers.map((s, idx) => (idx === i ? e.target.value : s)))}
/>
<Button
variant="ghost"
size="icon-sm"
aria-label="删除"
className="shrink-0 text-muted-foreground hover:text-destructive"
onClick={() => setServers(servers.filter((_, idx) => idx !== i))}
>
<Trash2 className="size-4" />
</Button>
</div>
);
})}
<p className="text-[11px] leading-relaxed text-muted-foreground">
端点需返回 <code className="font-mono">{'{ group_rkey, private_rkey, expired_time }'}</code>
(兼容 NapCat rkey 服务格式)。非 http(s) 链接会被忽略。
</p>
</div>
)}
</div>
</div>
{/* music sign URL */}
<div className="flex flex-col gap-4 rounded-xl border bg-card/40 p-4">
<div className="flex items-start gap-2 text-[11px] leading-relaxed text-muted-foreground">
<Music className="mt-0.5 size-3.5 shrink-0" />
<p>音乐分享卡片的签名服务,对所有账号统一生效。留空则使用内置默认服务。</p>
</div>
<div className="flex flex-col gap-1.5 border-t pt-3">
<Label>音乐签名服务 URL</Label>
<Input
type="url"
inputMode="url"
spellCheck={false}
placeholder={MUSIC_SIGN_DEFAULT}
value={config.musicSignUrl}
aria-invalid={config.musicSignUrl.trim().length > 0 && !isHttpUrl(config.musicSignUrl.trim())}
className={cn(
'font-mono text-xs',
config.musicSignUrl.trim().length > 0 && !isHttpUrl(config.musicSignUrl.trim())
&& 'border-destructive focus-visible:ring-destructive',
)}
onChange={(e) => commit({ ...config, musicSignUrl: e.target.value })}
/>
<p className="text-[11px] leading-relaxed text-muted-foreground">
内置默认:<code className="font-mono">{MUSIC_SIGN_DEFAULT}</code>
</p>
</div>
</div>
{msg && <p className={cn('text-xs', msg.kind === 'ok' ? 'text-success' : 'text-destructive')}>{msg.text}</p>}
</div>
);
}
+14 -1
View File
@@ -1,4 +1,4 @@
import type { AccountConnections, BackupBundle, BackupImportResult, DebugActionDoc, DebugInvokeResult, DebugStreamMessage, HookProcessInfo, LogEntry, LogLevel, NotificationDeliveryRecord, NotificationsConfig, QQInfo, SystemInfo, SystemSettingsPatch, SystemSettingsResponse, UiAppearance, UiConfig, UpdateInfo } from '@/types'; import type { AccountConnections, BackupBundle, BackupImportResult, DebugActionDoc, DebugInvokeResult, DebugStreamMessage, GlobalSettings, HookProcessInfo, LogEntry, LogLevel, NotificationDeliveryRecord, NotificationsConfig, QQInfo, SystemInfo, SystemSettingsPatch, SystemSettingsResponse, UiAppearance, UiConfig, UpdateInfo } from '@/types';
import type { PasswordRule } from '@/components/pages/change-password-page'; import type { PasswordRule } from '@/components/pages/change-password-page';
import { normalizeOneBotConfig } from '@/lib/onebot-config'; import { normalizeOneBotConfig } from '@/lib/onebot-config';
import { import {
@@ -48,6 +48,7 @@ class HttpApiClient implements ApiClient {
readonly update: ApiClient['update']; readonly update: ApiClient['update'];
readonly ui: ApiClient['ui']; readonly ui: ApiClient['ui'];
readonly notifications: ApiClient['notifications']; readonly notifications: ApiClient['notifications'];
readonly globalConfig: ApiClient['globalConfig'];
readonly systemSettings: ApiClient['systemSettings']; readonly systemSettings: ApiClient['systemSettings'];
readonly debug: ApiClient['debug']; readonly debug: ApiClient['debug'];
readonly agreements: ApiClient['agreements']; readonly agreements: ApiClient['agreements'];
@@ -190,6 +191,18 @@ class HttpApiClient implements ApiClient {
}), }),
}; };
this.globalConfig = {
get: () =>
this.getJson<{ config: GlobalSettings }>('/api/global-config').then((d) => d.config),
save: async (config) => {
const data = await this.postJson<{ success: boolean; config: GlobalSettings }>(
'/api/global-config',
config,
);
return data.config;
},
};
this.agreements = { this.agreements = {
get: () => this.getJson<AgreementsPayload>('/api/agreements'), get: () => this.getJson<AgreementsPayload>('/api/agreements'),
recordConsent: async (version) => { recordConsent: async (version) => {
+9
View File
@@ -5,6 +5,7 @@ import type {
DebugActionDoc, DebugActionDoc,
DebugInvokeResult, DebugInvokeResult,
DebugStreamMessage, DebugStreamMessage,
GlobalSettings,
HookProcessInfo, HookProcessInfo,
LogEntry, LogEntry,
LogLevel, LogLevel,
@@ -167,6 +168,14 @@ export interface ApiClient {
test(channelId: string): Promise<{ success: boolean; message?: string; status?: number }>; test(channelId: string): Promise<{ success: boolean; message?: string; status?: number }>;
}; };
// ---- global deployment config (rkey fallback servers + musicSignUrl) ----
globalConfig: {
/** Fetch the all-accounts global settings (config/snowluma.json). Bearer-gated. */
get(): Promise<GlobalSettings>;
/** Persist global settings (section-merged + normalized server-side). */
save(config: Partial<GlobalSettings>): Promise<GlobalSettings>;
};
// ---- update check ---- // ---- update check ----
update: { update: {
/** Advisory check for a newer stable release. Read-only — never downloads. */ /** Advisory check for a newer stable release. Read-only — never downloads. */
-1
View File
@@ -62,7 +62,6 @@ export function normalizeOneBotConfig(raw: unknown): OneBotConfig {
wsServers: list(nets.wsServers) as unknown as OneBotConfig['networks']['wsServers'], wsServers: list(nets.wsServers) as unknown as OneBotConfig['networks']['wsServers'],
wsClients: list(nets.wsClients) as unknown as OneBotConfig['networks']['wsClients'], wsClients: list(nets.wsClients) as unknown as OneBotConfig['networks']['wsClients'],
}, },
musicSignUrl: typeof cfg.musicSignUrl === 'string' ? cfg.musicSignUrl : undefined,
statusCommand: normalizeStatusCommand(cfg.statusCommand), statusCommand: normalizeStatusCommand(cfg.statusCommand),
notifications: normalizeNotifications(cfg.notifications), notifications: normalizeNotifications(cfg.notifications),
}; };
+1 -1
View File
@@ -74,7 +74,7 @@ const debugRoute = createRoute({
}); });
/** Settings sub-tabs — also the contract for the `?tab=` deep link. */ /** Settings sub-tabs — also the contract for the `?tab=` deep link. */
export const SETTINGS_TABS = ['appearance', 'data', 'advanced', 'account', 'system', 'notifications', 'about'] as const; export const SETTINGS_TABS = ['appearance', 'data', 'advanced', 'account', 'system', 'notifications', 'globalConfig', 'about'] as const;
export type SettingsTab = (typeof SETTINGS_TABS)[number]; export type SettingsTab = (typeof SETTINGS_TABS)[number];
export const settingsRoute = createRoute({ export const settingsRoute = createRoute({
+13 -1
View File
@@ -107,12 +107,24 @@ export interface StatusCommandConfig {
export interface OneBotConfig { export interface OneBotConfig {
networks: OneBotNetworks; networks: OneBotNetworks;
musicSignUrl?: string;
statusCommand: StatusCommandConfig; statusCommand: StatusCommandConfig;
/** Per-account opt-in to global notification channels (by channel id). */ /** Per-account opt-in to global notification channels (by channel id). */
notifications?: { channelIds: string[] }; notifications?: { channelIds: string[] };
} }
// ─── Global deployment settings (config/snowluma.json) ──────────────────────
// All-accounts SnowLuma knobs that aren't per-UIN: rkey fallback servers and
// the music-card signing endpoint. Mirrors @snowluma/onebot/global-config.
export interface RKeyConfig {
fallbackServers: string[];
}
export interface GlobalSettings {
rkey: RKeyConfig;
/** Music-card signing service URL. Empty = built-in default. */
musicSignUrl: string;
}
// ─── Notifications (account up/down webhooks) ─────────────────────────────── // ─── Notifications (account up/down webhooks) ───────────────────────────────
export type NotificationEventKind = 'offline' | 'online'; export type NotificationEventKind = 'offline' | 'online';