From 958d17ecc07124da130ebbba8d2572719f4be493 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sat, 1 Aug 2026 00:40:44 +0800 Subject: [PATCH] feat(webui): add developer settings tools Expose onboarding replay and page crash testing from a dedicated settings page.\n\nKeep replay actions isolated from persisted consent and password state. --- packages/webui/README.md | 4 + packages/webui/src/App.tsx | 136 ++++++++++++++---- .../src/components/pages/settings-page.tsx | 66 ++++++++- .../components/settings/developer-tools.ts | 19 +++ .../webui/src/contexts/SessionContext.tsx | 2 + packages/webui/src/lib/onboarding-actions.ts | 31 ++++ .../webui/src/lib/onboarding-navigation.ts | 27 ++++ packages/webui/src/router/index.tsx | 2 +- packages/webui/tests/developer-tools.test.tsx | 29 ++++ .../webui/tests/onboarding-actions.test.ts | 34 +++++ .../webui/tests/onboarding-navigation.test.ts | 44 ++++++ 11 files changed, 365 insertions(+), 29 deletions(-) create mode 100644 packages/webui/src/components/settings/developer-tools.ts create mode 100644 packages/webui/src/lib/onboarding-actions.ts create mode 100644 packages/webui/src/lib/onboarding-navigation.ts create mode 100644 packages/webui/tests/developer-tools.test.tsx create mode 100644 packages/webui/tests/onboarding-actions.test.ts create mode 100644 packages/webui/tests/onboarding-navigation.test.ts diff --git a/packages/webui/README.md b/packages/webui/README.md index 08955be4..96758745 100644 --- a/packages/webui/README.md +++ b/packages/webui/README.md @@ -23,6 +23,10 @@ status, OneBot configuration, logs, storage, and server settings. - Password change flows use floating labels and inline validation consistently. - Password strength details appear only while the new-password field has focus and leave with the same motion language when focus moves away. +- The first-run wizard keeps agreement text as the primary reading surface and + aligns each step's actions inside one responsive footer. Settings includes a + visible developer page for safely replaying this wizard and exercising the + page-level crash screen; replayed consent and passwords are never persisted. ## Local development diff --git a/packages/webui/src/App.tsx b/packages/webui/src/App.tsx index 3bb59e84..353e3171 100644 --- a/packages/webui/src/App.tsx +++ b/packages/webui/src/App.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { RouterProvider } from '@tanstack/react-router'; import { AlertTriangle, LogOut, RefreshCw } from 'lucide-react'; import { Button } from '@/components/ui/button'; @@ -25,6 +25,15 @@ import { } from '@/contexts/ActionFeedbackContext'; import type { AgreementsPayload } from '@/lib/api/types'; import { appRouter } from '@/router'; +import { + browserPath, + DEVELOPER_ONBOARDING_RETURN_KEY, + DEVELOPER_ONBOARDING_URL, + DEVELOPER_SETTINGS_URL, + developerOnboardingReturnPath, + isDeveloperOnboardingLocation, +} from '@/lib/onboarding-navigation'; +import { onboardingExecution } from '@/lib/onboarding-actions'; interface AppProps { onboardingSteps?: AdditionalOnboardingStep[]; @@ -72,6 +81,10 @@ function AuthBoundary({ onboardingSteps }: { onboardingSteps: AdditionalOnboardi const [agreementsError, setAgreementsError] = useState(null); const [needsConsent, setNeedsConsent] = useState(false); const [onboardingFinished, setOnboardingFinished] = useState(false); + const [replayingOnboarding, setReplayingOnboarding] = useState( + () => typeof window !== 'undefined' && isDeveloperOnboardingLocation(window.location), + ); + const onboardingReturnPath = useRef(null); // The password from *this* session's login, carried into the forced // change-password gate so it doesn't have to render an old-password field // (which browsers autofill, misleading users on upgrade). Stays undefined @@ -145,6 +158,8 @@ function AuthBoundary({ onboardingSteps }: { onboardingSteps: AdditionalOnboardi setAgreementsError(null); setNeedsConsent(false); setOnboardingFinished(false); + setReplayingOnboarding(false); + onboardingReturnPath.current = null; setLoginPassword(undefined); }, []); @@ -153,6 +168,47 @@ function AuthBoundary({ onboardingSteps }: { onboardingSteps: AdditionalOnboardi handleLoggedOut(); }, [client, handleLoggedOut]); + const restartOnboarding = useCallback(() => { + const currentPath = browserPath(window.location); + const returnPath = isDeveloperOnboardingLocation(window.location) + ? DEVELOPER_SETTINGS_URL + : currentPath; + onboardingReturnPath.current = returnPath; + const currentState = typeof window.history.state === 'object' && window.history.state !== null + ? window.history.state as Record + : {}; + setReplayingOnboarding(true); + appRouter.history.push( + DEVELOPER_ONBOARDING_URL, + { ...currentState, [DEVELOPER_ONBOARDING_RETURN_KEY]: returnPath }, + ); + }, []); + + const exitOnboardingReplay = useCallback(() => { + const returnPath = onboardingReturnPath.current + ?? developerOnboardingReturnPath(window.history.state); + onboardingReturnPath.current = null; + + if (returnPath && isDeveloperOnboardingLocation(window.location)) { + // The developer page pushed the replay entry, so browser Back is the + // authoritative way to restore both the URL and its router history. + appRouter.history.back(); + return; + } + + appRouter.history.replace(returnPath ?? DEVELOPER_SETTINGS_URL); + setReplayingOnboarding(false); + }, []); + + useEffect(() => { + const syncReplayToLocation = () => { + const replaying = isDeveloperOnboardingLocation(appRouter.history.location); + if (!replaying) onboardingReturnPath.current = null; + setReplayingOnboarding(replaying); + }; + return appRouter.history.subscribe(syncReplayToLocation); + }, []); + let view: React.ReactNode; if (authLoading || showAuthSkeleton) { view = {authChecked ? '加载中…' : '初始化中…'}; @@ -177,12 +233,19 @@ function AuthBoundary({ onboardingSteps }: { onboardingSteps: AdditionalOnboardi onLogout={() => { void handleDecline(); }} /> ); - } else if (!onboardingFinished && (needsConsent || mustChange || onboardingSteps.length > 0) && agreements) { + } else if ( + agreements + && ( + replayingOnboarding + || (!onboardingFinished && (needsConsent || mustChange || onboardingSteps.length > 0)) + ) + ) { view = ( setNeedsConsent(false)} @@ -190,14 +253,26 @@ function AuthBoundary({ onboardingSteps }: { onboardingSteps: AdditionalOnboardi setMustChange(false); setLoginPassword(undefined); }} - onComplete={() => setOnboardingFinished(true)} + onComplete={() => { + if (replayingOnboarding) { + exitOnboardingReplay(); + return; + } + setOnboardingFinished(true); + }} onStale={refreshAgreements} - onDecline={handleDecline} + onDecline={replayingOnboarding ? exitOnboardingReplay : handleDecline} /> ); } else { view = ( - + ); @@ -300,6 +375,7 @@ function OnboardingGate({ payload, needsConsent, mustChangePassword, + replay, knownOldPassword, onConsentComplete, onPasswordComplete, @@ -311,6 +387,7 @@ function OnboardingGate({ payload: AgreementsPayload; needsConsent: boolean; mustChangePassword: boolean; + replay: boolean; knownOldPassword?: string; onConsentComplete: () => void; onPasswordComplete: () => void; @@ -321,21 +398,11 @@ function OnboardingGate({ }) { const api = useApi(); const { runAction } = useActionFeedback(); - return ( - api.checkPasswordStrength(password)} - submitPassword={(oldPassword, newPassword) => api.changePassword(oldPassword, newPassword)} - onAccept={async () => { + const execution = onboardingExecution( + replay, + { + changePassword: (oldPassword, newPassword) => api.changePassword(oldPassword, newPassword), + acceptAgreements: async () => { const result = await runAction( { title: '正在记录协议确认', @@ -346,16 +413,31 @@ function OnboardingGate({ }, () => api.agreements.recordConsent(payload.version), ); - if (result.success) { - return { success: true }; - } - // 409: the agreement text changed under us — re-fetch and re-prompt. + if (result.success) return { success: true }; if (result.currentVersion && result.currentVersion !== payload.version) { onStale(); return { success: false, message: '协议已更新,已为你载入最新版本,请重新阅读后确认。' }; } return { success: false, message: result.message ?? '提交失败,请重试' }; - }} + }, + }, + ); + return ( + undefined : onConsentComplete} + onPasswordComplete={replay ? () => undefined : onPasswordComplete} + onComplete={onComplete} + additionalSteps={additionalSteps} + checkStrength={(password) => api.checkPasswordStrength(password)} + submitPassword={execution.actions.changePassword} + onAccept={execution.actions.acceptAgreements} /> ); } diff --git a/packages/webui/src/components/pages/settings-page.tsx b/packages/webui/src/components/pages/settings-page.tsx index c37a2009..b38e065b 100644 --- a/packages/webui/src/components/pages/settings-page.tsx +++ b/packages/webui/src/components/pages/settings-page.tsx @@ -1,4 +1,4 @@ -import { createContext, useContext, useId, useRef, useState, type ComponentProps, type ReactNode } from 'react'; +import { createContext, useContext, useId, useReducer, useRef, useState, type ComponentProps, type ReactNode } from 'react'; import { motion } from 'motion/react'; import { Accessibility, AlertTriangle, Bell, Bug, Check, Clock, Code2, Download, ExternalLink, Github, Image as ImageIcon, @@ -34,6 +34,7 @@ import { } from '@/contexts/ThemeContext'; import { DEFAULT_LAYOUT, DEFAULT_PAGES, reconcileLayoutItems, useLayout } from '@/contexts/LayoutContext'; import { useActionFeedback } from '@/contexts/ActionFeedbackContext'; +import { useSession } from '@/contexts/SessionContext'; import { NAV_ITEMS } from '@/components/layout/sidebar'; import { TOPBAR_CATALOGUE } from '@/components/layout/top-bar'; import { ChangePasswordDialog } from '@/components/change-password-dialog'; @@ -48,6 +49,10 @@ import { NotificationsPanel } from '@/components/settings/notifications-panel'; import { GlobalConfigPanel } from '@/components/settings/global-config-panel'; import { SystemPanel } from '@/components/settings/system-panel'; import { StoragePanel } from '@/components/settings/storage-panel'; +import { + DeveloperCrashProbe, + developerCrashReducer, +} from '@/components/settings/developer-tools'; interface TabDef { key: SettingsTab; label: string; icon: typeof Sun } @@ -77,6 +82,7 @@ const TAB_GROUPS: { title: string; tabs: TabDef[] }[] = [ tabs: [ { key: 'system', label: '服务', icon: Server }, { key: 'advanced', label: '高级', icon: Code2 }, + { key: 'developer', label: '开发者', icon: Bug }, { key: 'about', label: '关于', icon: Info }, ], }, @@ -115,6 +121,7 @@ export function SettingsPage() { {tab === 'storage' && } {tab === 'notifications' && } {tab === 'globalConfig' && } + {tab === 'developer' && } {tab === 'about' && } @@ -1254,6 +1261,63 @@ function AccountPanel() { ); } +// ─────────────── 开发者 ─────────────── + +function DeveloperPanel() { + const { restartOnboarding } = useSession(); + const [confirmOnboarding, setConfirmOnboarding] = useState(false); + const [confirmCrash, setConfirmCrash] = useState(false); + const [crashRequested, requestCrash] = useReducer(developerCrashReducer, false); + + return ( +
+ {/* Event-handler errors bypass React boundaries; the probe throws on render. */} + + + + + + + + + + + + + requestCrash('confirm')} + /> +
+ ); +} + // ─────────────── 关于 ─────────────── const REPO_URL = 'https://github.com/SnowLuma/SnowLuma'; diff --git a/packages/webui/src/components/settings/developer-tools.ts b/packages/webui/src/components/settings/developer-tools.ts new file mode 100644 index 00000000..b028c3d9 --- /dev/null +++ b/packages/webui/src/components/settings/developer-tools.ts @@ -0,0 +1,19 @@ +export const DEVELOPER_CRASH_MESSAGE = '开发者工具主动触发的 WebUI 崩溃测试'; + +/** Throws the deliberate render-time exception used to exercise ErrorPage. */ +export function raiseDeveloperCrash(): never { + throw new Error(DEVELOPER_CRASH_MESSAGE); +} + +export function developerCrashReducer( + _requested: boolean, + action: 'confirm', +): boolean { + if (action === 'confirm') return true; + throw new Error(`Unknown developer crash action: ${String(action)}`); +} + +export function DeveloperCrashProbe({ requested }: { requested: boolean }): null { + if (requested) raiseDeveloperCrash(); + return null; +} diff --git a/packages/webui/src/contexts/SessionContext.tsx b/packages/webui/src/contexts/SessionContext.tsx index bd6a7b05..4c3b587b 100644 --- a/packages/webui/src/contexts/SessionContext.tsx +++ b/packages/webui/src/contexts/SessionContext.tsx @@ -9,6 +9,8 @@ export interface SessionValue { status: string; /** Invoked by AppLayout's logout handler after it has scrubbed its own state. */ onLogoutComplete: () => void; + /** Replays the first-run wizard without changing persisted account state. */ + restartOnboarding: () => void; } const SessionContext = createContext(null); diff --git a/packages/webui/src/lib/onboarding-actions.ts b/packages/webui/src/lib/onboarding-actions.ts new file mode 100644 index 00000000..30e198e5 --- /dev/null +++ b/packages/webui/src/lib/onboarding-actions.ts @@ -0,0 +1,31 @@ +export interface OnboardingActionResult { + success: boolean; + message?: string; +} + +export interface OnboardingActions { + acceptAgreements: () => Promise; + changePassword: ( + oldPassword: string, + newPassword: string, + ) => Promise; +} + +export interface OnboardingExecution { + passwordMode: 'change' | 'rehearsal'; + actions: OnboardingActions; +} + +const REHEARSAL_ACTIONS: OnboardingActions = { + acceptAgreements: async () => ({ success: true }), + changePassword: async () => ({ success: true }), +}; + +export function onboardingExecution( + replaying: boolean, + liveActions: OnboardingActions, +): OnboardingExecution { + return replaying + ? { passwordMode: 'rehearsal', actions: REHEARSAL_ACTIONS } + : { passwordMode: 'change', actions: liveActions }; +} diff --git a/packages/webui/src/lib/onboarding-navigation.ts b/packages/webui/src/lib/onboarding-navigation.ts new file mode 100644 index 00000000..9791136a --- /dev/null +++ b/packages/webui/src/lib/onboarding-navigation.ts @@ -0,0 +1,27 @@ +export const DEVELOPER_ONBOARDING_URL = '/onboarding?mode=developer'; +export const DEVELOPER_SETTINGS_URL = '/settings?tab=developer'; +export const DEVELOPER_ONBOARDING_RETURN_KEY = 'snowlumaOnboardingReturnTo'; + +interface LocationLike { + pathname: string; + search: string; + hash?: string; +} + +export function isDeveloperOnboardingLocation(location: LocationLike): boolean { + if (location.pathname !== '/onboarding') return false; + return new URLSearchParams(location.search).get('mode') === 'developer'; +} + +export function browserPath(location: LocationLike): string { + return `${location.pathname}${location.search}${location.hash ?? ''}`; +} + +export function developerOnboardingReturnPath(state: unknown): string | null { + if (typeof state !== 'object' || state === null) return null; + const candidate = (state as Record)[DEVELOPER_ONBOARDING_RETURN_KEY]; + if (typeof candidate !== 'string') return null; + if (!candidate.startsWith('/') || candidate.startsWith('//')) return null; + if (candidate.startsWith('/onboarding')) return null; + return candidate; +} diff --git a/packages/webui/src/router/index.tsx b/packages/webui/src/router/index.tsx index f7ee26e6..1a833050 100644 --- a/packages/webui/src/router/index.tsx +++ b/packages/webui/src/router/index.tsx @@ -74,7 +74,7 @@ const debugRoute = createRoute({ }); /** Settings sub-tabs — also the contract for the `?tab=` deep link. */ -export const SETTINGS_TABS = ['appearance', 'data', 'advanced', 'account', 'system', 'storage', 'notifications', 'globalConfig', 'about'] as const; +export const SETTINGS_TABS = ['appearance', 'data', 'advanced', 'account', 'system', 'storage', 'notifications', 'globalConfig', 'developer', 'about'] as const; export type SettingsTab = (typeof SETTINGS_TABS)[number]; export const settingsRoute = createRoute({ diff --git a/packages/webui/tests/developer-tools.test.tsx b/packages/webui/tests/developer-tools.test.tsx new file mode 100644 index 00000000..e1dae7b9 --- /dev/null +++ b/packages/webui/tests/developer-tools.test.tsx @@ -0,0 +1,29 @@ +import { renderToStaticMarkup } from 'react-dom/server'; +import { describe, expect, it } from 'vitest'; +import { + DEVELOPER_CRASH_MESSAGE, + DeveloperCrashProbe, + developerCrashReducer, +} from '../src/components/settings/developer-tools'; +import { ErrorPage } from '../src/components/pages/status-screens'; +import { SETTINGS_TABS } from '../src/router'; + +describe('developer settings tools', () => { + it('keeps the developer page in the public settings route contract', () => { + expect(SETTINGS_TABS).toContain('developer'); + }); + + it('promotes a confirmed crash into the route error screen', () => { + const requested = developerCrashReducer(false, 'confirm'); + expect(() => renderToStaticMarkup( + , + )).toThrowError(DEVELOPER_CRASH_MESSAGE); + + const html = renderToStaticMarkup( + undefined} />, + ); + expect(html).toContain('页面出错了'); + expect(html).toContain('重试'); + expect(html).toContain(DEVELOPER_CRASH_MESSAGE); + }); +}); diff --git a/packages/webui/tests/onboarding-actions.test.ts b/packages/webui/tests/onboarding-actions.test.ts new file mode 100644 index 00000000..0d03bb79 --- /dev/null +++ b/packages/webui/tests/onboarding-actions.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it, vi } from 'vitest'; +import { onboardingExecution } from '../src/lib/onboarding-actions'; + +describe('developer onboarding rehearsal', () => { + it('completes consent and password steps without writing persistent state', async () => { + const acceptAgreements = vi.fn(async () => ({ success: true })); + const changePassword = vi.fn(async () => ({ success: true })); + const execution = onboardingExecution(true, { + acceptAgreements, + changePassword, + }); + + expect(execution.passwordMode).toBe('rehearsal'); + await expect(execution.actions.acceptAgreements()).resolves.toEqual({ success: true }); + await expect(execution.actions.changePassword('old', 'new')).resolves.toEqual({ success: true }); + expect(acceptAgreements).not.toHaveBeenCalled(); + expect(changePassword).not.toHaveBeenCalled(); + }); + + it('keeps real onboarding wired to persistent actions', async () => { + const acceptAgreements = vi.fn(async () => ({ success: true })); + const changePassword = vi.fn(async () => ({ success: true })); + const execution = onboardingExecution(false, { + acceptAgreements, + changePassword, + }); + + expect(execution.passwordMode).toBe('change'); + await execution.actions.acceptAgreements(); + await execution.actions.changePassword('old', 'new'); + expect(acceptAgreements).toHaveBeenCalledOnce(); + expect(changePassword).toHaveBeenCalledWith('old', 'new'); + }); +}); diff --git a/packages/webui/tests/onboarding-navigation.test.ts b/packages/webui/tests/onboarding-navigation.test.ts new file mode 100644 index 00000000..da9fea4e --- /dev/null +++ b/packages/webui/tests/onboarding-navigation.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from 'vitest'; +import { + browserPath, + DEVELOPER_ONBOARDING_RETURN_KEY, + developerOnboardingReturnPath, + isDeveloperOnboardingLocation, +} from '../src/lib/onboarding-navigation'; + +describe('developer onboarding navigation', () => { + it('recognizes only the dedicated developer replay URL', () => { + expect(isDeveloperOnboardingLocation({ + pathname: '/onboarding', + search: '?mode=developer', + })).toBe(true); + expect(isDeveloperOnboardingLocation({ pathname: '/onboarding', search: '' })).toBe(false); + expect(isDeveloperOnboardingLocation({ + pathname: '/settings', + search: '?mode=developer', + })).toBe(false); + }); + + it('preserves the complete local return path', () => { + expect(browserPath({ + pathname: '/settings', + search: '?tab=developer', + hash: '#tools', + })).toBe('/settings?tab=developer#tools'); + }); + + it('accepts only local non-onboarding return paths from history state', () => { + expect(developerOnboardingReturnPath({ + [DEVELOPER_ONBOARDING_RETURN_KEY]: '/settings?tab=developer', + })).toBe('/settings?tab=developer'); + expect(developerOnboardingReturnPath({ + [DEVELOPER_ONBOARDING_RETURN_KEY]: 'https://example.com', + })).toBeNull(); + expect(developerOnboardingReturnPath({ + [DEVELOPER_ONBOARDING_RETURN_KEY]: '//example.com', + })).toBeNull(); + expect(developerOnboardingReturnPath({ + [DEVELOPER_ONBOARDING_RETURN_KEY]: '/onboarding?mode=developer', + })).toBeNull(); + }); +});