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,25 @@
import { useState } from 'react';
import { cn } from '@/lib/utils';
export type UserAvatarProps = {
src: string | null | undefined;
initial: string;
className: string;
alt?: string;
testId?: string;
};
export 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>
);
}

View File

@@ -0,0 +1,322 @@
import { useEffect, useRef, useState, type ChangeEvent } from 'react';
import { Trash2, Upload, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { AgentProfileApiError, deleteAgentAvatar, getAgentProfileApiErrorMessage, uploadAgentAvatar } from '@/lib/agent-profile';
import { getAuthUserDisplayName } from '@/lib/auth-user-display';
import { prepareUserAvatar, type PreparedUserAvatar } from '@/lib/user-avatar';
import { cn } from '@/lib/utils';
import { useAuthStore } from '@/stores/auth';
import {
EMPTY_AGENT_USER_PROFILE,
getProfileAccountKey,
useUserProfileStore,
type UserGender,
} from '@/stores/user-profile';
import { UserAvatar } from './UserAvatar';
import { getAccountInitial } from './user-avatar-utils';
type ProfileAvatarDraft =
| { kind: 'unchanged' }
| { kind: 'upload'; value: PreparedUserAvatar }
| { kind: 'remove' };
export type UserProfileDialogProps = {
open: boolean;
required?: boolean;
syncError?: string | null;
onOpenChange: (open: boolean) => void;
};
export function UserProfileDialog({
open,
required = false,
syncError = null,
onOpenChange,
}: UserProfileDialogProps) {
const authUser = useAuthStore((state) => state.user);
const getValidAccessToken = useAuthStore((state) => state.getValidAccessToken);
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 saveUserProfileToServer = useUserProfileStore((state) => state.saveProfileToServer);
const profileAccountKey = getProfileAccountKey(authUser?.userId ?? authUser?.username);
const userProfile = profileAccountKey ? profilesByUserId[profileAccountKey] : undefined;
const profileSyncState = profileAccountKey ? syncStatesByUserId[profileAccountKey] : undefined;
const accountName = getAuthUserDisplayName(authUser) || '未登录用户';
const accountAvatarUrl = userProfile?.avatarUrl ?? null;
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 profileDialogDirtyRef = useRef(false);
const forceRequiredRef = useRef(false);
const dismissAfterSaveRef = useRef(false);
const mustCompleteProfile = required || forceRequiredRef.current;
const profileAvatarPreviewUrl = profileAvatarDraft.kind === 'upload'
? profileAvatarDraft.value.previewUrl
: profileAvatarDraft.kind === 'remove'
? null
: accountAvatarUrl;
useEffect(() => {
if (!open) {
profileDialogDirtyRef.current = false;
forceRequiredRef.current = false;
dismissAfterSaveRef.current = false;
return;
}
if (required) forceRequiredRef.current = true;
}, [open, required]);
useEffect(() => {
if (!open || 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' });
}, [open, userProfile]);
useEffect(() => {
if (open && syncError) setProfileError(syncError);
}, [open, syncError]);
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) {
setProfileError('请先登录后再维护个人资料。');
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);
forceRequiredRef.current = false;
dismissAfterSaveRef.current = true;
onOpenChange(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);
}
};
return (
<Dialog
open={open}
onOpenChange={(nextOpen) => {
if (!nextOpen && (mustCompleteProfile || profileSaving || profileAvatarProcessing) && !dismissAfterSaveRef.current) return;
if (nextOpen) dismissAfterSaveRef.current = false;
onOpenChange(nextOpen);
}}
>
<DialogContent
className="max-w-sm p-5"
onInteractOutside={(event) => {
if (mustCompleteProfile || 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>
{!mustCompleteProfile ? (
<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={() => onOpenChange(false)}
disabled={profileAvatarProcessing || profileSaving}
>
<X className="h-4 w-4" />
</button>
) : null}
</DialogHeader>
{mustCompleteProfile ? (
<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>
);
}

View File

@@ -0,0 +1,4 @@
export function getAccountInitial(name: string): string {
const first = name.trim().charAt(0);
return first ? first.toUpperCase() : 'M';
}