feat(webui): unify first-run onboarding

Combine agreement consent and password setup into one ordered first-run flow.

Allow future steps to declare skip policy while honoring unattended deployment requirements.
This commit is contained in:
DrSmoothl committed 2026-07-31 17:39:12 +08:00
1 parent 5b68ca5bd3
commit a361ee512e
10 files changed
+936 -312

No files matched your search

+4 -2
View File
@@ -70,12 +70,12 @@ chmod +x launcher.sh
### 3. 打开 WebUI
浏览器访问 [`http://localhost:5099`](http://localhost:5099)。初始账号为 `admin`,随机密码会显示在启动日志中;登录后即可接入已启动的 QQ 进程并配置 OneBot 连接。
浏览器访问 [`http://localhost:5099`](http://localhost:5099)。初始账号为 `admin`,随机密码会显示在启动日志中;首次登录后,WebUI 会在同一个引导流程中完成协议确认与访问密码设置,随后即可接入已启动的 QQ 进程并配置 OneBot 连接。
<details>
<summary><strong>无人值守部署:通过环境变量确认协议</strong></summary>
同时设置以下两个变量可跳过 WebUI 的协议确认页面:
同时设置以下两个变量可跳过 WebUI 首次使用引导中的协议确认步骤:
```bash
SNOWLUMA_ACCEPT_EULA=1
@@ -84,6 +84,8 @@ SNOWLUMA_ACCEPT_PRIVACY=1
两项必须同时设置,且环境变量确认不会写入持久化同意记录。设置变量即表示运营者已阅读并同意 [`EULA.md`](EULA.md) 与 [`PRIVACY.md`](PRIVACY.md)。
全新无人值守部署还可以使用 `SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD` 预设 WebUI 密码(至少 8 位);由该变量初始化的密码不再要求进入强制修改步骤。已有 `config/webui.json` 时仍以现有凭据为准。
</details>
## 可选:登录时补齐云端历史
+50 -40
View File
@@ -7,8 +7,10 @@ import { TooltipProvider } from '@/components/ui/tooltip';
import { ThemeProvider } from '@/contexts/ThemeContext';
import { SessionProvider } from '@/contexts/SessionContext';
import { LoginPage } from '@/components/pages/login-page';
import { ChangePasswordPage } from '@/components/pages/change-password-page';
import { ConsentPage } from '@/components/pages/consent-page';
import {
OnboardingWizardPage,
type AdditionalOnboardingStep,
} from '@/components/pages/onboarding-wizard-page';
import { SkeletonSwap, useSkeletonSwap } from '@/components/interior/skeleton-swap';
import { ApiProvider, createApiClient, useApi, type ApiClient } from '@/lib/api';
import { DebugTaskProvider } from '@/contexts/DebugTaskContext';
@@ -24,14 +26,18 @@ import {
import type { AgreementsPayload } from '@/lib/api/types';
import { appRouter } from '@/router';
export default function App() {
interface AppProps {
onboardingSteps?: AdditionalOnboardingStep[];
}
export default function App({ onboardingSteps = [] }: AppProps) {
return (
<ActionFeedbackProvider>
<ThemeProvider>
<ActionFeedbackViewport />
<AdaptivePointer />
<GlobalContextMenu />
<AuthBoundary />
<AuthBoundary onboardingSteps={onboardingSteps} />
</ThemeProvider>
</ActionFeedbackProvider>
);
@@ -55,7 +61,7 @@ function consumeUrlToken(): string | null {
}
}
function AuthBoundary() {
function AuthBoundary({ onboardingSteps }: { onboardingSteps: AdditionalOnboardingStep[] }) {
const [authChecked, setAuthChecked] = useState(false);
const [authed, setAuthed] = useState(false);
const [mustChange, setMustChange] = useState(false);
@@ -65,6 +71,7 @@ function AuthBoundary() {
const [agreements, setAgreements] = useState<AgreementsPayload | null>(null);
const [agreementsError, setAgreementsError] = useState<string | null>(null);
const [needsConsent, setNeedsConsent] = useState(false);
const [onboardingFinished, setOnboardingFinished] = useState(false);
// 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
@@ -137,6 +144,7 @@ function AuthBoundary() {
setAgreements(null);
setAgreementsError(null);
setNeedsConsent(false);
setOnboardingFinished(false);
setLoginPassword(undefined);
}, []);
@@ -156,6 +164,7 @@ function AuthBoundary() {
setStatus('已连接');
setMustChange(needsChange);
setLoginPassword(password);
setOnboardingFinished(false);
void refreshAgreements();
}}
/>
@@ -168,23 +177,22 @@ function AuthBoundary() {
onLogout={() => { void handleDecline(); }}
/>
);
} else if (needsConsent && agreements) {
} else if (!onboardingFinished && (needsConsent || mustChange || onboardingSteps.length > 0) && agreements) {
view = (
<ConsentGate
<OnboardingGate
payload={agreements}
onAccepted={() => setNeedsConsent(false)}
onStale={refreshAgreements}
onDecline={handleDecline}
/>
);
} else if (mustChange) {
view = (
<ForcedChangePasswordGate
needsConsent={needsConsent}
mustChangePassword={mustChange}
additionalSteps={onboardingSteps}
knownOldPassword={loginPassword}
onSuccess={() => {
onConsentComplete={() => setNeedsConsent(false)}
onPasswordComplete={() => {
setMustChange(false);
setLoginPassword(undefined);
}}
onComplete={() => setOnboardingFinished(true)}
onStale={refreshAgreements}
onDecline={handleDecline}
/>
);
} else {
@@ -288,24 +296,45 @@ function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean, password: str
return <LoginPage onLogin={handleLogin} />;
}
function ConsentGate({
function OnboardingGate({
payload,
onAccepted,
needsConsent,
mustChangePassword,
knownOldPassword,
onConsentComplete,
onPasswordComplete,
onComplete,
additionalSteps,
onStale,
onDecline,
}: {
payload: AgreementsPayload;
onAccepted: () => void;
needsConsent: boolean;
mustChangePassword: boolean;
knownOldPassword?: string;
onConsentComplete: () => void;
onPasswordComplete: () => void;
onComplete: () => void;
additionalSteps: AdditionalOnboardingStep[];
onStale: () => void;
onDecline: () => void;
}) {
const api = useApi();
const { runAction } = useActionFeedback();
return (
<ConsentPage
<OnboardingWizardPage
documents={payload.documents}
version={payload.version}
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 result = await runAction(
{
@@ -318,7 +347,6 @@ function ConsentGate({
() => api.agreements.recordConsent(payload.version),
);
if (result.success) {
onAccepted();
return { success: true };
}
// 409: the agreement text changed under us — re-fetch and re-prompt.
@@ -331,21 +359,3 @@ function ConsentGate({
/>
);
}
function ForcedChangePasswordGate({
knownOldPassword,
onSuccess,
}: {
knownOldPassword?: string;
onSuccess: () => void;
}) {
const api = useApi();
return (
<ChangePasswordPage
knownOldPassword={knownOldPassword}
checkStrength={(p) => api.checkPasswordStrength(p)}
submit={(o, n) => api.changePassword(o, n)}
onSuccess={onSuccess}
/>
);
}
@@ -0,0 +1,436 @@
"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { KeyboardEvent, ReactNode } from "react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
const EASE = [0.23, 1, 0.32, 1] as const;
const EXIT_EASE = [0.4, 0, 1, 1] as const;
const RAIL = { type: "spring", stiffness: 520, damping: 40, mass: 0.5 } as const;
const CROSSFADE = { type: "spring", stiffness: 260, damping: 34, mass: 0.8 } as const;
export type WizardDirection = 1 | -1;
export type UseWizardOptions = {
total: number;
index?: number;
defaultIndex?: number;
onIndexChange?: (index: number, direction: WizardDirection) => void;
onComplete?: () => void;
};
function clampIndex(value: number, total: number) {
if (total < 1) return 0;
return Math.max(0, Math.min(total - 1, Math.trunc(value)));
}
export function useWizard({
total,
index,
defaultIndex = 0,
onIndexChange,
onComplete,
}: UseWizardOptions) {
const [internal, setInternal] = useState(() => clampIndex(defaultIndex, total));
const current = clampIndex(index ?? internal, total);
const [seen, setSeen] = useState<{ index: number; direction: WizardDirection }>({
index: current,
direction: 1,
});
if (seen.index !== current) {
setSeen({ index: current, direction: current > seen.index ? 1 : -1 });
}
const [furthest, setFurthest] = useState(current);
if (furthest < current) setFurthest(current);
const emit = useRef(onIndexChange);
const finish = useRef(onComplete);
useEffect(() => {
emit.current = onIndexChange;
finish.current = onComplete;
}, [onIndexChange, onComplete]);
const controlled = index !== undefined;
const goTo = useCallback(
(to: number) => {
const target = clampIndex(to, total);
if (target === current) return;
const direction: WizardDirection = target > current ? 1 : -1;
if (!controlled) setInternal(target);
emit.current?.(target, direction);
},
[controlled, current, total],
);
const next = useCallback(() => {
if (current >= total - 1) {
finish.current?.();
return;
}
goTo(current + 1);
}, [current, goTo, total]);
const back = useCallback(() => goTo(current - 1), [current, goTo]);
return {
index: current,
direction: seen.direction,
furthest: Math.min(furthest, Math.max(total - 1, 0)),
total,
isFirst: current === 0,
isLast: current === total - 1,
next,
back,
goTo,
};
}
export type WizardStep = {
id: string;
label: string;
content: ReactNode;
canSkip?: boolean;
onSkip?: () => void;
hideAdvance?: boolean;
};
export type WizardStepsProps = {
steps: WizardStep[];
index?: number;
defaultIndex?: number;
onIndexChange?: (index: number, direction: WizardDirection) => void;
onComplete?: () => void;
complete?: boolean;
height?: number;
backLabel?: string;
nextLabel?: string;
finishLabel?: string;
skipLabel?: string;
completeLabel?: string;
completeHint?: string;
label?: string;
className?: string;
};
export function WizardSteps({
steps,
index,
defaultIndex = 0,
onIndexChange,
onComplete,
complete = false,
height = 184,
backLabel = "Back",
nextLabel = "Next",
finishLabel = "Finish",
skipLabel = "Skip",
completeLabel = "All set",
completeHint = "Step back to change anything",
label = "Steps",
className = "",
}: WizardStepsProps) {
const wizard = useWizard({
total: steps.length,
index,
defaultIndex,
onIndexChange,
onComplete,
});
const reduced = useReducedMotion();
const listRef = useRef<HTMLOListElement>(null);
const viewportRef = useRef<HTMLDivElement>(null);
const intent = useRef<"list" | "panel" | null>(null);
const {
index: at,
direction,
furthest,
total,
isFirst,
isLast,
next,
back,
goTo,
} = wizard;
useEffect(() => {
const move = intent.current;
intent.current = null;
if (move === "list") {
listRef.current
?.querySelector<HTMLButtonElement>('button[data-current="true"]')
?.focus();
return;
}
if (move === "panel") viewportRef.current?.focus({ preventScroll: true });
}, [at]);
const variants = useMemo(
() => ({
enter: (nextDirection: WizardDirection) => (
reduced ? { opacity: 0 } : { opacity: 0, x: nextDirection * 22 }
),
center: reduced ? { opacity: 1 } : { opacity: 1, x: 0 },
exit: (nextDirection: WizardDirection) => (
reduced
? { opacity: 0, transition: { duration: 0 } }
: {
opacity: 0,
x: nextDirection * -22,
transition: { duration: 0.14, ease: EXIT_EASE },
}
),
}),
[reduced],
);
const panelTransition = reduced ? { duration: 0 } : CROSSFADE;
const onStepKeyDown = (event: KeyboardEvent<HTMLElement>) => {
let target: number;
if (event.key === "ArrowRight" || event.key === "ArrowDown") target = at + 1;
else if (event.key === "ArrowLeft" || event.key === "ArrowUp") target = at - 1;
else if (event.key === "Home") target = 0;
else if (event.key === "End") target = furthest;
else return;
event.preventDefault();
target = Math.min(clampIndex(target, total), furthest);
if (target === at) return;
intent.current = "list";
goTo(target);
};
const step = steps[at];
if (!step) return null;
const position = `Step ${at + 1} of ${total}: ${step.label}`;
return (
<div className={`w-full ${className}`}>
<p aria-live="polite" className="sr-only">{position}</p>
<span
aria-hidden
className="mb-2 grid select-none text-[13px] font-medium text-foreground"
>
{steps.map((candidate, stepIndex) => (
<motion.span
key={candidate.id}
className="col-start-1 row-start-1 truncate"
initial={false}
animate={{ opacity: stepIndex === at ? 1 : 0 }}
transition={reduced ? { duration: 0 } : CROSSFADE}
>
{candidate.label}
</motion.span>
))}
</span>
<ol
ref={listRef}
aria-label={label}
className="mb-4 flex list-none items-center gap-1 p-0"
>
{steps.map((candidate, stepIndex) => {
const done = complete || stepIndex < at;
const here = !complete && stepIndex === at;
const tile = (
<motion.span
aria-hidden
className={`grid size-7 place-items-center rounded-[8px] border text-[11.5px] font-medium tabular-nums shadow-xs transition-colors duration-150 ${
done
? "border-foreground bg-foreground text-background"
: here
? "border-border bg-background text-foreground"
: "border-border bg-background text-muted-foreground"
}`}
initial={false}
animate={{ scale: here ? 1 : 0.92 }}
transition={reduced ? { duration: 0 } : RAIL}
>
{done ? (
<svg width="12" height="12" viewBox="0 0 256 256" fill="none" aria-hidden="true">
<polyline
points="216 72 104 184 48 128"
stroke="currentColor"
strokeWidth="24"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
) : (
stepIndex + 1
)}
</motion.span>
);
return (
<li key={candidate.id} className="flex flex-1 items-center gap-1 last:flex-none">
{stepIndex <= furthest ? (
<button
type="button"
data-current={here ? "true" : undefined}
tabIndex={here ? 0 : -1}
aria-current={here ? "step" : undefined}
aria-label={`Step ${stepIndex + 1} of ${total}: ${candidate.label}`}
onKeyDown={onStepKeyDown}
onClick={() => {
if (here) return;
intent.current = "list";
goTo(stepIndex);
}}
className="rounded-[8px] outline-none focus-visible:shadow-[0_0_0_1.5px_var(--ring)]"
>
{tile}
</button>
) : (
<span>
<span className="sr-only">
{`Step ${stepIndex + 1} of ${total}: ${candidate.label}`}
</span>
{tile}
</span>
)}
{stepIndex < total - 1 ? (
<span
aria-hidden
className="relative h-[3px] flex-1 overflow-hidden rounded-[2px] bg-muted shadow-[inset_0_1px_2px_rgb(0_0_0/0.07)]"
>
<motion.span
className="absolute inset-0 origin-left rounded-[2px] bg-foreground"
initial={false}
animate={{ scaleX: complete || stepIndex < at ? 1 : 0 }}
transition={reduced ? { duration: 0 } : RAIL}
/>
</span>
) : null}
</li>
);
})}
</ol>
<div
ref={viewportRef}
tabIndex={-1}
role="group"
aria-label={position}
style={{ height }}
className="relative overflow-hidden rounded-[11px] border border-border bg-card shadow-sm outline-none transition-[border-color,box-shadow] duration-150 focus-visible:border-ring"
>
<AnimatePresence initial={false} custom={direction}>
<motion.div
key={complete ? "__complete" : step.id}
custom={direction}
variants={variants}
initial="enter"
animate="center"
exit="exit"
transition={panelTransition}
style={{ scrollbarGutter: "stable" }}
className="absolute inset-0 overflow-y-auto overscroll-contain p-4 text-[13.5px] leading-relaxed text-foreground"
>
{complete ? (
<div className="flex h-full flex-col items-center justify-center gap-1.5">
<p className="text-[13px] font-medium text-foreground">{completeLabel}</p>
<p className="text-[12.5px] text-muted-foreground">{completeHint}</p>
</div>
) : (
step.content
)}
</motion.div>
</AnimatePresence>
</div>
<div className="mt-3 flex h-9 items-center gap-3">
<AnimatePresence initial={false}>
{isFirst ? null : (
<motion.button
key="back"
type="button"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{
opacity: 0,
transition: reduced ? { duration: 0 } : { duration: 0.12, ease: EXIT_EASE },
}}
transition={reduced ? { duration: 0 } : { duration: 0.16, ease: EASE }}
onClick={() => {
intent.current = "panel";
back();
}}
className="h-9 rounded-[9px] border border-border bg-background px-3 text-[13px] font-medium text-foreground outline-none transition-[border-color,box-shadow] duration-150 hover:border-foreground/20 focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/40"
>
{backLabel}
</motion.button>
)}
</AnimatePresence>
{step.canSkip ? (
<motion.button
key={`skip-${step.id}`}
type="button"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{
opacity: 0,
transition: reduced ? { duration: 0 } : { duration: 0.12, ease: EXIT_EASE },
}}
transition={reduced ? { duration: 0 } : { duration: 0.16, ease: EASE }}
onClick={() => {
step.onSkip?.();
if (!isLast) intent.current = "panel";
next();
}}
className="h-9 rounded-[9px] px-3 text-[13px] font-medium text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/40"
>
{skipLabel}
</motion.button>
) : null}
<AnimatePresence initial={false}>
{complete || step.hideAdvance ? null : (
<motion.button
key="advance"
type="button"
aria-label={isLast ? finishLabel : nextLabel}
onClick={() => {
if (!isLast) intent.current = "panel";
next();
}}
initial={{ opacity: 0, scale: 0.96 }}
animate={{ opacity: 1, scale: 1 }}
exit={{
opacity: 0,
scale: 0.96,
transition: reduced
? { duration: 0 }
: { duration: 0.14, ease: EXIT_EASE },
}}
transition={reduced ? { duration: 0 } : CROSSFADE}
className="ml-auto grid h-9 place-items-center rounded-[9px] bg-foreground px-3.5 text-[13px] font-medium text-background outline-none focus-visible:shadow-[inset_0_0_0_1.5px_var(--ring)]"
>
<span aria-hidden className="invisible col-start-1 row-start-1">
{finishLabel.length > nextLabel.length ? finishLabel : nextLabel}
</span>
<motion.span
aria-hidden
className="col-start-1 row-start-1"
initial={false}
animate={{ opacity: isLast ? 0 : 1 }}
transition={reduced ? { duration: 0 } : CROSSFADE}
>
{nextLabel}
</motion.span>
<motion.span
aria-hidden
className="col-start-1 row-start-1"
initial={false}
animate={{ opacity: isLast ? 1 : 0 }}
transition={reduced ? { duration: 0 } : CROSSFADE}
>
{finishLabel}
</motion.span>
</motion.button>
)}
</AnimatePresence>
</div>
</div>
);
}
@@ -1,89 +0,0 @@
import { motion } from 'motion/react';
import { ShieldAlert } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { ThemeToggle } from '@/components/theme-toggle';
import { ChangePasswordForm, type PasswordRule } from '@/components/pages/change-password-form';
// Re-exported so existing importers (e.g. the API client) keep resolving
// `PasswordRule` from this module after the form was extracted.
export type { PasswordRule };
interface ChangePasswordPageProps {
/**
* The password the user just logged in with. Passed straight through to the
* form as `knownOldPassword`, so the forced flow never renders an
* old-password field for a browser to autofill. See change-password-form.
*/
knownOldPassword?: string;
title?: string;
description?: string;
checkStrength: (password: string) => Promise<{ rules: PasswordRule[]; valid: boolean }>;
submit: (oldPassword: string, newPassword: string) => Promise<{ success: boolean; message?: string }>;
onSuccess: () => void;
}
/**
* Full-screen "you must set a new password before continuing" gate, shown
* once right after the first login with a generated temp password. The
* in-app "修改访问密码" action uses ChangePasswordDialog instead.
*/
export function ChangePasswordPage({
knownOldPassword,
title = '请先设置新的访问密码',
description = '为了保护你的实例,必须将首次启动生成的临时密码替换为符合下列要求的强密码。',
checkStrength,
submit,
onSuccess,
}: ChangePasswordPageProps) {
return (
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-8">
<div
className="pointer-events-none absolute inset-0"
style={{
background:
'radial-gradient(80% 60% at 50% 0%, color-mix(in oklab, var(--primary) 18%, transparent) 0%, transparent 70%)',
}}
/>
<motion.div
aria-hidden
className="pointer-events-none absolute -left-24 top-24 size-72 rounded-full bg-primary/15 blur-3xl"
animate={{ scale: [1, 1.08, 1] }}
transition={{ duration: 8, repeat: Infinity, ease: 'easeInOut' }}
/>
<div className="absolute right-4 top-4">
<ThemeToggle />
</div>
<motion.div
initial={{ opacity: 0, y: 16, scale: 0.98 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
transition={{ duration: 0.45, ease: [0.16, 1, 0.3, 1] }}
className="relative z-10 w-full max-w-lg"
>
<Card className="border-primary/15 shadow-xl">
<CardContent className="p-7 sm:p-9">
<div className="flex items-start gap-3">
<div className="flex size-12 shrink-0 items-center justify-center rounded-2xl bg-primary/10 ring-1 ring-primary/20">
<ShieldAlert className="size-6 text-primary" />
</div>
<div className="min-w-0">
<h1 className="text-lg font-semibold tracking-tight">{title}</h1>
<p className="mt-1 text-xs leading-relaxed text-muted-foreground">{description}</p>
</div>
</div>
<div className="mt-6">
<ChangePasswordForm
knownOldPassword={knownOldPassword}
checkStrength={checkStrength}
submit={submit}
onSuccess={onSuccess}
idPrefix="forced-cpw"
/>
</div>
</CardContent>
</Card>
</motion.div>
</div>
);
}
@@ -1,179 +0,0 @@
import { useState } from 'react';
import { motion } from 'motion/react';
import { Check, ScrollText, ShieldCheck } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { ThemeToggle } from '@/components/theme-toggle';
import { Markdown } from '@/lib/markdown';
import { cn } from '@/lib/utils';
import type { AgreementDoc } from '@/lib/api/types';
interface ConsentPageProps {
documents: AgreementDoc[];
version: string;
/** Persist acceptance. Resolves {success:false,message} to show inline. */
onAccept: () => Promise<{ success: boolean; message?: string }>;
/** Operator refuses — caller logs them out. */
onDecline: () => void;
}
const TAB_FALLBACK_TITLE: Record<string, string> = {
eula: '用户协议 / EULA',
privacy: '隐私政策 / Privacy',
};
/**
* Full-screen consent gate shown once at first login, before the forced
* password change. The operator must accept the EULA + Privacy Notice before
* the panel unlocks; acceptance is keyed to the agreement content version, so
* it persists across app upgrades and re-prompts only when the text changes.
*/
export function ConsentPage({ documents, version, onAccept, onDecline }: ConsentPageProps) {
const tabs = documents.length > 0 ? documents : [];
const [activeId, setActiveId] = useState<string>(tabs[0]?.id ?? 'eula');
const [agreed, setAgreed] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const active = tabs.find((d) => d.id === activeId) ?? tabs[0];
const handleAccept = async () => {
if (!agreed || submitting) return;
setSubmitting(true);
setError(null);
try {
const result = await onAccept();
if (!result.success) {
setError(result.message ?? '提交失败,请重试');
setSubmitting(false);
}
// on success the parent unmounts this gate; no local state change needed.
} catch {
// Defense in depth: onAccept should never reject (client resolves errors),
// but never leave the button stuck on "提交中…" if it somehow does.
setError('网络错误,请重试');
setSubmitting(false);
}
};
return (
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-8">
<div
className="pointer-events-none absolute inset-0"
style={{
background:
'radial-gradient(80% 60% at 50% 0%, color-mix(in oklab, var(--primary) 18%, transparent) 0%, transparent 70%)',
}}
/>
<div className="absolute right-4 top-4">
<ThemeToggle />
</div>
<motion.div
initial={{ opacity: 0, y: 16, scale: 0.98 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
transition={{ duration: 0.45, ease: [0.16, 1, 0.3, 1] }}
className="relative z-10 flex w-full max-w-3xl flex-col"
>
<Card className="border-primary/15 shadow-xl">
<CardContent className="flex max-h-[88vh] flex-col p-7 sm:p-9">
<div className="flex items-start gap-3">
<div className="flex size-12 shrink-0 items-center justify-center rounded-2xl bg-primary/10 ring-1 ring-primary/20">
<ScrollText className="size-6 text-primary" />
</div>
<div className="min-w-0">
<h1 className="text-lg font-semibold tracking-tight">请阅读并同意以下协议</h1>
<p className="mt-1 text-xs leading-relaxed text-muted-foreground">
首次使用前,请阅读并同意《用户协议》与《隐私政策》。同意一次后无需重复确认;仅当协议内容更新时才会再次请求确认。
<br />
Please read and accept the agreements below before first use. You only consent once — you'll be asked again only if the text changes.
</p>
</div>
</div>
{/* tab switcher */}
<div className="mt-5 flex gap-1 rounded-lg bg-muted/60 p-1">
{tabs.map((doc) => (
<button
key={doc.id}
type="button"
onClick={() => setActiveId(doc.id)}
className={cn(
'flex-1 rounded-md px-3 py-1.5 text-xs font-medium transition-colors',
doc.id === activeId
? 'bg-background text-foreground shadow-sm'
: 'text-muted-foreground hover:text-foreground',
)}
>
{doc.title?.split('/')[0]?.trim() || TAB_FALLBACK_TITLE[doc.id] || doc.id}
</button>
))}
</div>
{active && (active.declaredVersion || active.effectiveDate) && (
<p className="mt-2 text-meta text-muted-foreground">
{active.declaredVersion && `版本 / Version ${active.declaredVersion}`}
{active.declaredVersion && active.effectiveDate && ' · '}
{active.effectiveDate && `生效 / Effective ${active.effectiveDate}`}
</p>
)}
{/* document body */}
<div className="mt-3 min-h-0 flex-1 overflow-y-auto rounded-lg border border-border bg-background/60 p-4">
{active ? (
<Markdown content={active.text} />
) : (
<p className="text-sm text-muted-foreground">未能加载协议文本,请刷新页面重试。</p>
)}
</div>
{/* agree checkbox — full-width row so it reads as an obvious control */}
<button
type="button"
onClick={() => setAgreed((v) => !v)}
aria-pressed={agreed}
className={cn(
'mt-4 flex w-full items-center gap-3 rounded-lg border px-3.5 py-3 text-left transition-colors',
agreed
? 'border-primary/60 bg-primary/5'
: 'border-border hover:border-primary/40 hover:bg-accent/40',
)}
>
<span
className={cn(
'flex size-5 shrink-0 items-center justify-center rounded-[5px] border-2 transition-colors',
agreed
? 'border-primary bg-primary text-primary-foreground'
: 'border-muted-foreground/50 bg-background',
)}
>
{agreed && <Check className="size-3.5" strokeWidth={3} />}
</span>
<span className="leading-snug">
<span className="text-sm font-medium text-foreground">
我已阅读并同意《用户协议》与《隐私政策》
</span>
<span className="mt-0.5 block text-xs text-muted-foreground">
I have read and agree to the User Agreement and the Privacy Notice.
</span>
</span>
</button>
{error && <p className="mt-3 text-xs text-destructive">{error}</p>}
<div className="mt-5 flex items-center justify-end gap-2">
<Button type="button" variant="ghost" onClick={onDecline} disabled={submitting}>
不同意并退出
</Button>
<Button type="button" onClick={handleAccept} disabled={!agreed || submitting}>
<ShieldCheck className="size-4" />
{submitting ? '提交中…' : '同意并继续'}
</Button>
</div>
</CardContent>
</Card>
<p className="mt-3 text-center text-micro text-muted-foreground/70">agreements {version.slice(0, 8)}</p>
</motion.div>
</div>
);
}
@@ -0,0 +1,39 @@
export type RequiredOnboardingStepId = 'agreements' | 'password';
export interface OnboardingRequirements {
needsConsent: boolean;
mustChangePassword: boolean;
}
/**
* The server has already applied environment policy before returning these
* booleans. Accepted legal env flags therefore omit the agreement step, while
* a configured bootstrap password omits forced password rotation.
*/
export function buildRequiredOnboardingStepIds({
needsConsent,
mustChangePassword,
}: OnboardingRequirements): RequiredOnboardingStepId[] {
const steps: RequiredOnboardingStepId[] = [];
if (needsConsent) steps.push('agreements');
if (mustChangePassword) steps.push('password');
return steps;
}
export type OnboardingAdvance =
| { nextIndex: number; complete: false }
| { nextIndex: null; complete: true };
export function advanceOnboardingStep(
stepIds: readonly string[],
currentStepId: string,
): OnboardingAdvance {
const current = stepIds.indexOf(currentStepId);
if (current < 0) {
throw new Error(`Unknown onboarding step: ${currentStepId}`);
}
if (current === stepIds.length - 1) {
return { nextIndex: null, complete: true };
}
return { nextIndex: current + 1, complete: false };
}
@@ -0,0 +1,337 @@
import { useState, type ReactNode } from 'react';
import { Check, ScrollText, ShieldAlert, ShieldCheck } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { ThemeToggle } from '@/components/theme-toggle';
import { SegmentedControl } from '@/components/interior/segmented-control';
import { WizardSteps, type WizardStep } from '@/components/interior/wizard-steps';
import { ChangePasswordForm, type PasswordRule } from '@/components/pages/change-password-form';
import {
advanceOnboardingStep,
buildRequiredOnboardingStepIds,
} from '@/components/pages/onboarding-steps';
import { Markdown } from '@/lib/markdown';
import { cn } from '@/lib/utils';
import type { AgreementDoc } from '@/lib/api/types';
export interface AdditionalOnboardingStep {
id: string;
label: string;
content: ReactNode;
canSkip: boolean;
onSkip?: () => void;
hideAdvance?: boolean;
}
interface OnboardingWizardPageProps {
documents: AgreementDoc[];
agreementVersion: string;
needsConsent: boolean;
mustChangePassword: boolean;
knownOldPassword?: string;
onAccept: () => Promise<{ success: boolean; message?: string }>;
onConsentComplete: () => void;
onDecline: () => void;
checkStrength: (password: string) => Promise<{ rules: PasswordRule[]; valid: boolean }>;
submitPassword: (
oldPassword: string,
newPassword: string,
) => Promise<{ success: boolean; message?: string }>;
onPasswordComplete: () => void;
onComplete: () => void;
additionalSteps?: AdditionalOnboardingStep[];
}
const TAB_FALLBACK_TITLE: Record<string, string> = {
eula: '用户协议 / EULA',
privacy: '隐私政策 / Privacy',
};
export function OnboardingWizardPage({
documents,
agreementVersion,
needsConsent,
mustChangePassword,
knownOldPassword,
onAccept,
onConsentComplete,
onDecline,
checkStrength,
submitPassword,
onPasswordComplete,
onComplete,
additionalSteps = [],
}: OnboardingWizardPageProps) {
const [requiredStepIds] = useState(() => buildRequiredOnboardingStepIds({
needsConsent,
mustChangePassword,
}));
const [index, setIndex] = useState(0);
const total = requiredStepIds.length + additionalSteps.length;
const advanceFrom = (stepId: string) => {
const order = [...requiredStepIds, ...additionalSteps.map((step) => step.id)];
const advance = advanceOnboardingStep(order, stepId);
if (advance.complete) {
onComplete();
return;
}
setIndex(advance.nextIndex);
};
const required: WizardStep[] = requiredStepIds.map((stepId) => {
if (stepId === 'agreements') {
return {
id: stepId,
label: '阅读并同意协议',
canSkip: false,
hideAdvance: true,
content: (
<AgreementStep
documents={documents}
version={agreementVersion}
onAccept={onAccept}
onDecline={onDecline}
onComplete={() => {
onConsentComplete();
advanceFrom(stepId);
}}
/>
),
};
}
return {
id: stepId,
label: '设置访问密码',
canSkip: false,
hideAdvance: true,
content: (
<PasswordStep
knownOldPassword={knownOldPassword}
checkStrength={checkStrength}
submit={submitPassword}
onComplete={() => {
onPasswordComplete();
advanceFrom(stepId);
}}
/>
),
};
});
const steps: WizardStep[] = [
...required,
...additionalSteps.map((step) => ({
id: step.id,
label: step.label,
content: step.content,
canSkip: step.canSkip,
onSkip: step.onSkip,
hideAdvance: step.hideAdvance,
})),
];
if (total === 0) return null;
return (
<div className="relative flex min-h-screen items-center justify-center overflow-x-hidden bg-background px-4 py-6">
<div
className="pointer-events-none absolute inset-0"
style={{
background:
'radial-gradient(80% 60% at 50% 0%, color-mix(in oklab, var(--primary) 18%, transparent) 0%, transparent 70%)',
}}
/>
<div className="absolute right-4 top-4">
<ThemeToggle />
</div>
<main className="relative z-10 w-full max-w-3xl">
<div className="mb-5">
<p className="text-xs font-medium text-primary">SnowLuma WebUI</p>
<h1 className="mt-1 text-xl font-semibold tracking-tight">完成首次使用设置</h1>
<p className="mt-1 text-sm text-muted-foreground">
按顺序完成必要步骤后即可进入控制台。
</p>
</div>
<WizardSteps
steps={steps}
index={index}
onIndexChange={setIndex}
onComplete={onComplete}
height={520}
label="首次使用设置步骤"
backLabel="上一步"
nextLabel="下一步"
finishLabel="完成"
skipLabel="跳过"
/>
</main>
</div>
);
}
function AgreementStep({
documents,
version,
onAccept,
onDecline,
onComplete,
}: {
documents: AgreementDoc[];
version: string;
onAccept: () => Promise<{ success: boolean; message?: string }>;
onDecline: () => void;
onComplete: () => void;
}) {
const [activeId, setActiveId] = useState(documents[0]?.id ?? 'eula');
const [agreed, setAgreed] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const active = documents.find((document) => document.id === activeId) ?? documents[0];
const accept = async () => {
if (!agreed || submitting) return;
setSubmitting(true);
setError(null);
try {
const result = await onAccept();
if (result.success) {
onComplete();
return;
}
setError(result.message ?? '提交失败,请重试');
} catch (caught) {
console.error('record onboarding consent failed', caught);
setError(caught instanceof Error ? caught.message : '网络错误,请重试');
} finally {
setSubmitting(false);
}
};
return (
<div className="flex min-h-full flex-col">
<div className="flex items-start gap-3">
<div className="flex size-11 shrink-0 items-center justify-center rounded-xl bg-primary/10 ring-1 ring-primary/20">
<ScrollText className="size-5 text-primary" />
</div>
<div className="min-w-0">
<h2 className="text-base font-semibold">请阅读并同意以下协议</h2>
<p className="mt-1 text-xs leading-relaxed text-muted-foreground">
同意一次后无需重复确认;仅当协议内容更新时才会再次请求确认。
</p>
</div>
</div>
{documents.length > 1 ? (
<div className="mt-4 max-w-full overflow-x-auto">
<SegmentedControl
label="协议文档"
value={activeId}
onValueChange={(next) => setActiveId(next as AgreementDoc['id'])}
options={documents.map((document) => ({
value: document.id,
label: document.title?.split('/')[0]?.trim()
|| TAB_FALLBACK_TITLE[document.id]
|| document.id,
}))}
/>
</div>
) : null}
{active && (active.declaredVersion || active.effectiveDate) ? (
<p className="mt-2 text-meta text-muted-foreground">
{active.declaredVersion ? `版本 / Version ${active.declaredVersion}` : ''}
{active.declaredVersion && active.effectiveDate ? ' · ' : ''}
{active.effectiveDate ? `生效 / Effective ${active.effectiveDate}` : ''}
</p>
) : null}
<div className="mt-3 min-h-48 flex-1 overflow-y-auto rounded-lg border border-border bg-background/60 p-4">
{active ? (
<Markdown content={active.text} />
) : (
<p className="text-sm text-muted-foreground">未能加载协议文本,请刷新页面重试。</p>
)}
</div>
<button
type="button"
onClick={() => setAgreed((current) => !current)}
aria-pressed={agreed}
className={cn(
'mt-3 flex w-full items-center gap-3 rounded-lg border px-3.5 py-2.5 text-left transition-colors',
agreed
? 'border-primary/60 bg-primary/5'
: 'border-border hover:border-primary/40 hover:bg-accent/40',
)}
>
<span
className={cn(
'flex size-5 shrink-0 items-center justify-center rounded-[5px] border-2 transition-colors',
agreed
? 'border-primary bg-primary text-primary-foreground'
: 'border-muted-foreground/50 bg-background',
)}
>
{agreed ? <Check className="size-3.5" strokeWidth={3} /> : null}
</span>
<span className="text-sm font-medium">我已阅读并同意《用户协议》与《隐私政策》</span>
</button>
{error ? <p role="alert" className="mt-2 text-xs text-destructive">{error}</p> : null}
<div className="mt-3 flex items-center justify-between gap-2">
<span className="text-micro text-muted-foreground/70">
agreements {version.slice(0, 8)}
</span>
<div className="flex gap-2">
<Button type="button" variant="ghost" onClick={onDecline} disabled={submitting}>
不同意并退出
</Button>
<Button type="button" onClick={() => { void accept(); }} disabled={!agreed || submitting}>
<ShieldCheck className="size-4" />
{submitting ? '提交中…' : '同意并继续'}
</Button>
</div>
</div>
</div>
);
}
function PasswordStep({
knownOldPassword,
checkStrength,
submit,
onComplete,
}: {
knownOldPassword?: string;
checkStrength: (password: string) => Promise<{ rules: PasswordRule[]; valid: boolean }>;
submit: (
oldPassword: string,
newPassword: string,
) => Promise<{ success: boolean; message?: string }>;
onComplete: () => void;
}) {
return (
<div className="mx-auto flex w-full max-w-lg flex-col">
<div className="mb-5 flex items-start gap-3">
<div className="flex size-11 shrink-0 items-center justify-center rounded-xl bg-primary/10 ring-1 ring-primary/20">
<ShieldAlert className="size-5 text-primary" />
</div>
<div className="min-w-0">
<h2 className="text-base font-semibold">设置新的访问密码</h2>
<p className="mt-1 text-xs leading-relaxed text-muted-foreground">
将首次启动生成的临时密码替换为符合要求的强密码。
</p>
</div>
</div>
<ChangePasswordForm
knownOldPassword={knownOldPassword}
checkStrength={checkStrength}
submit={submit}
onSuccess={onComplete}
idPrefix="onboarding-cpw"
submitLabel="保存并完成"
/>
</div>
);
}
+1 -1
View File
@@ -1,5 +1,5 @@
import type { AccountConnections, BackupBundle, BackupImportResult, DebugActionDoc, DebugInvokeResult, DebugStreamMessage, GlobalSettings, HookProcessInfo, LogEntry, LogLevel, LogStorageSettingsPatch, NotificationDeliveryRecord, NotificationsConfig, QQInfo, StorageCleanupRequest, StorageCleanupResponse, StorageOverviewResponse, StorageSettingsUpdateResponse, SystemInfo, SystemSettingsPatch, SystemSettingsResponse, UiAppearance, UiConfig, UpdateInfo } from '@/types';
import type { PasswordRule } from '@/components/pages/change-password-page';
import type { PasswordRule } from '@/components/pages/change-password-form';
import { normalizeOneBotConfig } from '@/lib/onebot-config';
import {
type AgreementsPayload,
+1 -1
View File
@@ -28,7 +28,7 @@ import type {
UiConfig,
UpdateInfo,
} from '@/types';
import type { PasswordRule } from '@/components/pages/change-password-page';
import type { PasswordRule } from '@/components/pages/change-password-form';
export class ApiError extends Error {
status: number;
@@ -0,0 +1,68 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
import { WizardSteps } from '../src/components/interior/wizard-steps';
import {
advanceOnboardingStep,
buildRequiredOnboardingStepIds,
} from '../src/components/pages/onboarding-steps';
describe('buildRequiredOnboardingStepIds', () => {
it('keeps legal consent before password setup when both are required', () => {
expect(buildRequiredOnboardingStepIds({
needsConsent: true,
mustChangePassword: true,
})).toEqual(['agreements', 'password']);
});
it('omits steps already satisfied by backend environment-aware policy', () => {
expect(buildRequiredOnboardingStepIds({
needsConsent: false,
mustChangePassword: false,
})).toEqual([]);
expect(buildRequiredOnboardingStepIds({
needsConsent: false,
mustChangePassword: true,
})).toEqual(['password']);
});
it('completes consent and password in order before releasing onboarding', () => {
const steps = buildRequiredOnboardingStepIds({
needsConsent: true,
mustChangePassword: true,
});
expect(advanceOnboardingStep(steps, 'agreements')).toEqual({
nextIndex: 1,
complete: false,
});
expect(advanceOnboardingStep(steps, 'password')).toEqual({
nextIndex: null,
complete: true,
});
});
});
describe('WizardSteps onboarding policy', () => {
it('only renders a skip action for a step configured as skippable', () => {
const skippable = renderToStaticMarkup(
<WizardSteps
steps={[
{ id: 'optional', label: '可选步骤', content: <p>可选内容</p>, canSkip: true },
{ id: 'required', label: '必要步骤', content: <p>必要内容</p> },
]}
skipLabel="跳过"
/>,
);
const required = renderToStaticMarkup(
<WizardSteps
steps={[
{ id: 'required', label: '必要步骤', content: <p>必要内容</p>, canSkip: false },
]}
skipLabel="跳过"
/>,
);
expect(skippable).toContain('跳过');
expect(required).not.toContain('跳过');
});
});