diff --git a/README.md b/README.md
index 45da3a48..b1d5db23 100644
--- a/README.md
+++ b/README.md
@@ -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 连接。
无人值守部署:通过环境变量确认协议
-同时设置以下两个变量可跳过 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` 时仍以现有凭据为准。
+
## 可选:登录时补齐云端历史
diff --git a/packages/webui/src/App.tsx b/packages/webui/src/App.tsx
index 43d7a347..3bb59e84 100644
--- a/packages/webui/src/App.tsx
+++ b/packages/webui/src/App.tsx
@@ -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 (
-
+
);
@@ -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(null);
const [agreementsError, setAgreementsError] = useState(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 = (
- setNeedsConsent(false)}
- onStale={refreshAgreements}
- onDecline={handleDecline}
- />
- );
- } else if (mustChange) {
- view = (
- {
+ 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 ;
}
-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 (
- 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 (
- api.checkPasswordStrength(p)}
- submit={(o, n) => api.changePassword(o, n)}
- onSuccess={onSuccess}
- />
- );
-}
diff --git a/packages/webui/src/components/interior/wizard-steps.tsx b/packages/webui/src/components/interior/wizard-steps.tsx
new file mode 100644
index 00000000..03d59e07
--- /dev/null
+++ b/packages/webui/src/components/interior/wizard-steps.tsx
@@ -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(null);
+ const viewportRef = useRef(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('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) => {
+ 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 (
+
+
{position}
+
+ {steps.map((candidate, stepIndex) => (
+
+ {candidate.label}
+
+ ))}
+
+
+ {steps.map((candidate, stepIndex) => {
+ const done = complete || stepIndex < at;
+ const here = !complete && stepIndex === at;
+ const tile = (
+
+ {done ? (
+
+
+
+ ) : (
+ stepIndex + 1
+ )}
+
+ );
+
+ return (
+
+ {stepIndex <= furthest ? (
+ {
+ if (here) return;
+ intent.current = "list";
+ goTo(stepIndex);
+ }}
+ className="rounded-[8px] outline-none focus-visible:shadow-[0_0_0_1.5px_var(--ring)]"
+ >
+ {tile}
+
+ ) : (
+
+
+ {`Step ${stepIndex + 1} of ${total}: ${candidate.label}`}
+
+ {tile}
+
+ )}
+
+ {stepIndex < total - 1 ? (
+
+
+
+ ) : null}
+
+ );
+ })}
+
+
+
+
+ {complete ? (
+
+
{completeLabel}
+
{completeHint}
+
+ ) : (
+ step.content
+ )}
+
+
+
+
+
+ {isFirst ? null : (
+ {
+ 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}
+
+ )}
+
+ {step.canSkip ? (
+
{
+ 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}
+
+ ) : null}
+
+ {complete || step.hideAdvance ? null : (
+ {
+ 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)]"
+ >
+
+ {finishLabel.length > nextLabel.length ? finishLabel : nextLabel}
+
+
+ {nextLabel}
+
+
+ {finishLabel}
+
+
+ )}
+
+
+
+ );
+}
diff --git a/packages/webui/src/components/pages/change-password-page.tsx b/packages/webui/src/components/pages/change-password-page.tsx
deleted file mode 100644
index 09aae42f..00000000
--- a/packages/webui/src/components/pages/change-password-page.tsx
+++ /dev/null
@@ -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 (
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
{title}
-
{description}
-
-
-
-
-
-
-
-
-
-
- );
-}
diff --git a/packages/webui/src/components/pages/consent-page.tsx b/packages/webui/src/components/pages/consent-page.tsx
deleted file mode 100644
index 6dcf3818..00000000
--- a/packages/webui/src/components/pages/consent-page.tsx
+++ /dev/null
@@ -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 = {
- 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(tabs[0]?.id ?? 'eula');
- const [agreed, setAgreed] = useState(false);
- const [submitting, setSubmitting] = useState(false);
- const [error, setError] = useState(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 (
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
请阅读并同意以下协议
-
- 首次使用前,请阅读并同意《用户协议》与《隐私政策》。同意一次后无需重复确认;仅当协议内容更新时才会再次请求确认。
-
- Please read and accept the agreements below before first use. You only consent once — you'll be asked again only if the text changes.
-
-
-
-
- {/* tab switcher */}
-
- {tabs.map((doc) => (
- 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}
-
- ))}
-
-
- {active && (active.declaredVersion || active.effectiveDate) && (
-
- {active.declaredVersion && `版本 / Version ${active.declaredVersion}`}
- {active.declaredVersion && active.effectiveDate && ' · '}
- {active.effectiveDate && `生效 / Effective ${active.effectiveDate}`}
-
- )}
-
- {/* document body */}
-
- {active ? (
-
- ) : (
-
未能加载协议文本,请刷新页面重试。
- )}
-
-
- {/* agree checkbox — full-width row so it reads as an obvious control */}
- 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',
- )}
- >
-
- {agreed && }
-
-
-
- 我已阅读并同意《用户协议》与《隐私政策》
-
-
- I have read and agree to the User Agreement and the Privacy Notice.
-
-
-
-
- {error && {error}
}
-
-
-
- 不同意并退出
-
-
-
- {submitting ? '提交中…' : '同意并继续'}
-
-
-
-
- agreements {version.slice(0, 8)}
-
-
- );
-}
diff --git a/packages/webui/src/components/pages/onboarding-steps.ts b/packages/webui/src/components/pages/onboarding-steps.ts
new file mode 100644
index 00000000..deb3019a
--- /dev/null
+++ b/packages/webui/src/components/pages/onboarding-steps.ts
@@ -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 };
+}
diff --git a/packages/webui/src/components/pages/onboarding-wizard-page.tsx b/packages/webui/src/components/pages/onboarding-wizard-page.tsx
new file mode 100644
index 00000000..7be9a753
--- /dev/null
+++ b/packages/webui/src/components/pages/onboarding-wizard-page.tsx
@@ -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 = {
+ 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: (
+ {
+ onConsentComplete();
+ advanceFrom(stepId);
+ }}
+ />
+ ),
+ };
+ }
+ return {
+ id: stepId,
+ label: '设置访问密码',
+ canSkip: false,
+ hideAdvance: true,
+ content: (
+ {
+ 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 (
+
+
+
+
+
+
+
+
SnowLuma WebUI
+
完成首次使用设置
+
+ 按顺序完成必要步骤后即可进入控制台。
+
+
+
+
+
+ );
+}
+
+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(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 (
+
+
+
+
+
+
+
请阅读并同意以下协议
+
+ 同意一次后无需重复确认;仅当协议内容更新时才会再次请求确认。
+
+
+
+
+ {documents.length > 1 ? (
+
+ 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,
+ }))}
+ />
+
+ ) : null}
+
+ {active && (active.declaredVersion || active.effectiveDate) ? (
+
+ {active.declaredVersion ? `版本 / Version ${active.declaredVersion}` : ''}
+ {active.declaredVersion && active.effectiveDate ? ' · ' : ''}
+ {active.effectiveDate ? `生效 / Effective ${active.effectiveDate}` : ''}
+
+ ) : null}
+
+
+ {active ? (
+
+ ) : (
+
未能加载协议文本,请刷新页面重试。
+ )}
+
+
+
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',
+ )}
+ >
+
+ {agreed ? : null}
+
+ 我已阅读并同意《用户协议》与《隐私政策》
+
+
+ {error ?
{error}
: null}
+
+
+
+ agreements {version.slice(0, 8)}
+
+
+
+ 不同意并退出
+
+ { void accept(); }} disabled={!agreed || submitting}>
+
+ {submitting ? '提交中…' : '同意并继续'}
+
+
+
+
+ );
+}
+
+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 (
+
+
+
+
+
+
+
设置新的访问密码
+
+ 将首次启动生成的临时密码替换为符合要求的强密码。
+
+
+
+
+
+ );
+}
diff --git a/packages/webui/src/lib/api/client.ts b/packages/webui/src/lib/api/client.ts
index 38312c90..78ec39c7 100644
--- a/packages/webui/src/lib/api/client.ts
+++ b/packages/webui/src/lib/api/client.ts
@@ -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,
diff --git a/packages/webui/src/lib/api/types.ts b/packages/webui/src/lib/api/types.ts
index 7c66aaaa..5f299fda 100644
--- a/packages/webui/src/lib/api/types.ts
+++ b/packages/webui/src/lib/api/types.ts
@@ -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;
diff --git a/packages/webui/tests/onboarding-steps.test.tsx b/packages/webui/tests/onboarding-steps.test.tsx
new file mode 100644
index 00000000..1cab8eab
--- /dev/null
+++ b/packages/webui/tests/onboarding-steps.test.tsx
@@ -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(
+ 可选内容
, canSkip: true },
+ { id: 'required', label: '必要步骤', content: 必要内容
},
+ ]}
+ skipLabel="跳过"
+ />,
+ );
+ const required = renderToStaticMarkup(
+ 必要内容, canSkip: false },
+ ]}
+ skipLabel="跳过"
+ />,
+ );
+
+ expect(skippable).toContain('跳过');
+ expect(required).not.toContain('跳过');
+ });
+});