feat(webui): improve operation feedback

Keep confirmations in dialogs while showing clear progress and results for long-running actions.

Auto-close completed notices, preserve important outcomes across reloads, and avoid noise from routine edits.
This commit is contained in:
DrSmoothl committed 2026-07-31 15:35:03 +08:00
1 parent b099dbe8cd
commit b982927b4a
20 files changed
+1863 -222

No files matched your search

@@ -10,6 +10,7 @@ import { AlertTriangle, KeyRound, Loader2, Music, Plus, RefreshCw, Trash2 } from
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useActionFeedback } from '@/contexts/ActionFeedbackContext';
import { useApi } from '@/lib/api';
import { useFlashMessage } from '@/hooks/use-flash-message';
import { cn } from '@/lib/utils';
@@ -28,6 +29,7 @@ function isHttpUrl(value: string): boolean {
export function GlobalConfigPanel() {
const api = useApi();
const { runAction } = useActionFeedback();
const [config, setConfig] = useState<GlobalSettings | null>(null);
const [loading, setLoading] = useState(true);
const [loadFailed, setLoadFailed] = useState(false);
@@ -61,23 +63,41 @@ export function GlobalConfigPanel() {
/** 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) => {
const commit = (
next: GlobalSettings,
feedback: false | { title: string; successTitle: string } = {
title: '正在更新全局配置',
successTitle: '全局配置已更新',
},
) => {
setConfig(next);
const gen = ++saveGen.current;
if (saveTimer.current) clearTimeout(saveTimer.current);
saveTimer.current = window.setTimeout(() => {
void api.globalConfig
.save(next)
const dropped = next.rkey.fallbackServers.some((s) => s.trim() && !isHttpUrl(s.trim()))
|| (next.musicSignUrl.trim().length > 0 && !isHttpUrl(next.musicSignUrl.trim()));
const save = feedback === false
? api.globalConfig.save(next)
: runAction(
{
title: feedback.title,
detail: '正在同步 config/snowluma.json',
successTitle: feedback.successTitle,
successDetail: dropped ? '已保存,无效项已忽略' : '配置已同步',
errorTitle: '全局配置更新失败',
},
() => api.globalConfig.save(next),
);
void save
.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(() => {
.catch((error) => {
if (saveGen.current !== gen) return;
console.error('save global config failed', error);
flash('err', '保存失败,请检查服务器日志');
});
}, 500);
@@ -104,7 +124,8 @@ export function GlobalConfigPanel() {
}
const servers = config.rkey.fallbackServers;
const setServers = (next: string[]) => commit({ ...config, rkey: { fallbackServers: next } });
const setServers = (next: string[]) =>
commit({ ...config, rkey: { fallbackServers: next } }, false);
return (
<div className="flex flex-col gap-4">
@@ -123,7 +144,11 @@ export function GlobalConfigPanel() {
<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, ''])}>
<Button
variant="outline"
size="sm"
onClick={() => setServers([...servers, ''])}
>
<Plus className="size-3.5" /> 添加
</Button>
</div>
@@ -10,6 +10,7 @@ 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 { useActionFeedback } from '@/contexts/ActionFeedbackContext';
import { useApi } from '@/lib/api';
import { useFlashMessage } from '@/hooks/use-flash-message';
import { useTheme } from '@/contexts/ThemeContext';
@@ -38,6 +39,7 @@ interface DialogState {
export function NotificationsPanel() {
const api = useApi();
const { runAction } = useActionFeedback();
const [config, setConfig] = useState<NotificationsConfig | null>(null);
const [loading, setLoading] = useState(true);
const [dialog, setDialog] = useState<DialogState>({ open: false, index: null, seed: blankChannel([]) });
@@ -72,13 +74,27 @@ export function NotificationsPanel() {
/** Apply locally + debounced auto-save. A generation guard reconciles with
* the server's normalized result only if no newer edit landed meanwhile. */
const commit = (next: NotificationsConfig) => {
const commit = (
next: NotificationsConfig,
copy: { title: string; successTitle: string } = {
title: '正在更新通知配置',
successTitle: '通知配置已更新',
},
) => {
setConfig(next);
const gen = ++saveGen.current;
if (saveTimer.current) clearTimeout(saveTimer.current);
saveTimer.current = window.setTimeout(() => {
void api.notifications
.saveConfig(next)
void runAction(
{
title: copy.title,
detail: '正在同步通知渠道设置',
successTitle: copy.successTitle,
successDetail: '通知配置已同步',
errorTitle: '通知配置更新失败',
},
() => api.notifications.saveConfig(next),
)
.then((result) => {
// Only the latest save reconciles + confirms; a superseded in-flight
// save stays silent (its successor will confirm).
@@ -86,7 +102,10 @@ export function NotificationsPanel() {
setConfig(result);
flash('ok', '已保存');
})
.catch(() => flash('err', '保存失败,请检查服务器日志'));
.catch((error) => {
console.error('save notifications config failed', error);
flash('err', '保存失败,请检查服务器日志');
});
}, 350);
};
@@ -99,14 +118,26 @@ export function NotificationsPanel() {
}
const channels = config.channels;
const setChannels = (next: NotificationChannel[]) => commit({ ...config, channels: next });
const setChannels = (
next: NotificationChannel[],
copy?: { title: string; successTitle: string },
) => commit({ ...config, channels: next }, copy);
const otherIds = (index: number | null) => channels.filter((_, i) => i !== index).map((c) => c.id);
const openCreate = () => setDialog({ open: true, index: null, seed: blankChannel(channels) });
const openEdit = (i: number) => setDialog({ open: true, index: i, seed: channels[i] });
const submitChannel = (ch: NotificationChannel) => {
if (dialog.index == null) setChannels([...channels, ch]);
else setChannels(channels.map((c, idx) => (idx === dialog.index ? ch : c)));
if (dialog.index == null) {
setChannels(
[...channels, ch],
{ title: '正在新增通知渠道', successTitle: '通知渠道已新增' },
);
} else {
setChannels(
channels.map((c, idx) => (idx === dialog.index ? ch : c)),
{ title: '正在更新通知渠道', successTitle: '通知渠道已更新' },
);
}
};
const test = async (id: string) => {
@@ -117,10 +148,23 @@ export function NotificationsPanel() {
saveTimer.current = null;
}
try {
await api.notifications.saveConfig(config);
const res = await api.notifications.test(id);
const res = await runAction(
{
title: '正在测试通知渠道',
detail: id,
successTitle: '测试通知已发送',
successDetail: id,
errorTitle: '通知渠道测试失败',
resultError: (result) => result.success ? null : result.message || '测试发送失败',
},
async () => {
await api.notifications.saveConfig(config);
return api.notifications.test(id);
},
);
flash(res.success ? 'ok' : 'err', res.message ?? (res.success ? '测试发送成功' : '测试发送失败'));
} catch {
} catch (error) {
console.error('test notification channel failed', error);
flash('err', '测试请求失败');
} finally {
setTesting(null);
@@ -182,10 +226,16 @@ export function NotificationsPanel() {
key={ch.id}
channel={ch}
testing={testing === ch.id}
onToggle={(v) => setChannels(channels.map((c, idx) => (idx === i ? { ...c, enabled: v } : c)))}
onToggle={(v) => setChannels(
channels.map((c, idx) => (idx === i ? { ...c, enabled: v } : c)),
{ title: '正在更新通知渠道', successTitle: '通知渠道已更新' },
)}
onTest={() => void test(ch.id)}
onEdit={() => openEdit(i)}
onDelete={() => setChannels(channels.filter((_, idx) => idx !== i))}
onDelete={() => setChannels(
channels.filter((_, idx) => idx !== i),
{ title: '正在删除通知渠道', successTitle: '通知渠道已删除' },
)}
/>
))}
</div>
@@ -18,16 +18,9 @@ import {
type LucideIcon,
} from 'lucide-react';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Badge, type BadgeProps } from '@/components/ui/badge';
Badge,
type BadgeProps,
} from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
@@ -35,6 +28,7 @@ import { Label } from '@/components/ui/label';
import { Progress } from '@/components/ui/progress';
import { ToggleSwitch } from '@/components/ui/toggle-switch';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { useActionFeedback } from '@/contexts/ActionFeedbackContext';
import { useFlashMessage } from '@/hooks/use-flash-message';
import { useApi } from '@/lib/api';
import {
@@ -53,6 +47,7 @@ import {
type LogStorageSettings,
type LogStorageSettingsField,
type StorageCleanupRequest,
type StorageCleanupResponse,
type StorageOverviewResponse,
} from '@/types';
@@ -90,6 +85,7 @@ interface PendingCleanup {
export function StoragePanel() {
const api = useApi();
const { runAction } = useActionFeedback();
const [data, setData] = useState<StorageOverviewResponse | null>(null);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
@@ -159,13 +155,21 @@ export function StoragePanel() {
data.settings.envOverrides,
);
if (Object.keys(patch).length === 0) {
flash('ok', '没有需要保存的更改');
return;
}
setSaving(true);
try {
const result = await api.storage.saveSettings(patch);
const result = await runAction(
{
title: '正在更新日志策略',
detail: '正在保存并应用存储限制',
successTitle: '日志策略已更新',
successDetail: '新策略已立即生效',
errorTitle: '日志策略更新失败',
},
() => api.storage.saveSettings(patch),
);
applyOverview({
settings: result.settings,
snapshot: result.snapshot,
@@ -185,7 +189,17 @@ export function StoragePanel() {
const key = cleanupKey(request);
setOperation(key);
try {
const result = await api.storage.cleanup(request);
const result = await runAction(
{
title: '正在清理存储数据',
detail: cleanupLabel(request),
successTitle: '存储数据清理完成',
successDetail: cleanupResultSummary,
errorTitle: '存储数据清理失败',
resultError: (outcome) => outcome.success ? null : cleanupResultSummary(outcome),
},
() => api.storage.cleanup(request),
);
if (result.snapshot) {
setData((previous) => previous
? {
@@ -197,17 +211,7 @@ export function StoragePanel() {
} else {
await load();
}
const summary = [
`删除 ${result.cleanup.deletedFiles} 个文件`,
`释放 ${formatBytes(result.cleanup.freedBytes)}`,
];
if ('skippedActiveItems' in result.cleanup && result.cleanup.skippedActiveItems > 0) {
summary.push(`跳过 ${result.cleanup.skippedActiveItems} 个活动传输`);
}
if (result.cleanup.failures.length > 0) {
summary.push(`${result.cleanup.failures.length} 项失败`);
}
flash(result.success ? 'ok' : 'err', summary.join(','));
flash(result.success ? 'ok' : 'err', cleanupResultSummary(result));
return result.success;
} catch (error) {
flash('err', error instanceof Error ? error.message : '清理失败');
@@ -741,23 +745,20 @@ function AllAccountsCleanupDialog({
onOpenChange(false);
};
return (
<AlertDialog
<ConfirmDialog
open={open}
onOpenChange={(nextOpen) => {
if (!nextOpen && !busy) close();
}}
>
<AlertDialogContent className="max-h-[calc(100dvh-2rem)] w-[calc(100%-2rem)] max-w-md overflow-y-auto p-5 sm:p-6">
<AlertDialogHeader>
<AlertDialogTitle>
清理全部账号的{category ? CATEGORY_INFO[category].label : '数据'}?
</AlertDialogTitle>
<AlertDialogDescription className="leading-relaxed">
该操作会删除所有离线账号的对应数据库及边车文件,无法撤销。请输入
<strong className="mx-1 text-foreground">{ALL_ACCOUNTS_CONFIRMATION}</strong>
继续。
</AlertDialogDescription>
</AlertDialogHeader>
title={`清理全部账号的${category ? CATEGORY_INFO[category].label : '数据'}?`}
description={
<>
该操作会删除所有离线账号的对应数据库及边车文件,无法撤销。请输入
<strong className="mx-1 text-foreground">{ALL_ACCOUNTS_CONFIRMATION}</strong>
继续。
</>
}
content={(
<div className="flex flex-col gap-1.5">
<Label htmlFor="all-account-cleanup-confirmation">确认短语</Label>
<Input
@@ -769,25 +770,16 @@ function AllAccountsCleanupDialog({
disabled={busy}
/>
</div>
<AlertDialogFooter>
<AlertDialogCancel disabled={busy} onClick={() => setConfirmation('')}>
取消
</AlertDialogCancel>
<AlertDialogAction
disabled={!isAllAccountsConfirmation(confirmation) || busy || !category}
onClick={(event) => {
event.preventDefault();
if (!category || !isAllAccountsConfirmation(confirmation)) return;
void onConfirm(category);
}}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{busy ? <Loader2 className="size-4 animate-spin" /> : <Trash2 className="size-4" />}
确认清理
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)}
confirmText="确认清理"
destructive
confirmDisabled={!isAllAccountsConfirmation(confirmation) || busy || !category}
onConfirm={async () => {
if (!category || !isAllAccountsConfirmation(confirmation)) return;
await onConfirm(category);
setConfirmation('');
}}
/>
);
}
@@ -797,6 +789,27 @@ function cleanupKey(request: StorageCleanupRequest): string {
return request.scope;
}
function cleanupLabel(request: StorageCleanupRequest): string {
if (request.scope === 'logs') return '全部日志';
if (request.scope === 'temporary') return '非活动文件传输临时数据';
const label = CATEGORY_INFO[request.category].label;
return request.scope === 'allAccounts' ? `全部账号的${label}` : `账号 ${request.uin} 的${label}`;
}
function cleanupResultSummary(result: StorageCleanupResponse): string {
const summary = [
`删除 ${result.cleanup.deletedFiles} 个文件`,
`释放 ${formatBytes(result.cleanup.freedBytes)}`,
];
if ('skippedActiveItems' in result.cleanup && result.cleanup.skippedActiveItems > 0) {
summary.push(`跳过 ${result.cleanup.skippedActiveItems} 个活动传输`);
}
if (result.cleanup.failures.length > 0) {
summary.push(`${result.cleanup.failures.length} 项失败`);
}
return summary.join(',');
}
function toneBadgeVariant(tone: StorageTone): BadgeProps['variant'] {
if (tone === 'success') return 'success';
if (tone === 'warning') return 'warning';
@@ -15,6 +15,8 @@ import { Label } from '@/components/ui/label';
import { Select } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { ToggleSwitch } from '@/components/ui/toggle-switch';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { useActionFeedback } from '@/contexts/ActionFeedbackContext';
import { useApi } from '@/lib/api';
import { useFlashMessage } from '@/hooks/use-flash-message';
import { cn } from '@/lib/utils';
@@ -22,6 +24,7 @@ import type { SystemSettingsResponse } from '@/types';
export function SystemPanel() {
const api = useApi();
const { runAction } = useActionFeedback();
const [data, setData] = useState<SystemSettingsResponse | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
@@ -41,6 +44,8 @@ export function SystemPanel() {
// backup / restore
const [exportCreds, setExportCreds] = useState(false);
const [restoreCreds, setRestoreCreds] = useState(false);
const [confirmDeleteCert, setConfirmDeleteCert] = useState(false);
const [pendingBackup, setPendingBackup] = useState<File | null>(null);
const fileRef = useRef<HTMLInputElement>(null);
const load = async (): Promise<boolean> => {
@@ -72,7 +77,16 @@ export function SystemPanel() {
}
setSaving(true);
try {
await api.systemSettings.save({ webuiPort: portNum, webuiHost: host.trim(), trustProxy, tlsEnabled });
await runAction(
{
title: '正在更新服务设置',
detail: `${host.trim()}:${portNum}`,
successTitle: '服务设置已更新',
successDetail: '重启 SnowLuma 后生效',
errorTitle: '服务设置更新失败',
},
() => api.systemSettings.save({ webuiPort: portNum, webuiHost: host.trim(), trustProxy, tlsEnabled }),
);
await load();
flash('ok', '已保存,重启 SnowLuma 后生效');
} catch (e) {
@@ -86,7 +100,16 @@ export function SystemPanel() {
if (!certPem.trim() || !keyPem.trim()) { flash('err', '请同时填入证书与私钥'); return; }
setSaving(true);
try {
await api.systemSettings.uploadCert(certPem, keyPem);
await runAction(
{
title: '正在更新 TLS 证书',
detail: '正在校验证书与私钥',
successTitle: 'TLS 证书已更新',
successDetail: '重启 SnowLuma 后生效',
errorTitle: 'TLS 证书更新失败',
},
() => api.systemSettings.uploadCert(certPem, keyPem),
);
setCertPem(''); setKeyPem('');
setEditingCert(false);
await load();
@@ -101,12 +124,21 @@ export function SystemPanel() {
const deleteCert = async () => {
setSaving(true);
try {
await api.systemSettings.deleteCert();
await runAction(
{
title: '正在删除 TLS 证书',
detail: '正在移除服务器上的证书与私钥',
successTitle: 'TLS 证书已删除',
errorTitle: 'TLS 证书删除失败',
},
() => api.systemSettings.deleteCert(),
);
setEditingCert(false);
await load();
flash('ok', '证书已删除');
} catch (e) {
flash('err', e instanceof Error ? e.message : '删除失败');
throw e;
} finally {
setSaving(false);
}
@@ -115,7 +147,15 @@ export function SystemPanel() {
const exportBackup = async () => {
setSaving(true);
try {
const bundle = await api.systemSettings.exportBackup(exportCreds);
const bundle = await runAction(
{
title: '正在导出配置备份',
detail: exportCreds ? '包含敏感配置' : '不包含敏感配置',
successTitle: '配置备份已导出',
errorTitle: '配置备份导出失败',
},
() => api.systemSettings.exportBackup(exportCreds),
);
const blob = new Blob([JSON.stringify(bundle, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
@@ -136,8 +176,21 @@ export function SystemPanel() {
try {
const text = await file.text();
let parsed: Record<string, unknown>;
try { parsed = JSON.parse(text); } catch { flash('err', '文件不是有效的 JSON'); return; }
const res = await api.systemSettings.importBackup(parsed, restoreCreds);
try {
parsed = JSON.parse(text);
} catch {
throw new Error('文件不是有效的 JSON');
}
const res = await runAction(
{
title: '正在恢复配置备份',
detail: file.name,
successTitle: '配置备份已恢复',
successDetail: '恢复结果已写入服务器',
errorTitle: '配置备份恢复失败',
},
() => api.systemSettings.importBackup(parsed, restoreCreds),
);
const parts = res.restored.length ? [`已恢复 ${res.restored.length} 项`] : ['没有可恢复的配置'];
if (res.skipped.length) parts.push(`跳过 ${res.skipped.length} 项(敏感配置,含 OneBot 配置)`);
if (res.migrated.length) parts.push(`兼容转换 ${res.migrated.length} 项`);
@@ -151,6 +204,7 @@ export function SystemPanel() {
const message = e instanceof Error ? e.message : '恢复失败';
const refreshed = await load();
flash('err', refreshed ? message : `${message};界面状态刷新失败,请手动刷新页面`);
throw e;
} finally {
setSaving(false);
if (fileRef.current) fileRef.current.value = '';
@@ -237,7 +291,7 @@ export function SystemPanel() {
<Button variant="outline" onClick={() => setEditingCert(true)} className="gap-1.5">
<Pencil className="h-4 w-4" /> 更改证书
</Button>
<Button variant="outline" onClick={deleteCert} disabled={saving} className="gap-1.5">
<Button variant="outline" onClick={() => setConfirmDeleteCert(true)} disabled={saving} className="gap-1.5">
<Trash2 className="h-4 w-4" /> 删除证书
</Button>
</div>
@@ -306,7 +360,11 @@ export function SystemPanel() {
type="file"
accept="application/json,.json"
className="hidden"
onChange={(e) => { const f = e.target.files?.[0]; if (f) void importBackup(f); }}
onChange={(e) => {
const file = e.target.files?.[0];
if (file) setPendingBackup(file);
e.target.value = '';
}}
/>
<div>
<Button variant="outline" onClick={() => fileRef.current?.click()} disabled={saving} className="gap-1.5">
@@ -317,6 +375,36 @@ export function SystemPanel() {
</div>
</CardContent>
</Card>
<ConfirmDialog
open={confirmDeleteCert}
onOpenChange={setConfirmDeleteCert}
title="删除 TLS 证书?"
description="将移除服务器上的证书与私钥。若 HTTPS 仍处于启用状态,下次启动将无法继续使用当前证书。"
confirmText="删除证书"
destructive
onConfirm={deleteCert}
/>
<ConfirmDialog
open={pendingBackup !== null}
onOpenChange={(open) => {
if (!open) setPendingBackup(null);
}}
title="恢复配置备份?"
description={
pendingBackup
? `将从 ${pendingBackup.name} 覆盖当前系统配置${restoreCreds ? ',包括敏感配置、TLS 私钥与 OneBot 配置' : ''}。成功后需要重启 SnowLuma。`
: ''
}
confirmText="确认恢复"
destructive
onConfirm={async () => {
if (!pendingBackup) return;
await importBackup(pendingBackup);
setPendingBackup(null);
}}
/>
</motion.div>
);
}