feat: integrate learning module
Some checks failed
Electron E2E / Electron E2E (macos-latest) (push) Has been cancelled
Electron E2E / Electron E2E (ubuntu-latest) (push) Has been cancelled
Electron E2E / Electron E2E (windows-latest) (push) Has been cancelled

This commit is contained in:
inman
2026-08-16 20:52:16 +08:00
parent 26b52d76e3
commit 01bee3188b
107 changed files with 6318 additions and 12063 deletions

View File

@@ -0,0 +1,173 @@
import { useCallback, useEffect, useState } from 'react';
import { BookOpen, Download, Loader2, Plus, Sparkles } from 'lucide-react';
import { useLocation, useNavigate } from 'react-router-dom';
import {
downloadLearningCourse,
fetchMyLearningCourses,
LEARNING_LIBRARY_CHANGED_EVENT,
listInstalledLearningCourses,
} from '@/lib/learning';
import { cn } from '@/lib/utils';
import type { InstalledLearningCourse, LearningCourse } from '../../../shared/learning';
type LearningSidebarProps = {
sidebarCollapsed: boolean;
};
export function LearningSidebar({ sidebarCollapsed }: LearningSidebarProps) {
const navigate = useNavigate();
const location = useLocation();
const [installed, setInstalled] = useState<Record<string, InstalledLearningCourse>>({});
const [ownedCourses, setOwnedCourses] = useState<LearningCourse[]>([]);
const [loading, setLoading] = useState(true);
const [downloading, setDownloading] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const loadCourses = useCallback(async () => {
setLoading(true);
setError(null);
try {
const [localCourses, personalCourses] = await Promise.all([
listInstalledLearningCourses(),
fetchMyLearningCourses().catch(() => []),
]);
setInstalled(Object.fromEntries(localCourses.map((record) => [record.course.id, record])));
setOwnedCourses(personalCourses);
} catch (cause) {
setError(cause instanceof Error ? cause.message : '个人课程暂时无法读取');
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
void loadCourses();
const refresh = () => void loadCourses();
window.addEventListener(LEARNING_LIBRARY_CHANGED_EVENT, refresh);
return () => window.removeEventListener(LEARNING_LIBRARY_CHANGED_EVENT, refresh);
}, [loadCourses]);
const personalCourses = (() => {
const courses = new Map<string, LearningCourse>();
for (const record of Object.values(installed)) courses.set(record.course.id, record.course);
for (const course of ownedCourses) courses.set(course.id, course);
return [...courses.values()];
})();
const openCourse = useCallback(async (course: LearningCourse) => {
if (installed[course.id]) {
navigate(`/learning/course/${encodeURIComponent(course.id)}`);
return;
}
setDownloading(course.id);
setError(null);
try {
const record = await downloadLearningCourse(course.id);
setInstalled((current) => ({ ...current, [course.id]: record }));
navigate(`/learning/course/${encodeURIComponent(course.id)}`);
} catch (cause) {
setError(cause instanceof Error ? cause.message : '课程下载失败');
} finally {
setDownloading(null);
}
}, [installed, navigate]);
const catalogActive = location.pathname === '/learning';
return (
<div data-testid="sidebar-learning-navigation" className="px-1 py-1">
<button
type="button"
aria-label="课程广场"
aria-current={catalogActive ? 'page' : undefined}
onClick={() => navigate('/learning')}
className={cn(
'motion-press flex min-h-9 w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-sm font-semibold transition-colors active:scale-[0.985]',
catalogActive ? 'bg-brand-soft text-foreground' : 'text-foreground hover:bg-surface-subtle',
sidebarCollapsed && 'justify-center px-0',
)}
>
<BookOpen className="h-4 w-4 shrink-0 text-brand" />
{!sidebarCollapsed ? <span>课程广场</span> : null}
</button>
<button
type="button"
aria-label="生成课程"
onClick={() => navigate('/learning?generate=1')}
className={cn(
'motion-press mt-1 flex min-h-9 w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-sm font-medium text-foreground transition-colors hover:bg-surface-subtle active:scale-[0.985]',
sidebarCollapsed && 'justify-center px-0',
)}
>
<Plus className="h-4 w-4 shrink-0 text-brand" />
{!sidebarCollapsed ? <span>生成课程</span> : null}
</button>
{!sidebarCollapsed ? (
<div className="mt-4">
<div className="flex min-h-8 items-center gap-2 px-2 text-xs font-semibold text-muted-foreground">
<Sparkles className="h-4 w-4 shrink-0" />
<span className="min-w-0 flex-1 truncate">我的课程</span>
{!loading ? <span className="tabular-nums">{personalCourses.length}</span> : null}
</div>
{loading ? (
<div role="status" className="flex items-center px-2 py-3 text-xs font-medium text-muted-foreground">
<Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />正在读取课程
</div>
) : error ? (
<button
type="button"
className="w-full rounded-lg px-2 py-3 text-left text-xs font-medium leading-5 text-destructive hover:bg-destructive/5"
onClick={() => void loadCourses()}
>
{error},点击重试
</button>
) : personalCourses.length === 0 ? (
<p className="px-2 py-3 text-xs font-medium leading-5 text-muted-foreground">
下载或生成课程后,会显示在这里。
</p>
) : (
<div className="mt-1 space-y-1">
{personalCourses.map((course) => {
const isInstalled = Boolean(installed[course.id]);
const isActive = location.pathname === `/learning/course/${encodeURIComponent(course.id)}`;
const courseMeta = course.origin === 'user_single'
? isInstalled ? '我生成的,已下载' : '我生成的,待下载'
: '已下载到本机';
return (
<button
type="button"
key={course.id}
aria-label={`${isInstalled ? '打开' : '下载'}课程 ${course.title}`}
aria-current={isActive ? 'page' : undefined}
disabled={downloading === course.id}
onClick={() => void openCourse(course)}
className={cn(
'motion-press group/course flex w-full items-center gap-2 rounded-xl px-2.5 py-2 text-left transition-[background-color,color,transform] active:scale-[0.985]',
isActive ? 'bg-brand-selected text-foreground ring-1 ring-brand/20' : 'hover:bg-surface-tertiary',
)}
>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-semibold text-foreground">{course.title}</span>
<span className="mt-0.5 block truncate text-[11px] font-medium text-muted-foreground">{courseMeta}</span>
</span>
{downloading === course.id ? (
<Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin text-brand" />
) : isInstalled ? (
<BookOpen className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
) : (
<Download className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
)}
</button>
);
})}
</div>
)}
</div>
) : null}
</div>
);
}

View File

@@ -35,6 +35,7 @@ export function MainLayout() {
const activeModule = getAiModuleForPath(location.pathname);
const isProgrammingModule = activeModule === 'programming';
const isPaintingModule = activeModule === 'painting';
const isLearningPlayer = location.pathname.startsWith('/learning/course/');
const isPromptMuseum = location.pathname === '/image-prompts' || location.pathname.startsWith('/image-prompts/');
const isChatWorkspace = location.pathname === '/opencode-chat';
const isInitializationSafeRoute = location.pathname === '/project-config' || !isProgrammingModule;
@@ -91,7 +92,7 @@ export function MainLayout() {
<div data-testid="main-layout" className="relative flex h-[100dvh] flex-col overflow-hidden bg-transparent font-sans">
{/* Title bar: drag region on macOS, icon + controls on Windows */}
<TitleBar
integrated
integrated={!isLearningPlayer}
workspaceLayout={isChatWorkspace}
overlay={isPaintingModule && !isPromptMuseum}
pageTitle={isPromptMuseum ? '获取灵感' : undefined}
@@ -101,16 +102,18 @@ export function MainLayout() {
{/* Below the title bar: sidebar + content */}
<div className="relative flex min-h-0 flex-1 overflow-hidden">
<Sidebar
workspaceLayout={isChatWorkspace}
sidebarPeekOpen={sidebarPeekOpen}
onSidebarPeekChange={handleSidebarPeekChange}
/>
{!isLearningPlayer ? (
<Sidebar
workspaceLayout={isChatWorkspace}
sidebarPeekOpen={sidebarPeekOpen}
onSidebarPeekChange={handleSidebarPeekChange}
/>
) : null}
<main
data-testid="main-content"
className={cn(
'relative min-h-0 min-w-0 flex-1 overflow-auto bg-background',
isPaintingModule ? 'basis-0 h-full overflow-hidden p-0' : 'p-5 sm:p-6',
isPaintingModule || isLearningPlayer ? 'basis-0 h-full overflow-hidden p-0' : 'p-5 sm:p-6',
isChatWorkspace && !isPaintingModule && 'basis-0 overflow-hidden p-0',
)}
>

View File

@@ -1,4 +1,4 @@
import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate } from 'react-router-dom';
@@ -12,39 +12,36 @@ import {
LogOut,
Plus,
Settings as SettingsIcon,
Trash2,
Upload,
UserCircle2,
X,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { DisclosureContent } from '@/components/ui/disclosure';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { getAgentAvatarSrc } from '@/lib/agent-avatars';
import { AgentProfileApiError, deleteAgentAvatar, getAgentProfileApiErrorMessage, uploadAgentAvatar } from '@/lib/agent-profile';
import { getAiModuleForPath } from '@/lib/ai-modules';
import { invokeIpc } from '@/lib/api-client';
import { getAuthUserDisplayName } from '@/lib/auth-user-display';
import { prepareUserAvatar, type PreparedUserAvatar } from '@/lib/user-avatar';
import { WORKS_SQUARE_TOKEN_USAGE_STALE_EVENT } from '@/lib/works-square-usage-events';
import { fetchWorksTokenUsage, type WorksTokenUsage } from '@/lib/works-square';
import { isWorksTokenUsageExhausted } from '@/lib/works-square-token-usage';
import { openWorksSquareSubscriptionUpgrade } from '@/lib/subscription-upgrade';
import { cn } from '@/lib/utils';
import { useCurrentUserProfile } from '@/hooks/use-current-user-profile';
import type { SidebarPeekSource } from './sidebar-peek';
import { ModuleSwitcher } from './ModuleSwitcher';
import { ImageWorkspaceSidebar } from './ImageWorkspaceSidebar';
import { LearningSidebar } from './LearningSidebar';
import { SidebarUpdateButton } from './SidebarUpdateButton';
import { UserAvatar } from '@/components/profile/UserAvatar';
import { getAccountInitial } from '@/components/profile/user-avatar-utils';
import { UserProfileDialog } from '@/components/profile/UserProfileDialog';
import { useSettingsStore } from '@/stores/settings';
import { useAuthStore, type AuthUser } from '@/stores/auth';
import { useOpencodeStore, type ProjectDirectoryMode } from '@/stores/opencode';
import { useProviderStore } from '@/stores/providers';
import type { OpencodeProject } from '@/types/opencode';
import { useProjectConfigStore } from '@/stores/project-config';
import { EMPTY_AGENT_USER_PROFILE, getProfileAccountKey, isUserProfileComplete, useUserProfileStore, type UserGender } from '@/stores/user-profile';
import type { ProjectType } from '../../../shared/project-config';
import { toast } from 'sonner';
@@ -64,40 +61,6 @@ type ProjectEntryError = {
message: string;
};
type ProfileAvatarDraft =
| { kind: 'unchanged' }
| { kind: 'upload'; value: PreparedUserAvatar }
| { kind: 'remove' };
type UserAvatarProps = {
src: string | null | undefined;
initial: string;
className: string;
alt?: string;
testId?: string;
};
function UserAvatar({ src, initial, className, alt = '', testId }: UserAvatarProps) {
const [failedSrc, setFailedSrc] = useState<string | null>(null);
const imageAvailable = Boolean(src && failedSrc !== src);
return (
<span data-testid={testId} className={cn('flex items-center justify-center overflow-hidden rounded-full bg-accent-soft text-xs font-semibold text-foreground', className)}>
{imageAvailable ? (
<img src={src ?? undefined} alt={alt} className="h-full w-full object-cover" onError={() => setFailedSrc(src ?? null)} />
) : (
initial
)}
</span>
);
}
function getAccountInitial(name: string): string {
const first = name.trim().charAt(0);
return first ? first.toUpperCase() : 'M';
}
function getFolderName(pathValue: string): string {
const trimmed = pathValue.trim();
const withoutTrailingSeparators = trimmed.replace(/[\\/]+$/u, '');
@@ -175,23 +138,16 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
const authUser = useAuthStore((state) => state.user);
const getValidAccessToken = useAuthStore((state) => state.getValidAccessToken);
const logout = useAuthStore((state) => state.logout);
const profilesByUserId = useUserProfileStore((state) => state.profilesByUserId);
const syncStatesByUserId = useUserProfileStore((state) => state.syncStatesByUserId);
const saveUserProfile = useUserProfileStore((state) => state.saveProfile);
const setUserAvatarUrl = useUserProfileStore((state) => state.setAvatarUrl);
const syncUserProfile = useUserProfileStore((state) => state.syncProfile);
const saveUserProfileToServer = useUserProfileStore((state) => state.saveProfileToServer);
const {
userProfile,
profileRequired,
profileSyncError,
syncProfileNow,
} = useCurrentUserProfile();
const refreshProviderSnapshot = useProviderStore((state) => state.refreshProviderSnapshot);
const [projectsOpen, setProjectsOpen] = useState(true);
const [accountMenuOpen, setAccountMenuOpen] = useState(false);
const [profileDialogOpen, setProfileDialogOpen] = useState(false);
const [profileName, setProfileName] = useState('');
const [profileAge, setProfileAge] = useState('');
const [profileGender, setProfileGender] = useState<UserGender>('undisclosed');
const [profileAvatarDraft, setProfileAvatarDraft] = useState<ProfileAvatarDraft>({ kind: 'unchanged' });
const [profileAvatarProcessing, setProfileAvatarProcessing] = useState(false);
const [profileError, setProfileError] = useState<string | null>(null);
const [profileSaving, setProfileSaving] = useState(false);
const [usageDrawerOpen, setUsageDrawerOpen] = useState(false);
const [tokenUsageState, setTokenUsageState] = useState<TokenUsageState>({ status: 'idle', usage: null });
const [createDialogOpen, setCreateDialogOpen] = useState(false);
@@ -205,34 +161,21 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
const [removeProjectCandidate, setRemoveProjectCandidate] = useState<OpencodeProject | null>(null);
const accountButtonRef = useRef<HTMLButtonElement | null>(null);
const accountMenuRef = useRef<HTMLDivElement | null>(null);
const profileDialogDirtyRef = useRef(false);
const tokenUsageRequestIdRef = useRef(0);
const navigate = useNavigate();
const location = useLocation();
const activeModule = getAiModuleForPath(location.pathname);
const isProgrammingModule = activeModule === 'programming';
const isPaintingModule = activeModule === 'painting';
const isLearningModule = activeModule === 'learning';
const isPromptMuseum = location.pathname === '/image-prompts' || location.pathname.startsWith('/image-prompts/');
const projectConfigPath = '/project-config';
const visibleProjects = opencodeProjects;
const selectedProjectFolderName = getFolderName(newProjectSelectedPath);
const accountName = getAuthUserDisplayName(authUser) || '未登录用户';
const profileAccountKey = getProfileAccountKey(authUser?.userId ?? authUser?.username);
const userProfile = profileAccountKey ? profilesByUserId[profileAccountKey] : undefined;
const profileSyncState = profileAccountKey ? syncStatesByUserId[profileAccountKey] : undefined;
const profileRequired = Boolean(
authUser
&& profileSyncState?.status === 'ready'
&& !isUserProfileComplete(userProfile),
);
const accountFullName = authUser?.username?.trim() || accountName;
const accountName = userProfile?.displayName?.trim() || getAuthUserDisplayName(authUser) || '未登录用户';
const accountFullName = accountName;
const accountInitial = getAccountInitial(accountName);
const accountAvatarUrl = userProfile?.avatarUrl ?? null;
const profileAvatarPreviewUrl = profileAvatarDraft.kind === 'upload'
? profileAvatarDraft.value.previewUrl
: profileAvatarDraft.kind === 'remove'
? null
: accountAvatarUrl;
const settingsLabel = t('sidebar.settings', '设置');
const memberLabel = getSubscriptionPlanLabel(authUser, tokenUsageState);
const membershipLabel = getSubscriptionMembershipLabel(authUser, tokenUsageState);
@@ -258,109 +201,8 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
}, [isProgrammingModule, refreshProviderSnapshot]);
useEffect(() => {
if (!authUser || !profileAccountKey) return;
let cancelled = false;
void getValidAccessToken()
.then((accessToken) => {
if (!accessToken) throw new Error('登录已过期,请重新登录后再同步个人资料。');
return syncUserProfile(profileAccountKey, accessToken);
})
.catch((error) => {
if (cancelled) return;
setProfileError(error instanceof Error ? error.message : String(error));
setProfileDialogOpen(true);
});
return () => {
cancelled = true;
};
}, [authUser, getValidAccessToken, profileAccountKey, syncUserProfile]);
useEffect(() => {
if (!profileRequired) return;
profileDialogDirtyRef.current = false;
setProfileError(null);
setProfileDialogOpen(true);
}, [profileRequired]);
useEffect(() => {
if (!profileDialogOpen) {
profileDialogDirtyRef.current = false;
return;
}
if (profileDialogDirtyRef.current) return;
const profile = userProfile ?? EMPTY_AGENT_USER_PROFILE;
setProfileName(profile.displayName);
setProfileAge(profile.age === null ? '' : String(profile.age));
setProfileGender(profile.gender);
setProfileAvatarDraft({ kind: 'unchanged' });
}, [profileDialogOpen, userProfile]);
const handleAvatarFileChange = async (event: ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
event.target.value = '';
if (!file) return;
profileDialogDirtyRef.current = true;
setProfileAvatarProcessing(true);
setProfileError(null);
try {
const prepared = await prepareUserAvatar(file);
setProfileAvatarDraft({ kind: 'upload', value: prepared });
} catch (error) {
setProfileError(error instanceof Error ? error.message : '头像图片处理失败');
} finally {
setProfileAvatarProcessing(false);
}
};
const handleRemoveAvatar = () => {
profileDialogDirtyRef.current = true;
setProfileAvatarDraft({ kind: 'remove' });
setProfileError(null);
};
const handleSaveProfile = async () => {
if (!profileAccountKey) return;
const displayName = profileName.trim();
if (!displayName) { setProfileError('请填写名字'); return; }
const age = profileAge.trim() ? Number(profileAge) : null;
if (age !== null && (!Number.isInteger(age) || age < 1 || age > 150)) { setProfileError('年龄请输入 1 至 150 的整数'); return; }
setProfileError(null);
setProfileSaving(true);
try {
const accessToken = await getValidAccessToken();
if (!accessToken) throw new Error('登录已过期,请重新登录后再同步个人资料。');
if (profileAvatarDraft.kind === 'upload') {
const avatarUrl = await uploadAgentAvatar(accessToken, {
fileName: profileAvatarDraft.value.fileName,
mimeType: profileAvatarDraft.value.mimeType,
dataBase64: profileAvatarDraft.value.dataBase64,
});
if (!avatarUrl) throw new Error('头像上传成功但未返回头像地址');
setUserAvatarUrl(profileAccountKey, avatarUrl);
} else if (profileAvatarDraft.kind === 'remove') {
const avatarUrl = await deleteAgentAvatar(accessToken);
setUserAvatarUrl(profileAccountKey, avatarUrl);
}
setProfileAvatarDraft({ kind: 'unchanged' });
saveUserProfile(profileAccountKey, { displayName, age, gender: profileGender });
await saveUserProfileToServer(profileAccountKey, accessToken);
setProfileDialogOpen(false);
} catch (error) {
if (error instanceof AgentProfileApiError && error.status === 409) {
setProfileError('个人资料已在其他设备更新,请确认最新内容后再次保存。');
} else if (error instanceof AgentProfileApiError) {
setProfileError(getAgentProfileApiErrorMessage(error));
} else {
setProfileError(error instanceof Error ? error.message : String(error));
}
} finally {
setProfileSaving(false);
}
};
if (profileRequired || profileSyncError) setProfileDialogOpen(true);
}, [profileRequired, profileSyncError]);
useEffect(() => {
if (!accountMenuOpen) return undefined;
@@ -589,19 +431,8 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
const openProfileDialog = () => {
setAccountMenuOpen(false);
setUsageDrawerOpen(false);
profileDialogDirtyRef.current = false;
setProfileError(null);
setProfileDialogOpen(true);
if (profileAccountKey) {
void getValidAccessToken()
.then((accessToken) => {
if (!accessToken) throw new Error('登录已过期,请重新登录后再同步个人资料。');
return syncUserProfile(profileAccountKey, accessToken);
})
.catch((error) => {
setProfileError(error instanceof Error ? error.message : String(error));
});
}
void syncProfileNow().catch(() => undefined);
};
const openSubscriptionUpgrade = () => {
@@ -736,6 +567,8 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
) : null}
</div>
</>
) : isLearningModule ? (
<LearningSidebar sidebarCollapsed={sidebarCollapsed} />
) : (
<div data-testid="sidebar-robot-navigation" className="px-2 py-3">
<button
@@ -1015,99 +848,12 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
/>
) : null}
{profileDialogOpen ? (
<Dialog
open={profileDialogOpen}
onOpenChange={(open) => {
if (!open && !profileRequired && !profileSaving && !profileAvatarProcessing) setProfileDialogOpen(false);
}}
>
<DialogContent
className="max-w-sm p-5"
onInteractOutside={(event) => {
if (profileRequired || profileSaving || profileAvatarProcessing) event.preventDefault();
}}
>
<DialogHeader className="flex-row items-start justify-between gap-3 space-y-0">
<div>
<DialogTitle className="text-xl">个人资料</DialogTitle>
<DialogDescription className="mt-1 text-xs">帮助所有 Agent 更自然地了解和协作</DialogDescription>
</div>
{!profileRequired ? <button
type="button"
aria-label="关闭个人资料"
className="flex h-9 w-9 items-center justify-center rounded-md border border-foreground/15 bg-white text-foreground transition-transform active:scale-[0.985]"
onClick={() => setProfileDialogOpen(false)}
disabled={profileAvatarProcessing || profileSaving}
>
<X className="h-4 w-4" />
</button> : null}
</DialogHeader>
{profileRequired ? <div className="mt-4 rounded-lg border border-foreground/15 bg-surface-tertiary p-3 text-sm font-semibold">首次使用前请先填写名字。个人资料与登录账号信息相互独立。</div> : null}
<div className="mt-4 grid gap-4 text-sm font-medium">
<div>
<Label>个人头像</Label>
<div className="mt-2 flex items-center gap-3 rounded-lg border border-foreground/10 bg-surface-tertiary p-3">
<UserAvatar
src={profileAvatarPreviewUrl}
initial={getAccountInitial(profileName || accountName)}
alt="个人头像预览"
testId="profile-avatar-preview"
className="h-16 w-16 shrink-0 border border-foreground/15 text-lg shadow-soft"
/>
<div className="min-w-0 flex-1 space-y-2">
<div className="flex flex-wrap gap-2">
<label
htmlFor="profile-avatar-upload"
className={cn(
'inline-flex min-h-8 cursor-pointer items-center justify-center gap-1.5 rounded-md border border-foreground/15 bg-white px-2.5 py-1.5 text-xs font-semibold text-foreground shadow-soft transition-transform active:scale-[0.985]',
(profileAvatarProcessing || profileSaving) && 'pointer-events-none opacity-60',
)}
>
<Upload className="h-3.5 w-3.5" />
{profileAvatarProcessing ? '处理中…' : '更换头像'}
</label>
<input
id="profile-avatar-upload"
data-testid="profile-avatar-upload"
type="file"
accept="image/png,image/jpeg,image/webp"
className="sr-only"
onChange={(event) => void handleAvatarFileChange(event)}
disabled={profileAvatarProcessing || profileSaving}
/>
{profileAvatarDraft.kind !== 'remove' && (profileAvatarPreviewUrl || accountAvatarUrl) ? (
<Button
type="button"
variant="outline"
data-testid="profile-avatar-remove"
className="min-h-8 border border-foreground/15 bg-white px-2.5 py-1.5 text-xs font-semibold text-foreground"
onClick={handleRemoveAvatar}
disabled={profileAvatarProcessing || profileSaving}
>
<Trash2 className="mr-1.5 h-3.5 w-3.5" />
移除
</Button>
) : null}
</div>
<p className="text-[11px] font-medium leading-4 text-muted-foreground">
支持 PNG、JPEG、WebP 格式。
</p>
</div>
</div>
</div>
<div><Label htmlFor="profile-display-name">名字 <span className="text-red-700">*</span></Label><Input id="profile-display-name" value={profileName} maxLength={100} onChange={(event) => { profileDialogDirtyRef.current = true; setProfileName(event.target.value); }} placeholder="希望 Agent 如何称呼你" className="mt-2 border border-foreground/15 bg-white" /></div>
<div><Label htmlFor="profile-age">年龄(选填)</Label><Input id="profile-age" type="number" min={1} max={150} value={profileAge} onChange={(event) => { profileDialogDirtyRef.current = true; setProfileAge(event.target.value); }} className="mt-2 border border-foreground/15 bg-white" /></div>
<div><Label htmlFor="profile-gender">性别(选填)</Label><select id="profile-gender" value={profileGender} onChange={(event) => { profileDialogDirtyRef.current = true; setProfileGender(event.target.value as UserGender); }} className="mt-2 h-10 w-full rounded-md border border-foreground/15 bg-white px-3"><option value="undisclosed">不透露</option><option value="male">男</option><option value="female">女</option><option value="other">其他</option></select></div>
{profileError ? <p role="alert" className="text-sm font-semibold text-red-700">{profileError}</p> : null}
{profileSyncState?.status === 'loading' ? <p className="text-xs font-medium text-muted-foreground">正在同步云端个人资料…</p> : null}
<Button type="button" onClick={() => void handleSaveProfile()} disabled={profileSaving || profileAvatarProcessing || profileSyncState?.status === 'loading'} className="border border-foreground/15 bg-brand-soft font-semibold text-foreground shadow-soft">{profileSaving ? '正在同步…' : '保存个人资料'}</Button>
</div>
</DialogContent>
</Dialog>
) : null}
<UserProfileDialog
open={profileDialogOpen}
required={profileRequired}
syncError={profileSyncError}
onOpenChange={setProfileDialogOpen}
/>
<div className="mt-auto px-2 pb-2 pt-1">
<div className="relative">