From b982927b4afce47b917b20ab40b5ff1c8f6edfa3 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Fri, 31 Jul 2026 15:35:03 +0800 Subject: [PATCH] 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. --- packages/webui/README.md | 86 +--- packages/webui/src/App.tsx | 45 +- .../webui/src/components/confirm-dialog.tsx | 48 +- .../interior/collapsible-banner.tsx | 304 ++++++++++++ .../src/components/interior/live-activity.tsx | 468 ++++++++++++++++++ .../webui/src/components/layout/top-bar.tsx | 5 + .../webui/src/components/pages/logs-page.tsx | 32 +- .../src/components/pages/settings-page.tsx | 121 ++++- .../settings/global-config-panel.tsx | 41 +- .../settings/notifications-panel.tsx | 74 ++- .../src/components/settings/storage-panel.tsx | 125 ++--- .../src/components/settings/system-panel.tsx | 104 +++- .../src/contexts/ActionFeedbackContext.tsx | 356 +++++++++++++ .../webui/src/contexts/AppStateContext.tsx | 2 +- packages/webui/src/contexts/LayoutContext.tsx | 38 +- packages/webui/src/contexts/ThemeContext.tsx | 105 ++-- .../webui/src/hooks/use-hook-process-ops.ts | 22 +- .../src/hooks/use-onebot-instance-config.ts | 33 +- packages/webui/src/router/app-layout.tsx | 6 +- packages/webui/tests/action-feedback.test.ts | 70 +++ 20 files changed, 1863 insertions(+), 222 deletions(-) create mode 100644 packages/webui/src/components/interior/collapsible-banner.tsx create mode 100644 packages/webui/src/components/interior/live-activity.tsx create mode 100644 packages/webui/src/contexts/ActionFeedbackContext.tsx create mode 100644 packages/webui/tests/action-feedback.test.ts diff --git a/packages/webui/README.md b/packages/webui/README.md index 7dbf7ebf..51202e5e 100644 --- a/packages/webui/README.md +++ b/packages/webui/README.md @@ -1,73 +1,27 @@ -# React + TypeScript + Vite +# SnowLuma WebUI -This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. +SnowLuma's browser console is a Vite + React application for managing runtime +status, OneBot configuration, logs, storage, and server settings. -Currently, two official plugins are available: +## Interaction conventions -- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs) -- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) +- Destructive actions and second confirmations stay in modal dialogs. +- Operations that may take time show a bottom-right running state. +- Completed and failed operations use bottom-right result notices that close + automatically after a visible countdown. +- Routine, high-frequency adjustments should not generate a notice for every + intermediate edit. +- Failures must remain visible in the affected control and in the operation + result; do not convert failed responses into successful feedback. -## React Compiler +## Local development -The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation). +From the repository root: -## Expanding the ESLint configuration - -If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules: - -```js -export default defineConfig([ - globalIgnores(['dist']), - { - files: ['**/*.{ts,tsx}'], - extends: [ - // Other configs... - - // Remove tseslint.configs.recommended and replace with this - tseslint.configs.recommendedTypeChecked, - // Alternatively, use this for stricter rules - tseslint.configs.strictTypeChecked, - // Optionally, add this for stylistic rules - tseslint.configs.stylisticTypeChecked, - - // Other configs... - ], - languageOptions: { - parserOptions: { - project: ['./tsconfig.node.json', './tsconfig.app.json'], - tsconfigRootDir: import.meta.dirname, - }, - // other options... - }, - }, -]) -``` - -You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules: - -```js -// eslint.config.js -import reactX from 'eslint-plugin-react-x' -import reactDom from 'eslint-plugin-react-dom' - -export default defineConfig([ - globalIgnores(['dist']), - { - files: ['**/*.{ts,tsx}'], - extends: [ - // Other configs... - // Enable lint rules for React - reactX.configs['recommended-typescript'], - // Enable lint rules for React DOM - reactDom.configs.recommended, - ], - languageOptions: { - parserOptions: { - project: ['./tsconfig.node.json', './tsconfig.app.json'], - tsconfigRootDir: import.meta.dirname, - }, - // other options... - }, - }, -]) +```bash +pnpm --filter webui dev +pnpm --filter webui typecheck +pnpm --filter webui lint +pnpm --filter webui test +pnpm --filter webui build ``` diff --git a/packages/webui/src/App.tsx b/packages/webui/src/App.tsx index f7adae88..d9f4b117 100644 --- a/packages/webui/src/App.tsx +++ b/packages/webui/src/App.tsx @@ -11,16 +11,24 @@ import { DebugTaskProvider } from '@/contexts/DebugTaskContext'; import { TaskBadge } from '@/components/debug/task-badge'; import { AdaptivePointer } from '@/components/ui/adaptive-pointer'; import { GlobalContextMenu } from '@/components/ui/global-context-menu'; +import { + ActionFeedbackProvider, + ActionFeedbackViewport, + useActionFeedback, +} from '@/contexts/ActionFeedbackContext'; import type { AgreementsPayload } from '@/lib/api/types'; import { appRouter } from '@/router'; export default function App() { return ( - - - - - + + + + + + + + ); } @@ -191,14 +199,25 @@ function Splash({ children }: { children: React.ReactNode }) { function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean, password: string) => void }) { const api = useApi(); + const { runAction } = useActionFeedback(); const handleLogin = useCallback( async (password: string) => { - const result = await api.login(password); + const result = await runAction( + { + title: '正在登录', + detail: '正在验证 WebUI 访问密码', + successTitle: '登录成功', + successDetail: '正在进入控制台', + errorTitle: '登录失败', + resultError: (login) => login.ok ? null : login.message, + }, + () => api.login(password), + ); if (!result.ok) return { success: false, error: result.message }; onAuthed(result.mustChangePassword, password); return { success: true }; }, - [api, onAuthed], + [api, onAuthed, runAction], ); return ; } @@ -215,13 +234,23 @@ function ConsentGate({ onDecline: () => void; }) { const api = useApi(); + const { runAction } = useActionFeedback(); return ( { - const result = await api.agreements.recordConsent(payload.version); + const result = await runAction( + { + title: '正在记录协议确认', + detail: `协议版本 ${payload.version.slice(0, 8)}`, + successTitle: '协议确认已记录', + errorTitle: '协议确认失败', + resultError: (consent) => consent.success ? null : consent.message, + }, + () => api.agreements.recordConsent(payload.version), + ); if (result.success) { onAccepted(); return { success: true }; diff --git a/packages/webui/src/components/confirm-dialog.tsx b/packages/webui/src/components/confirm-dialog.tsx index f384559a..23b559ce 100644 --- a/packages/webui/src/components/confirm-dialog.tsx +++ b/packages/webui/src/components/confirm-dialog.tsx @@ -10,6 +10,11 @@ import { AlertDialogTitle, } from '@/components/ui/alert-dialog'; import { buttonVariants } from '@/components/ui/button'; +import { + actionErrorMessage, + useActionFeedback, + type ActionFeedbackOptions, +} from '@/contexts/ActionFeedbackContext'; import { cn } from '@/lib/utils'; interface ConfirmDialogProps { @@ -20,6 +25,9 @@ interface ConfirmDialogProps { confirmText?: string; cancelText?: string; destructive?: boolean; + content?: ReactNode; + confirmDisabled?: boolean; + activity?: ActionFeedbackOptions; onConfirm: () => void | Promise; } @@ -31,25 +39,57 @@ export function ConfirmDialog({ confirmText = '确认', cancelText = '取消', destructive = false, + content, + confirmDisabled = false, + activity, onConfirm, }: ConfirmDialogProps) { const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const { runAction } = useActionFeedback(); + const handleConfirm = async () => { setBusy(true); + setError(null); try { - await onConfirm(); + if (!activity) { + await onConfirm(); + } else { + await runAction(activity, onConfirm); + } onOpenChange(false); + } catch (caught) { + const message = actionErrorMessage(caught); + setError(message); + console.error('confirm action failed', caught); } finally { setBusy(false); } }; + + const handleOpenChange = (nextOpen: boolean) => { + if (busy && !nextOpen) return; + if (!nextOpen) setError(null); + onOpenChange(nextOpen); + }; + return ( - + {title} - {description && {description}} + {description && ( + +
{description}
+
+ )}
+ {error && ( +
+ {error} +
+ )} + {content} {cancelText} {busy ? '处理中…' : confirmText} diff --git a/packages/webui/src/components/interior/collapsible-banner.tsx b/packages/webui/src/components/interior/collapsible-banner.tsx new file mode 100644 index 00000000..46833e99 --- /dev/null +++ b/packages/webui/src/components/interior/collapsible-banner.tsx @@ -0,0 +1,304 @@ +"use client"; + +import { useCallback, useEffect, useId, useRef, useState } from "react"; +import { motion, useReducedMotion } from "motion/react"; + +const EASE = [0.23, 1, 0.32, 1] as const; +const DISCLOSE = { type: "spring", stiffness: 190, damping: 30, mass: 1 } as const; +const NUDGE = { type: "spring", stiffness: 700, damping: 46, mass: 0.5 } as const; +const INSTANT = { duration: 0 } as const; + +export type BannerState = "open" | "folded" | "dismissed"; + +export type UseCollapsibleBannerOptions = { + state?: BannerState; + defaultState?: BannerState; + onStateChange?: (state: BannerState) => void; + onDismiss?: () => void; +}; + +export type UseCollapsibleBannerResult = { + state: BannerState; + open: boolean; + folded: boolean; + dismissed: boolean; + fold: () => void; + expand: () => void; + toggle: () => void; + dismiss: () => void; + restore: () => void; +}; + +export function useCollapsibleBanner({ + state: controlled, + defaultState = "open", + onStateChange, + onDismiss, +}: UseCollapsibleBannerOptions = {}): UseCollapsibleBannerResult { + const [uncontrolled, setUncontrolled] = useState(defaultState); + const state = controlled ?? uncontrolled; + + const changed = useRef(onStateChange); + const closed = useRef(onDismiss); + useEffect(() => { + changed.current = onStateChange; + }, [onStateChange]); + useEffect(() => { + closed.current = onDismiss; + }, [onDismiss]); + + const commit = useCallback((next: BannerState) => { + setUncontrolled(next); + changed.current?.(next); + }, []); + + const fold = useCallback(() => commit("folded"), [commit]); + const expand = useCallback(() => commit("open"), [commit]); + const restore = useCallback(() => commit("open"), [commit]); + + const toggle = useCallback( + () => commit(state === "open" ? "folded" : "open"), + [commit, state], + ); + + const dismiss = useCallback(() => { + commit("dismissed"); + closed.current?.(); + }, [commit]); + + return { + state, + open: state === "open", + folded: state === "folded", + dismissed: state === "dismissed", + fold, + expand, + toggle, + dismiss, + restore, + }; +} + +const NOTICE_GLYPH = ( + +); + +const CARET_DOWN = ( + +); + +const CLOSE = ( + +); + +export type CollapsibleBannerProps = { + title: React.ReactNode; + description?: React.ReactNode; + children?: React.ReactNode; + action?: React.ReactNode; + icon?: React.ReactNode; + + dismissible?: boolean; + state?: BannerState; + defaultState?: BannerState; + onStateChange?: (state: BannerState) => void; + onDismiss?: () => void; + onDismissed?: () => void; + dismissLabel?: string; + dismissedMessage?: string; + className?: string; +}; + +export function CollapsibleBanner({ + title, + description, + children, + action, + icon, + dismissible = true, + state: controlled, + defaultState = "open", + onStateChange, + onDismiss, + onDismissed, + dismissLabel = "Dismiss notice", + dismissedMessage = "Notice dismissed.", + className = "", +}: CollapsibleBannerProps) { + const reduced = useReducedMotion(); + const uid = useId(); + const bodyId = `${uid}-body`; + const titleId = `${uid}-title`; + + const { state, open, dismissed, toggle, fold, dismiss } = useCollapsibleBanner({ + state: controlled, + defaultState, + onStateChange, + onDismiss, + }); + const wasVisible = useRef(false); + useEffect(() => { + if (!dismissed) wasVisible.current = true; + }, [dismissed]); + + const hasBody = Boolean(description || children || action); + + const disclose = reduced + ? INSTANT + : { + height: DISCLOSE, + opacity: { duration: 0.14, ease: EASE, delay: open ? 0.05 : 0 }, + y: DISCLOSE, + }; + + return ( + <> + { + if (dismissed && wasVisible.current) onDismissed?.(); + }} + className="rounded-[11px]" + > +
+
+ + + {hasBody ? ( + + ) : ( + + {title} + + )} + + {dismissible ? ( + + ) : null} +
+ + {hasBody ? ( + + + {description ? ( +

+ {description} +

+ ) : null} + + {children} + + {action ?
{action}
: null} +
+
+ ) : null} +
+
+ + {state === "dismissed" ? dismissedMessage : ""} + + + ); +} diff --git a/packages/webui/src/components/interior/live-activity.tsx b/packages/webui/src/components/interior/live-activity.tsx new file mode 100644 index 00000000..ce26ceaa --- /dev/null +++ b/packages/webui/src/components/interior/live-activity.tsx @@ -0,0 +1,468 @@ +"use client"; + +import { + useCallback, + useEffect, + useLayoutEffect, + useRef, + useState, +} from "react"; +import { AnimatePresence, motion, useReducedMotion } from "motion/react"; + +const SURFACE = { type: "spring", stiffness: 420, damping: 36, mass: 0.9 } as const; +const CROSSFADE = { type: "spring", stiffness: 260, damping: 34, mass: 0.8 } as const; +const SMALL = { type: "spring", stiffness: 700, damping: 46, mass: 0.5 } as const; +const FILL = { type: "spring", stiffness: 210, damping: 34, mass: 0.9 } as const; +const EASE = [0.23, 1, 0.32, 1] as const; +const LEAVE = [0.4, 0, 1, 1] as const; +const DRAW = { duration: 0.3, ease: EASE } as const; +const INSTANT = { duration: 0 } as const; +const SPIN = { duration: 0.85, ease: "linear", repeat: Infinity } as const; + +const PEEK_FOR = 2600; +const LEAVE_DELAY = 160; + +const face = (on: boolean) => (on ? "" : "pointer-events-none"); + +const useIsoLayoutEffect = + typeof window === "undefined" ? useEffect : useLayoutEffect; + +export type ActivityPhase = "running" | "success" | "error"; + +export type Activity = { + id: string; + title: string; + detail?: string; + progress?: number | null; + phase: ActivityPhase; + action?: { label: string; onClick: () => void }; +}; + +export type ActivityInput = { + title: string; + detail?: string; + progress?: number | null; +}; + +export type UseLiveActivityOptions = { + linger?: number; +}; + +export function useLiveActivity({ linger = 2000 }: UseLiveActivityOptions = {}) { + const [activity, setActivity] = useState(null); + const seq = useRef(0); + const timer = useRef | null>(null); + + const clear = useCallback(() => { + if (timer.current) clearTimeout(timer.current); + timer.current = null; + }, []); + + const start = useCallback( + (input: ActivityInput) => { + clear(); + seq.current += 1; + const id = `activity-${seq.current}`; + setActivity({ progress: null, ...input, id, phase: "running" }); + return id; + }, + [clear], + ); + + const update = useCallback((patch: Partial) => { + setActivity((prev) => (prev ? { ...prev, ...patch } : prev)); + }, []); + + const dismiss = useCallback(() => { + clear(); + setActivity(null); + }, [clear]); + + const succeed = useCallback( + (patch?: Partial) => { + setActivity((prev) => + prev ? { ...prev, ...patch, phase: "success", progress: 1 } : prev, + ); + clear(); + timer.current = setTimeout(() => { + timer.current = null; + setActivity(null); + }, linger); + }, + [clear, linger], + ); + + const fail = useCallback( + (patch?: Partial, action?: Activity["action"]) => { + clear(); + setActivity((prev) => + prev ? { ...prev, ...patch, phase: "error", action } : prev, + ); + }, + [clear], + ); + + useEffect(() => clear, [clear]); + + return { activity, start, update, succeed, fail, dismiss }; +} + +export type UseLiveActivityReturn = ReturnType; + +export type LiveActivityProps = { + activity: Activity | null; + onDismiss?: () => void; + width?: number; + dismissLabel?: string; + label?: string; + className?: string; +}; + +export function LiveActivity({ + activity, + onDismiss, + width = 300, + dismissLabel = "Dismiss activity", + label = "Activity", + className = "", +}: LiveActivityProps) { + const reduced = useReducedMotion() === true; + + const [hovered, setHovered] = useState(false); + const [focused, setFocused] = useState(false); + const [peeking, setPeeking] = useState(false); + const [spoken, setSpoken] = useState(""); + + const compactRef = useRef(null); + const expandedRef = useRef(null); + const sizes = useRef({ c: { w: 0, h: 0 }, e: { w: 0, h: 0 } }); + const [dims, setDims] = useState<{ w: number; h: number } | null>(null); + + const leaveTimer = useRef | null>(null); + const peekTimer = useRef | null>(null); + const said = useRef>(new Set()); + + const phase = activity?.phase ?? "running"; + const expanded = + activity !== null && (hovered || focused || peeking || phase === "error"); + + const apply = useCallback((open: boolean) => { + const target = open ? sizes.current.e : sizes.current.c; + if (target.w === 0 || target.h === 0) return; + setDims((prev) => + prev && + Math.abs(prev.w - target.w) < 0.5 && + Math.abs(prev.h - target.h) < 0.5 + ? prev + : { w: target.w, h: target.h }, + ); + }, []); + + useIsoLayoutEffect(() => { + if (!activity) return; + const read = () => { + const c = compactRef.current; + const e = expandedRef.current; + if (c) sizes.current.c = { w: c.offsetWidth, h: c.offsetHeight }; + if (e) sizes.current.e = { w: e.offsetWidth, h: e.offsetHeight }; + apply(expanded); + }; + read(); + if (typeof ResizeObserver === "undefined") return; + const observer = new ResizeObserver(read); + if (compactRef.current) observer.observe(compactRef.current); + if (expandedRef.current) observer.observe(expandedRef.current); + return () => observer.disconnect(); + }, [activity, expanded, apply]); + + useEffect(() => { + if (!activity) { + setPeeking(false); + setHovered(false); + setFocused(false); + setDims(null); + return; + } + setPeeking(true); + if (peekTimer.current) clearTimeout(peekTimer.current); + peekTimer.current = setTimeout(() => { + peekTimer.current = null; + setPeeking(false); + }, PEEK_FOR); + }, [activity?.id, activity?.phase, activity]); + + useEffect( + () => () => { + if (leaveTimer.current) clearTimeout(leaveTimer.current); + if (peekTimer.current) clearTimeout(peekTimer.current); + }, + [], + ); + + useEffect(() => { + if (!activity) return; + const key = `${activity.id}:${activity.phase}`; + if (said.current.has(key)) return; + if (said.current.size > 64) said.current.clear(); + said.current.add(key); + setSpoken( + activity.phase === "running" + ? `${activity.title} started.` + : activity.phase === "success" + ? `${activity.title} finished.` + : `${activity.title} failed.`, + ); + }, [activity]); + + const enter = () => { + if (leaveTimer.current) clearTimeout(leaveTimer.current); + leaveTimer.current = null; + setHovered(true); + }; + + const leave = () => { + if (leaveTimer.current) clearTimeout(leaveTimer.current); + leaveTimer.current = setTimeout(() => { + leaveTimer.current = null; + setHovered(false); + }, LEAVE_DELAY); + }; + + const percent = + activity?.progress === null || activity?.progress === undefined + ? null + : Math.round(Math.min(1, Math.max(0, activity.progress)) * 100); + + return ( +
+ + {activity ? ( + setFocused(true)} + onBlurCapture={(e) => { + if (!e.currentTarget.contains(e.relatedTarget as Node | null)) { + setFocused(false); + } + }} + onKeyDown={(e) => { + if (e.key !== "Escape") return; + e.preventDefault(); + if (phase === "running") setHovered(false); + else onDismiss?.(); + }} + className="pointer-events-auto relative overflow-hidden rounded-[11px] border border-border/80 bg-popover/95 text-popover-foreground shadow-[0_1px_2px_rgb(0_0_0/0.07),0_16px_36px_-18px_rgb(0_0_0/0.5)] backdrop-blur-xl" + > + + + {percent !== null && phase === "running" ? ( + + {percent}% + + ) : ( + + {activity.title} + + )} + + + +
+ + + {activity.title} + + {activity.action ? ( + + ) : null} + {onDismiss && phase !== "running" ? ( + + ) : null} +
+ + {activity.detail ? ( +

+ {activity.detail} +

+ ) : null} + + {percent !== null && phase !== "error" ? ( +
+
+
+ +
+
+ + {percent}% + +
+ ) : null} + +
+
+ ) : null} +
+ + {spoken} + +
+ ); +} + +function PhaseGlyph({ phase, reduced }: { phase: ActivityPhase; reduced: boolean }) { + return ( + + + {reduced ? ( + + + + ) : ( + + + + + )} + + + + + + + + + + + + + + ); +} diff --git a/packages/webui/src/components/layout/top-bar.tsx b/packages/webui/src/components/layout/top-bar.tsx index 072d39bf..5846706d 100644 --- a/packages/webui/src/components/layout/top-bar.tsx +++ b/packages/webui/src/components/layout/top-bar.tsx @@ -121,6 +121,11 @@ export function TopBar({ description="登出后将清除当前会话令牌,您需要重新输入访问密码才能进入控制台。" confirmText="登出" destructive + activity={{ + title: '正在退出登录', + successTitle: '已退出登录', + errorTitle: '退出登录失败', + }} onConfirm={onLogout} /> diff --git a/packages/webui/src/components/pages/logs-page.tsx b/packages/webui/src/components/pages/logs-page.tsx index a0a376d4..949173bd 100644 --- a/packages/webui/src/components/pages/logs-page.tsx +++ b/packages/webui/src/components/pages/logs-page.tsx @@ -18,6 +18,7 @@ import { } from '@/lib/server-log-level'; import { useTheme } from '@/contexts/ThemeContext'; import { useLayout } from '@/contexts/LayoutContext'; +import { useActionFeedback } from '@/contexts/ActionFeedbackContext'; // Dedicated log-level text tokens (see index.css): the app accent colors are // too light as small text on the light canvas (WCAG AA fails), so these hit @@ -100,6 +101,7 @@ function ToolButton({ label, onClick, children, active, danger, disabled }: Tool export function LogsPage() { const api = useApi(); + const { runAction } = useActionFeedback(); const { formatClock, appearance } = useTheme(); const { pages, setPages } = useLayout(); const prefs = pages.logs; @@ -152,14 +154,23 @@ export function LogsPage() { if (lv === serverLevel || levelBusy) return; setLevelBusy(true); try { - const { level } = await api.logs.setLevel(lv); + const { level } = await runAction( + { + title: '正在更新服务端日志级别', + detail: `切换为 ${lv.toUpperCase()}`, + successTitle: '日志级别已更新', + successDetail: `${lv.toUpperCase()} 已生效`, + errorTitle: '日志级别更新失败', + }, + () => api.logs.setLevel(lv), + ); setServerLevel(level); } catch (err) { console.error('setLevel', err); } finally { setLevelBusy(false); } - }, [api, serverLevel, levelBusy]); + }, [api, serverLevel, levelBusy, runAction]); const changeServerLevel = useCallback((lv: LogLevel) => { if (levelBusy) return; @@ -351,7 +362,15 @@ export function LogsPage() { if (traceExportBusy) return; setTraceExportBusy(true); try { - const { text, filename } = await api.logs.exportTrace(); + const { text, filename } = await runAction( + { + title: '正在导出完整 TRACE', + detail: '正在读取服务端 TRACE 文件', + successTitle: '完整 TRACE 已导出', + errorTitle: 'TRACE 导出失败', + }, + () => api.logs.exportTrace(), + ); const blob = new Blob([text], { type: 'text/plain;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); @@ -364,7 +383,7 @@ export function LogsPage() { } finally { setTraceExportBusy(false); } - }, [api, traceExportBusy]); + }, [api, traceExportBusy, runAction]); const addHighlight = () => { const kw = newKeyword.trim(); @@ -762,6 +781,11 @@ export function LogsPage() { description="此操作仅清空浏览器视图中的日志,不会影响服务端的日志缓冲区。" confirmText="清空" destructive + activity={{ + title: '正在清空日志视图', + successTitle: '日志视图已清空', + errorTitle: '日志视图清空失败', + }} onConfirm={() => setLogs([])} /> diff --git a/packages/webui/src/components/pages/settings-page.tsx b/packages/webui/src/components/pages/settings-page.tsx index c35aa9e3..82dac2eb 100644 --- a/packages/webui/src/components/pages/settings-page.tsx +++ b/packages/webui/src/components/pages/settings-page.tsx @@ -33,6 +33,7 @@ import { type TimeFormat, } from '@/contexts/ThemeContext'; import { DEFAULT_LAYOUT, DEFAULT_PAGES, reconcileLayoutItems, useLayout } from '@/contexts/LayoutContext'; +import { useActionFeedback } from '@/contexts/ActionFeedbackContext'; import { NAV_ITEMS } from '@/components/layout/sidebar'; import { TOPBAR_CATALOGUE } from '@/components/layout/top-bar'; import { ChangePasswordDialog } from '@/components/change-password-dialog'; @@ -956,18 +957,28 @@ function validateCss(css: string): string | null { function AdvancedPanel() { const { appearance, setAppearance } = useTheme(); + const { runAction } = useActionFeedback(); const cssRef = useRef(null); const [cssWarn, setCssWarn] = useState(null); const api = useApi(); const fileRef = useRef(null); const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null); const [confirmReset, setConfirmReset] = useState(false); + const [pendingImport, setPendingImport] = useState(null); const [busy, setBusy] = useState(false); const onExport = async () => { setMsg(null); try { - const config = await api.ui.get(); + const config = await runAction( + { + title: '正在导出界面配置', + detail: '外观、布局与自定义 CSS', + successTitle: '界面配置已导出', + errorTitle: '界面配置导出失败', + }, + () => api.ui.get(), + ); const blob = new Blob([JSON.stringify(config, null, 2)], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); @@ -975,7 +986,8 @@ function AdvancedPanel() { a.download = 'snowluma-ui-config.json'; a.click(); URL.revokeObjectURL(url); - } catch { + } catch (error) { + console.error('export UI config failed', error); setMsg({ kind: 'err', text: '导出失败' }); } }; @@ -988,28 +1000,59 @@ function AdvancedPanel() { setMsg({ kind: 'err', text: '导入失败:文件过大(上限 256KB)' }); return; } + setPendingImport(file); + }; + + const importUiConfig = async (file: File) => { setMsg(null); setBusy(true); try { const parsed = JSON.parse(await file.text()) as unknown; if (typeof parsed !== 'object' || parsed === null) throw new Error('shape'); - await api.ui.save(parsed as Parameters[0]); + await runAction( + { + title: '正在导入界面配置', + detail: file.name, + successTitle: '界面配置已导入', + successDetail: '即将重新载入界面', + errorTitle: '界面配置导入失败', + surviveReload: true, + }, + () => api.ui.save(parsed as Parameters[0]), + ); // The server normalized it; reload so appearance + layout both re-read. window.location.reload(); - } catch { + } catch (error) { setBusy(false); - setMsg({ kind: 'err', text: '导入失败:不是有效的配置 JSON' }); + setMsg({ + kind: 'err', + text: error instanceof SyntaxError || (error instanceof Error && error.message === 'shape') + ? '导入失败:不是有效的配置 JSON' + : `导入失败:${error instanceof Error ? error.message : '未知错误'}`, + }); + throw error; } }; const doReset = async () => { setBusy(true); try { - await api.ui.save({ appearance: DEFAULT_APPEARANCE, layout: DEFAULT_LAYOUT, pages: DEFAULT_PAGES }); + await runAction( + { + title: '正在重置界面配置', + detail: '恢复外观、布局、导航与自定义 CSS', + successTitle: '界面配置已重置', + successDetail: '即将重新载入界面', + errorTitle: '界面配置重置失败', + surviveReload: true, + }, + () => api.ui.save({ appearance: DEFAULT_APPEARANCE, layout: DEFAULT_LAYOUT, pages: DEFAULT_PAGES }), + ); window.location.reload(); - } catch { + } catch (error) { setBusy(false); setMsg({ kind: 'err', text: '重置失败' }); + throw error; } }; @@ -1114,8 +1157,27 @@ function AdvancedPanel() { title="重置全部界面配置" description="将外观、仪表盘布局、导航与自定义 CSS 全部恢复为默认。此操作不可撤销。" confirmText="重置" + destructive onConfirm={doReset} /> + + { + if (!open) setPendingImport(null); + }} + title="导入并覆盖界面配置?" + description={pendingImport + ? `将使用 ${pendingImport.name} 覆盖当前外观、布局、导航与自定义 CSS,随后重新载入界面。` + : ''} + confirmText="确认导入" + destructive + onConfirm={async () => { + if (!pendingImport) return; + await importUiConfig(pendingImport); + setPendingImport(null); + }} + /> ); } @@ -1126,6 +1188,7 @@ function AccountPanel() { const { onLogout } = useAppState(); const [showChangePwd, setShowChangePwd] = useState(false); const [pwdSavedAt, setPwdSavedAt] = useState(null); + const [confirmLogout, setConfirmLogout] = useState(false); return ( @@ -1140,11 +1203,26 @@ function AccountPanel() { - + + { setChecking(true); - try { await refreshUpdate(true); } finally { setChecking(false); } + try { + await runAction( + { + title: '正在检查更新', + detail: `当前版本 v${__APP_VERSION__}`, + successTitle: '更新检查完成', + successDetail: (result) => ( + result?.hasUpdate && result.latest + ? `发现新版本 v${result.latest}` + : '当前已是最新版本' + ), + errorTitle: '更新检查失败', + resultError: (result) => { + if (!result) return '更新检查未返回结果'; + if (result.error === 'disabled') return '更新检查已关闭'; + return result.error || null; + }, + }, + () => refreshUpdate(true), + ); + } catch (error) { + console.error('manual update check failed', error); + } finally { + setChecking(false); + } }; const disabledCheck = updateInfo?.error === 'disabled'; diff --git a/packages/webui/src/components/settings/global-config-panel.tsx b/packages/webui/src/components/settings/global-config-panel.tsx index 1fcd247d..60de65eb 100644 --- a/packages/webui/src/components/settings/global-config-panel.tsx +++ b/packages/webui/src/components/settings/global-config-panel.tsx @@ -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(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 (
@@ -123,7 +144,11 @@ export function GlobalConfigPanel() {
-
diff --git a/packages/webui/src/components/settings/notifications-panel.tsx b/packages/webui/src/components/settings/notifications-panel.tsx index bd955a17..18c03679 100644 --- a/packages/webui/src/components/settings/notifications-panel.tsx +++ b/packages/webui/src/components/settings/notifications-panel.tsx @@ -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(null); const [loading, setLoading] = useState(true); const [dialog, setDialog] = useState({ 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: '通知渠道已删除' }, + )} /> ))}
diff --git a/packages/webui/src/components/settings/storage-panel.tsx b/packages/webui/src/components/settings/storage-panel.tsx index a329807d..0db53334 100644 --- a/packages/webui/src/components/settings/storage-panel.tsx +++ b/packages/webui/src/components/settings/storage-panel.tsx @@ -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(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 ( - { if (!nextOpen && !busy) close(); }} - > - - - - 清理全部账号的{category ? CATEGORY_INFO[category].label : '数据'}? - - - 该操作会删除所有离线账号的对应数据库及边车文件,无法撤销。请输入 - {ALL_ACCOUNTS_CONFIRMATION} - 继续。 - - + title={`清理全部账号的${category ? CATEGORY_INFO[category].label : '数据'}?`} + description={ + <> + 该操作会删除所有离线账号的对应数据库及边车文件,无法撤销。请输入 + {ALL_ACCOUNTS_CONFIRMATION} + 继续。 + + } + content={(
- - setConfirmation('')}> - 取消 - - { - event.preventDefault(); - if (!category || !isAllAccountsConfirmation(confirmation)) return; - void onConfirm(category); - }} - className="bg-destructive text-destructive-foreground hover:bg-destructive/90" - > - {busy ? : } - 确认清理 - - -
-
+ )} + 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'; diff --git a/packages/webui/src/components/settings/system-panel.tsx b/packages/webui/src/components/settings/system-panel.tsx index e73f92c4..2eedf952 100644 --- a/packages/webui/src/components/settings/system-panel.tsx +++ b/packages/webui/src/components/settings/system-panel.tsx @@ -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(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(null); const fileRef = useRef(null); const load = async (): Promise => { @@ -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; - 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() { -
@@ -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 = ''; + }} />
+ + + + { + 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); + }} + /> ); } diff --git a/packages/webui/src/contexts/ActionFeedbackContext.tsx b/packages/webui/src/contexts/ActionFeedbackContext.tsx new file mode 100644 index 00000000..e49e4287 --- /dev/null +++ b/packages/webui/src/contexts/ActionFeedbackContext.tsx @@ -0,0 +1,356 @@ +import { + createContext, + useCallback, + useContext, + useEffect, + useMemo, + useRef, + useState, + type ReactNode, +} from 'react'; +import { CircleAlert, CircleCheck } from 'lucide-react'; +import { motion } from 'motion/react'; +import { + CollapsibleBanner, + type BannerState, +} from '@/components/interior/collapsible-banner'; +import { + LiveActivity, + useLiveActivity, + type ActivityInput, +} from '@/components/interior/live-activity'; + +type ResultDetail = string | ((result: T) => string | undefined); +type ErrorDetail = string | ((error: unknown) => string); + +export interface ActionFeedbackOptions extends ActivityInput { + successTitle?: string; + successDetail?: ResultDetail; + errorTitle?: string; + errorDetail?: ErrorDetail; + /** Re-show a successful result after an imminent full-page reload. */ + surviveReload?: boolean; + /** + * Some APIs resolve transport-successfully while reporting a failed domain + * result. Return its user-facing reason here so the activity ends in error + * without changing the caller's result/control flow. + */ + resultError?: (result: T) => string | null | undefined; +} + +export interface ActionFeedbackHandle { + update: (patch: Partial) => void; + succeed: (patch?: Partial) => void; + fail: (detail: string, patch?: Partial) => void; +} + +interface ActionFeedbackValue { + startAction: (input: ActivityInput) => ActionFeedbackHandle; + runAction: (options: ActionFeedbackOptions, action: () => Promise | T) => Promise; + activity: ReturnType['activity']; + notices: ActionNotice[]; + removeNotice: (id: number) => void; + dismiss: () => void; +} + +interface ActionNotice { + id: number; + tone: 'success' | 'error'; + title: string; + detail?: string; +} + +const ActionFeedbackContext = createContext(null); +const RESULT_NOTICE_DURATION_MS = 5_000; +const RELOAD_NOTICE_MAX_AGE_MS = 30_000; +const RELOAD_NOTICE_KEY = 'snowluma_action_feedback_reload_notice'; + +interface ReloadNotice extends Omit { + createdAt: number; +} + +function preserveReloadNotice(notice: Omit): void { + try { + sessionStorage.setItem( + RELOAD_NOTICE_KEY, + JSON.stringify({ ...notice, createdAt: Date.now() } satisfies ReloadNotice), + ); + } catch (error) { + console.error('preserve action feedback across reload failed', error); + } +} + +function takeReloadNotice(): Omit | null { + let raw: string | null; + try { + raw = sessionStorage.getItem(RELOAD_NOTICE_KEY); + sessionStorage.removeItem(RELOAD_NOTICE_KEY); + } catch (error) { + console.error('read action feedback after reload failed', error); + return null; + } + if (!raw) return null; + try { + const parsed = JSON.parse(raw) as Partial; + if ( + (parsed.tone !== 'success' && parsed.tone !== 'error') + || typeof parsed.title !== 'string' + || typeof parsed.createdAt !== 'number' + || Date.now() - parsed.createdAt > RELOAD_NOTICE_MAX_AGE_MS + ) { + throw new Error('invalid or expired reload notice'); + } + return { + tone: parsed.tone, + title: parsed.title, + ...(typeof parsed.detail === 'string' ? { detail: parsed.detail } : {}), + }; + } catch (error) { + console.error('parse action feedback after reload failed', error); + return null; + } +} + +export function actionErrorMessage(error: unknown): string { + if (error instanceof Error && error.message.trim()) return error.message; + if (typeof error === 'string' && error.trim()) return error; + return '未知错误'; +} + +function resolveResultDetail(detail: ResultDetail | undefined, result: T): string | undefined { + return typeof detail === 'function' ? detail(result) : detail; +} + +function resolveErrorDetail(detail: ErrorDetail | undefined, error: unknown): string { + if (typeof detail === 'function') return detail(error); + return detail ?? actionErrorMessage(error); +} + +export function publishActionResult( + ownsSurface: boolean, + updateCurrentActivity: () => void, + publishNotice: () => void, +): void { + if (ownsSurface) updateCurrentActivity(); + publishNotice(); +} + +export function scheduleActionNoticeDismiss(onDismiss: () => void): () => void { + const timeout = setTimeout(onDismiss, RESULT_NOTICE_DURATION_MS); + return () => clearTimeout(timeout); +} + +export function ActionFeedbackProvider({ children }: { children: ReactNode }) { + const { + activity, + start, + update, + succeed, + fail, + dismiss: dismissActivity, + } = useLiveActivity(); + const activeId = useRef(null); + const noticeId = useRef(0); + const [notices, setNotices] = useState([]); + + const pushNotice = useCallback((notice: Omit) => { + const next = { ...notice, id: ++noticeId.current }; + setNotices((current) => [...current.slice(-2), next]); + }, []); + + useEffect(() => { + const notice = takeReloadNotice(); + if (notice) pushNotice(notice); + }, [pushNotice]); + + const startAction = useCallback((input: ActivityInput): ActionFeedbackHandle => { + const id = start(input); + activeId.current = id; + const ownsSurface = () => activeId.current === id; + + return { + update: (patch) => { + if (ownsSurface()) update(patch); + }, + succeed: (patch) => { + publishActionResult( + ownsSurface(), + () => succeed(patch), + () => pushNotice({ + tone: 'success', + title: patch?.title ?? input.title, + detail: patch?.detail ?? input.detail, + }), + ); + }, + fail: (detail, patch) => { + publishActionResult( + ownsSurface(), + () => fail({ ...patch, detail }), + () => pushNotice({ + tone: 'error', + title: patch?.title ?? input.title, + detail, + }), + ); + }, + }; + }, [start, update, succeed, fail, pushNotice]); + + const runAction = useCallback(async ( + options: ActionFeedbackOptions, + action: () => Promise | T, + ): Promise => { + const { + successTitle, + successDetail, + errorTitle, + errorDetail, + resultError, + surviveReload, + ...input + } = options; + const handle = startAction(input); + try { + const result = await action(); + const failed = resultError?.(result); + if (failed) { + handle.fail(failed, errorTitle ? { title: errorTitle } : undefined); + } else { + const detail = resolveResultDetail(successDetail, result); + if (surviveReload) { + preserveReloadNotice({ + tone: 'success', + title: successTitle ?? input.title, + detail: detail ?? input.detail, + }); + } + handle.succeed({ + ...(successTitle ? { title: successTitle } : {}), + ...(detail !== undefined ? { detail } : {}), + }); + } + return result; + } catch (error) { + handle.fail(resolveErrorDetail(errorDetail, error), errorTitle ? { title: errorTitle } : undefined); + throw error; + } + }, [startAction]); + + const dismiss = useCallback(() => { + activeId.current = null; + dismissActivity(); + }, [dismissActivity]); + + const removeNotice = useCallback((id: number) => { + setNotices((current) => current.filter((notice) => notice.id !== id)); + }, []); + + const value = useMemo( + () => ({ startAction, runAction, activity, notices, removeNotice, dismiss }), + [startAction, runAction, activity, notices, removeNotice, dismiss], + ); + + return ( + + {children} + + ); +} + +/** + * Rendered inside ThemeProvider's MotionConfig so SnowLuma's existing reduced + * motion / disable-motion preference also reaches Interior's component. + */ +export function ActionFeedbackViewport() { + const { + activity, + notices, + removeNotice, + dismiss, + } = useActionFeedback(); + const runningActivity = activity?.phase === 'running' ? activity : null; + + return ( +
+ {notices.map((notice) => ( + removeNotice(notice.id)} + /> + ))} + +
+ ); +} + +function ActionNoticeBanner({ + notice, + onRemoved, +}: { + notice: ActionNotice; + onRemoved: () => void; +}) { + const [state, setState] = useState('dismissed'); + const visible = state !== 'dismissed'; + + useEffect(() => { + const frame = requestAnimationFrame(() => setState('open')); + return () => cancelAnimationFrame(frame); + }, []); + + useEffect(() => { + if (!visible) return; + return scheduleActionNoticeDismiss(() => setState('dismissed')); + }, [visible]); + + return ( +
+ + : } + dismissLabel="关闭通知" + dismissedMessage="操作通知已关闭。" + className={notice.tone === 'success' + ? 'border-success/25' + : 'border-destructive/30'} + /> + {state !== 'dismissed' ? ( + + ) : null} +
+ ); +} + +export function useActionFeedback(): ActionFeedbackValue { + const value = useContext(ActionFeedbackContext); + if (!value) throw new Error('useActionFeedback must be used within ActionFeedbackProvider'); + return value; +} diff --git a/packages/webui/src/contexts/AppStateContext.tsx b/packages/webui/src/contexts/AppStateContext.tsx index 174a0d4c..742be61c 100644 --- a/packages/webui/src/contexts/AppStateContext.tsx +++ b/packages/webui/src/contexts/AppStateContext.tsx @@ -22,7 +22,7 @@ export interface AppStateValue { refreshSystem: () => void; refreshConnections: () => void; /** Re-run the update check; `force` bypasses the server-side cache. */ - refreshUpdate: (force?: boolean) => Promise; + refreshUpdate: (force?: boolean) => Promise; /** Triggered from the topbar logout button. */ onLogout: () => void; } diff --git a/packages/webui/src/contexts/LayoutContext.tsx b/packages/webui/src/contexts/LayoutContext.tsx index 58de1ae3..17c95a50 100644 --- a/packages/webui/src/contexts/LayoutContext.tsx +++ b/packages/webui/src/contexts/LayoutContext.tsx @@ -1,4 +1,5 @@ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; +import { useActionFeedback } from '@/contexts/ActionFeedbackContext'; import { useApi } from '@/lib/api'; import { defaultOverviewGrid, defaultOverviewMobile, migrateOverviewBlocks } from '@/lib/dashboard-layout'; import type { UiLayout, UiLayoutItem, UiPages } from '@/types'; @@ -104,6 +105,7 @@ const LayoutContext = createContext(null); export function LayoutProvider({ children }: { children: ReactNode }) { const api = useApi(); + const { runAction } = useActionFeedback(); const [layout, setLayout] = useState(DEFAULT_LAYOUT); const [pages, setPagesState] = useState(DEFAULT_PAGES); const [ready, setReady] = useState(false); @@ -155,11 +157,15 @@ export function LayoutProvider({ children }: { children: ReactNode }) { useEffect(() => () => { if (saveTimer.current) { clearTimeout(saveTimer.current); - void api.ui.save({ layout: layoutRef.current }).catch(() => { /* best-effort */ }); + void api.ui.save({ layout: layoutRef.current }).catch((error) => { + console.error('layout unmount flush failed', error); + }); } if (pagesTimer.current) { clearTimeout(pagesTimer.current); - void api.ui.save({ pages: pagesRef.current }).catch(() => { /* best-effort */ }); + void api.ui.save({ pages: pagesRef.current }).catch((error) => { + console.error('page preferences unmount flush failed', error); + }); } }, [api]); @@ -170,9 +176,19 @@ export function LayoutProvider({ children }: { children: ReactNode }) { if (saveTimer.current) clearTimeout(saveTimer.current); saveTimer.current = setTimeout(() => { saveTimer.current = null; // mark not-pending so the unmount flush can't double-fire - void api.ui.save({ layout: next }).catch(() => { /* best-effort */ }); + void runAction( + { + title: '正在更新界面布局', + detail: '正在同步仪表盘与导航布局', + successTitle: '界面布局已更新', + errorTitle: '界面布局更新失败', + }, + () => api.ui.save({ layout: next }), + ).catch((error) => { + console.error('persist layout failed', error); + }); }, 300); - }, [api]); + }, [api, runAction]); const setOverviewBlocks = useCallback((items: UiLayoutItem[]) => { persist({ ...layoutRef.current, overviewBlocks: items }); @@ -207,9 +223,19 @@ export function LayoutProvider({ children }: { children: ReactNode }) { if (pagesTimer.current) clearTimeout(pagesTimer.current); pagesTimer.current = setTimeout(() => { pagesTimer.current = null; - void api.ui.save({ pages: next }).catch(() => { /* best-effort */ }); + void runAction( + { + title: '正在更新页面设置', + detail: '正在同步当前页面偏好', + successTitle: '页面设置已更新', + errorTitle: '页面设置更新失败', + }, + () => api.ui.save({ pages: next }), + ).catch((error) => { + console.error('persist page preferences failed', error); + }); }, 300); - }, [api]); + }, [api, runAction]); const value = useMemo(() => ({ overviewBlocks: layout.overviewBlocks, diff --git a/packages/webui/src/contexts/ThemeContext.tsx b/packages/webui/src/contexts/ThemeContext.tsx index 18ffeaa5..56efeee8 100644 --- a/packages/webui/src/contexts/ThemeContext.tsx +++ b/packages/webui/src/contexts/ThemeContext.tsx @@ -1,6 +1,7 @@ import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react'; import { flushSync } from 'react-dom'; import { MotionConfig } from 'motion/react'; +import { useActionFeedback } from '@/contexts/ActionFeedbackContext'; import type { Palette, ThemeMode, UiAppearance, UiBackground } from '@/types'; // Re-export the appearance value types so consumers (settings page etc.) can @@ -524,15 +525,15 @@ function isSafeMode(): boolean { async function persistAppearance(appearance: UiAppearance): Promise { const token = authToken(); if (!token) return; // pre-auth: local cache only (no settings UI exists there anyway) - try { - await fetch('/api/ui', { - method: 'POST', - headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` }, - // Section-level save: only `appearance`; the server preserves `layout`. - body: JSON.stringify({ appearance }), - }); - } catch { - /* best-effort — the local cache already holds the change */ + const response = await fetch('/api/ui', { + method: 'POST', + headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` }, + // Section-level save: only `appearance`; the server preserves `layout`. + body: JSON.stringify({ appearance }), + }); + if (!response.ok) { + const payload = (await response.json().catch(() => ({}))) as { message?: string; error?: string }; + throw new Error(payload.message || payload.error || `外观保存失败(HTTP ${response.status})`); } } @@ -634,6 +635,7 @@ function getSystemTheme(): 'light' | 'dark' { } export function ThemeProvider({ children }: { children: ReactNode }) { + const { runAction } = useActionFeedback(); const [appearance, setAppearanceState] = useState(readCache); const [systemTheme, setSystemTheme] = useState<'light' | 'dark'>(getSystemTheme); const [ready, setReady] = useState(false); @@ -671,7 +673,9 @@ export function ThemeProvider({ children }: { children: ReactNode }) { // clobber a look already set from another device. if (legacy && server && isPristine(server)) { next = { ...server, ...legacy, background: server.background }; - void persistAppearance(next); + void persistAppearance(next).catch((error) => { + console.error('appearance migration save failed', error); + }); } } @@ -714,8 +718,21 @@ export function ThemeProvider({ children }: { children: ReactNode }) { setAppearanceState(next); writeCache(next); if (saveTimer.current) clearTimeout(saveTimer.current); - saveTimer.current = setTimeout(() => void persistAppearance(next), 400); - }, []); + saveTimer.current = setTimeout(() => { + void runAction( + { + title: '正在更新外观', + detail: '正在同步界面设置', + successTitle: '外观已更新', + successDetail: '界面设置已同步', + errorTitle: '外观更新失败', + }, + () => persistAppearance(next), + ).catch((error) => { + console.error('persist appearance failed', error); + }); + }, 400); + }, [runAction]); const setAppearance = useCallback((patch: AppearancePatch) => { const prev = appearanceRef.current; @@ -732,30 +749,48 @@ export function ThemeProvider({ children }: { children: ReactNode }) { } }, [commit]); - const uploadBackground = useMemo(() => async (file: File) => { - const token = authToken(); - if (!token) throw new Error('未登录'); - const form = new FormData(); - form.append('file', file); - const res = await fetch('/api/ui/background', { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: form }); - if (!res.ok) { - const e = (await res.json().catch(() => ({}))) as { message?: string }; - throw new Error(e.message || '上传失败'); - } - const data = (await res.json()) as { config?: { appearance?: UiAppearance } }; - const ap = data.config?.appearance; - if (ap) { appearanceRef.current = ap; setAppearanceState(ap); writeCache(ap); } - }, []); + const uploadBackground = useMemo(() => async (file: File) => runAction( + { + title: '正在上传背景', + detail: file.name, + successTitle: '背景已更新', + successDetail: file.name, + errorTitle: '背景上传失败', + }, + async () => { + const token = authToken(); + if (!token) throw new Error('未登录'); + const form = new FormData(); + form.append('file', file); + const res = await fetch('/api/ui/background', { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: form }); + if (!res.ok) { + const e = (await res.json().catch(() => ({}))) as { message?: string }; + throw new Error(e.message || '上传失败'); + } + const data = (await res.json()) as { config?: { appearance?: UiAppearance } }; + const ap = data.config?.appearance; + if (ap) { appearanceRef.current = ap; setAppearanceState(ap); writeCache(ap); } + }, + ), [runAction]); - const removeBackground = useMemo(() => async () => { - const token = authToken(); - if (!token) throw new Error('未登录'); - const res = await fetch('/api/ui/background', { method: 'DELETE', headers: { Authorization: `Bearer ${token}` } }); - if (!res.ok) throw new Error('删除失败'); - const data = (await res.json()) as { config?: { appearance?: UiAppearance } }; - const ap = data.config?.appearance; - if (ap) { appearanceRef.current = ap; setAppearanceState(ap); writeCache(ap); } - }, []); + const removeBackground = useMemo(() => async () => runAction( + { + title: '正在删除背景', + detail: '移除已上传的壁纸', + successTitle: '背景已删除', + successDetail: '已恢复为无壁纸状态', + errorTitle: '背景删除失败', + }, + async () => { + const token = authToken(); + if (!token) throw new Error('未登录'); + const res = await fetch('/api/ui/background', { method: 'DELETE', headers: { Authorization: `Bearer ${token}` } }); + if (!res.ok) throw new Error('删除失败'); + const data = (await res.json()) as { config?: { appearance?: UiAppearance } }; + const ap = data.config?.appearance; + if (ap) { appearanceRef.current = ap; setAppearanceState(ap); writeCache(ap); } + }, + ), [runAction]); const formatClock = useMemo(() => (input: string | number | Date) => { const d = input instanceof Date ? input : new Date(input); diff --git a/packages/webui/src/hooks/use-hook-process-ops.ts b/packages/webui/src/hooks/use-hook-process-ops.ts index 1dc1efda..93f02c95 100644 --- a/packages/webui/src/hooks/use-hook-process-ops.ts +++ b/packages/webui/src/hooks/use-hook-process-ops.ts @@ -1,4 +1,5 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useActionFeedback } from '@/contexts/ActionFeedbackContext'; import { useApi, type ProcessActionResult } from '@/lib/api'; export type HookProcessOpKind = 'load' | 'unload' | 'refresh'; @@ -60,6 +61,7 @@ export function useHookProcessOps( opts: { onAfterOp?: () => Promise | void } = {}, ): UseHookProcessOpsResult { const api = useApi(); + const { runAction } = useActionFeedback(); const [byPid, setByPid] = useState>(() => new Map()); const [banner, setBanner] = useState(''); const [unloadFailedAlert, setUnloadFailedAlert] = useState(null); @@ -107,7 +109,23 @@ export function useHookProcessOps( const messages = KIND_MESSAGES[kind]; setBanner(messages.start(pid)); try { - const result = await action(); + const result = await runAction( + { + title: messages.start(pid), + detail: `PID ${pid}`, + successTitle: messages.ok(pid), + successDetail: `PID ${pid}`, + errorTitle: `${kind === 'load' ? '加载' : kind === 'unload' ? '卸载' : '刷新'}失败`, + resultError: (outcome) => ( + kind === 'unload' + && outcome.process?.status === 'connecting' + && outcome.process.error + ? outcome.process.error + : null + ), + }, + action, + ); if (kind === 'unload' && result.process?.status === 'connecting' && result.process.error) { setUnloadFailedAlert({ pid, error: result.process.error }); setBanner(`进程 ${pid} 卸载失败`); @@ -124,7 +142,7 @@ export function useHookProcessOps( scheduleBannerClear(); } }, - [setKind, scheduleBannerClear], + [setKind, scheduleBannerClear, runAction], ); const load = useCallback( diff --git a/packages/webui/src/hooks/use-onebot-instance-config.ts b/packages/webui/src/hooks/use-onebot-instance-config.ts index 202b9a15..47fe747e 100644 --- a/packages/webui/src/hooks/use-onebot-instance-config.ts +++ b/packages/webui/src/hooks/use-onebot-instance-config.ts @@ -1,4 +1,5 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useActionFeedback } from '@/contexts/ActionFeedbackContext'; import type { OneBotConfig, QQInfo } from '@/types'; import { useApi } from '@/lib/api'; @@ -50,6 +51,7 @@ export function useOneBotInstanceConfig( options: UseOneBotInstanceConfigOptions, ): UseOneBotInstanceConfig { const api = useApi(); + const { runAction } = useActionFeedback(); const { selectedUin, onSelectedUinChange } = options; const [config, setConfigState] = useState(null); const [savedSnapshot, setSavedSnapshot] = useState(null); @@ -152,8 +154,35 @@ export function useOneBotInstanceConfig( setSaveStatus('保存中...'); setSaveStatusTone('saving'); try { - const result = await api.config.save(uin, target); + const result = await runAction( + { + title: '正在保存账号配置', + detail: `账号 ${uin}`, + successTitle: '账号配置已更新', + successDetail: (saved) => ( + !saved.online + ? '配置已保存,将在账号下次连接时应用' + : saved.applied + ? '配置已保存并完成热重载' + : '配置已保存' + ), + errorTitle: '账号配置更新失败', + resultError: (saved) => { + if (!saved.saved) return saved.message || '服务器未确认配置已保存'; + if (saved.online && !saved.applied) { + return `配置已保存,但热重载失败${saved.errors[0]?.message ? `:${saved.errors[0].message}` : ''}`; + } + return null; + }, + }, + () => api.config.save(uin, target), + ); if (selectedUinRef.current !== uin || saveGenerationRef.current !== generation) return; + if (!result.saved) { + setSaveStatus(`保存失败:${result.message || '服务器未确认配置已保存'}`); + setSaveStatusTone('error'); + return; + } setSavedSnapshot(JSON.stringify(result.config)); if (editRevisionRef.current === editRevision) { setConfigState(result.config); @@ -182,7 +211,7 @@ export function useOneBotInstanceConfig( scheduleStatusClear(uin, generation); } } - }, [api, selectedUin, config, scheduleStatusClear]); + }, [api, selectedUin, config, scheduleStatusClear, runAction]); return { selectedUin, diff --git a/packages/webui/src/router/app-layout.tsx b/packages/webui/src/router/app-layout.tsx index df770481..9877ad82 100644 --- a/packages/webui/src/router/app-layout.tsx +++ b/packages/webui/src/router/app-layout.tsx @@ -94,9 +94,13 @@ export function AppLayout() { const refreshUpdate = useCallback(async (force = false) => { try { - setUpdateInfo(await api.update.check(force)); + const next = await api.update.check(force); + setUpdateInfo(next); + return next; } catch (e) { console.error('update-check', e); + if (force) throw e; + return null; } }, [api]); diff --git a/packages/webui/tests/action-feedback.test.ts b/packages/webui/tests/action-feedback.test.ts new file mode 100644 index 00000000..ca62ea1f --- /dev/null +++ b/packages/webui/tests/action-feedback.test.ts @@ -0,0 +1,70 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { + actionErrorMessage, + publishActionResult, + scheduleActionNoticeDismiss, +} from '../src/contexts/ActionFeedbackContext'; + +describe('action feedback error details', () => { + it('preserves the real Error message', () => { + expect(actionErrorMessage(new Error('证书校验失败'))).toBe('证书校验失败'); + }); + + it('preserves a non-empty string rejection', () => { + expect(actionErrorMessage('保存被拒绝')).toBe('保存被拒绝'); + }); + + it('makes an unknown rejection observable', () => { + expect(actionErrorMessage({ code: 'E_UNKNOWN' })).toBe('未知错误'); + }); +}); + +describe('action feedback result publishing', () => { + it('publishes a superseded action result without replacing the active surface', () => { + const updateCurrentActivity = vi.fn(); + const publishNotice = vi.fn(); + + publishActionResult(false, updateCurrentActivity, publishNotice); + + expect(updateCurrentActivity).not.toHaveBeenCalled(); + expect(publishNotice).toHaveBeenCalledOnce(); + }); + + it('updates and publishes the current action result', () => { + const updateCurrentActivity = vi.fn(); + const publishNotice = vi.fn(); + + publishActionResult(true, updateCurrentActivity, publishNotice); + + expect(updateCurrentActivity).toHaveBeenCalledOnce(); + expect(publishNotice).toHaveBeenCalledOnce(); + }); +}); + +describe('action feedback auto-dismiss', () => { + afterEach(() => { + vi.useRealTimers(); + }); + + it('dismisses a completed notice after its visible countdown', () => { + vi.useFakeTimers(); + const dismiss = vi.fn(); + + scheduleActionNoticeDismiss(dismiss); + vi.advanceTimersByTime(4_999); + expect(dismiss).not.toHaveBeenCalled(); + vi.advanceTimersByTime(1); + expect(dismiss).toHaveBeenCalledOnce(); + }); + + it('cancels dismissal when the notice unmounts early', () => { + vi.useFakeTimers(); + const dismiss = vi.fn(); + + const cancel = scheduleActionNoticeDismiss(dismiss); + cancel(); + vi.runAllTimers(); + + expect(dismiss).not.toHaveBeenCalled(); + }); +});