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.
This commit is contained in:
DrSmoothl committed 2026-08-01 00:40:44 +08:00
1 parent 8080104311
commit 958d17ecc0
11 files changed
+365 -29

No files matched your search

+4
View File
@@ -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
+109 -27
View File
@@ -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<string | null>(null);
const [needsConsent, setNeedsConsent] = useState(false);
const [onboardingFinished, setOnboardingFinished] = useState(false);
const [replayingOnboarding, setReplayingOnboarding] = useState(
() => typeof window !== 'undefined' && isDeveloperOnboardingLocation(window.location),
);
const onboardingReturnPath = useRef<string | null>(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<string, unknown>
: {};
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 = <Splash>{authChecked ? '加载中…' : '初始化中…'}</Splash>;
@@ -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 = (
<OnboardingGate
payload={agreements}
needsConsent={needsConsent}
mustChangePassword={mustChange}
needsConsent={replayingOnboarding || needsConsent}
mustChangePassword={replayingOnboarding || mustChange}
replay={replayingOnboarding}
additionalSteps={onboardingSteps}
knownOldPassword={loginPassword}
onConsentComplete={() => 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 = (
<SessionProvider value={{ status, onLogoutComplete: handleLoggedOut }}>
<SessionProvider
value={{
status,
onLogoutComplete: handleLoggedOut,
restartOnboarding,
}}
>
<RouterProvider router={appRouter} />
</SessionProvider>
);
@@ -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 (
<OnboardingWizardPage
documents={payload.documents}
agreementVersion={payload.version}
needsConsent={needsConsent}
mustChangePassword={mustChangePassword}
knownOldPassword={knownOldPassword}
onDecline={onDecline}
onConsentComplete={onConsentComplete}
onPasswordComplete={onPasswordComplete}
onComplete={onComplete}
additionalSteps={additionalSteps}
checkStrength={(password) => 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 (
<OnboardingWizardPage
documents={payload.documents}
agreementVersion={payload.version}
needsConsent={needsConsent}
mustChangePassword={mustChangePassword}
knownOldPassword={knownOldPassword}
passwordMode={execution.passwordMode}
onDecline={onDecline}
onConsentComplete={replay ? () => undefined : onConsentComplete}
onPasswordComplete={replay ? () => undefined : onPasswordComplete}
onComplete={onComplete}
additionalSteps={additionalSteps}
checkStrength={(password) => api.checkPasswordStrength(password)}
submitPassword={execution.actions.changePassword}
onAccept={execution.actions.acceptAgreements}
/>
);
}
@@ -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' && <StoragePanel />}
{tab === 'notifications' && <NotificationsPanel />}
{tab === 'globalConfig' && <GlobalConfigPanel />}
{tab === 'developer' && <DeveloperPanel />}
{tab === 'about' && <AboutPanel />}
</motion.div>
</div>
@@ -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 (
<div className="flex flex-col gap-5">
{/* Event-handler errors bypass React boundaries; the probe throws on render. */}
<DeveloperCrashProbe requested={crashRequested} />
<Group
title="界面测试"
icon={Bug}
description="直接验证首次使用流程与页面级异常恢复;这些工具始终可见,不受环境开关限制。"
>
<SettingRow
label="首次使用引导"
hint="以演练模式重新进入完整引导,不会修改协议确认记录或真实访问密码。"
>
<Button variant="outline" size="sm" onClick={() => setConfirmOnboarding(true)}>
<RotateCcw className="size-4" /> 重新进入
</Button>
</SettingRow>
<SettingRow
label="崩溃界面"
hint="主动抛出测试异常并交给页面错误边界;在崩溃界面点击“重试”即可返回。"
>
<Button variant="destructive" size="sm" onClick={() => setConfirmCrash(true)}>
<AlertTriangle className="size-4" /> 触发崩溃
</Button>
</SettingRow>
</Group>
<ConfirmDialog
open={confirmOnboarding}
onOpenChange={setConfirmOnboarding}
title="重新进入首次使用引导?"
description="将以演练模式展示完整流程,不会修改协议确认记录或真实访问密码。"
confirmText="进入引导"
onConfirm={restartOnboarding}
/>
<ConfirmDialog
open={confirmCrash}
onOpenChange={setConfirmCrash}
title="触发 WebUI 崩溃测试?"
description="当前设置页面将主动抛出测试异常,并交由崩溃界面接管。"
confirmText="触发崩溃"
destructive
onConfirm={() => requestCrash('confirm')}
/>
</div>
);
}
// ─────────────── 关于 ───────────────
const REPO_URL = 'https://github.com/SnowLuma/SnowLuma';
@@ -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;
}
@@ -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<SessionValue | null>(null);
@@ -0,0 +1,31 @@
export interface OnboardingActionResult {
success: boolean;
message?: string;
}
export interface OnboardingActions {
acceptAgreements: () => Promise<OnboardingActionResult>;
changePassword: (
oldPassword: string,
newPassword: string,
) => Promise<OnboardingActionResult>;
}
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 };
}
@@ -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<string, unknown>)[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;
}
+1 -1
View File
@@ -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({
@@ -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(
<DeveloperCrashProbe requested={requested} />,
)).toThrowError(DEVELOPER_CRASH_MESSAGE);
const html = renderToStaticMarkup(
<ErrorPage error={new Error(DEVELOPER_CRASH_MESSAGE)} reset={() => undefined} />,
);
expect(html).toContain('页面出错了');
expect(html).toContain('重试');
expect(html).toContain(DEVELOPER_CRASH_MESSAGE);
});
});
@@ -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');
});
});
@@ -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();
});
});