完善客户端模块与工作区能力
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useLocation, useNavigate } from 'react-router-dom';
|
||||
@@ -11,6 +11,8 @@ import {
|
||||
LogOut,
|
||||
Plus,
|
||||
Settings as SettingsIcon,
|
||||
Trash2,
|
||||
Upload,
|
||||
UserCircle2,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
@@ -21,10 +23,11 @@ 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 } from '@/lib/agent-profile';
|
||||
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';
|
||||
@@ -60,6 +63,34 @@ 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);
|
||||
@@ -146,6 +177,7 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
|
||||
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 refreshProviderSnapshot = useProviderStore((state) => state.refreshProviderSnapshot);
|
||||
@@ -155,6 +187,8 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
|
||||
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);
|
||||
@@ -170,6 +204,7 @@ 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();
|
||||
@@ -188,6 +223,12 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
|
||||
);
|
||||
const accountFullName = authUser?.username?.trim() || 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);
|
||||
@@ -233,35 +274,82 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
|
||||
|
||||
useEffect(() => {
|
||||
if (!profileRequired) return;
|
||||
profileDialogDirtyRef.current = false;
|
||||
setProfileError(null);
|
||||
setProfileDialogOpen(true);
|
||||
}, [profileRequired]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!profileDialogOpen) return;
|
||||
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; }
|
||||
saveUserProfile(profileAccountKey, { displayName, age, gender: profileGender });
|
||||
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));
|
||||
}
|
||||
@@ -497,8 +585,19 @@ 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));
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const openSubscriptionUpgrade = () => {
|
||||
@@ -534,7 +633,13 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
|
||||
sidebarPeekPreview && 'sidebar-peek-surface pt-10 shadow-float',
|
||||
)}
|
||||
>
|
||||
<div className={cn('bg-transparent px-3 py-2 text-foreground', sidebarCollapsed && 'px-2')}>
|
||||
<div
|
||||
className={cn(
|
||||
'bg-transparent px-3 text-foreground',
|
||||
isPaintingModule && !sidebarCollapsed ? 'pb-2 pt-10' : 'py-2',
|
||||
sidebarCollapsed && 'px-2',
|
||||
)}
|
||||
>
|
||||
<div className="min-w-0 w-full">
|
||||
<ModuleSwitcher sidebarCollapsed={sidebarCollapsed} compact={!sidebarCollapsed} />
|
||||
</div>
|
||||
@@ -611,7 +716,7 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
|
||||
className="h-5 w-5 overflow-hidden rounded-full border border-background bg-white"
|
||||
>
|
||||
<img
|
||||
src={getAgentAvatarSrc(agent.avatarId)}
|
||||
src={getAgentAvatarSrc(agent.avatarId, agent.avatarDataUrl)}
|
||||
alt=""
|
||||
className="h-full w-full object-cover [image-rendering:pixelated]"
|
||||
/>
|
||||
@@ -889,13 +994,13 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
|
||||
<Dialog
|
||||
open={profileDialogOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!open && !profileRequired && !profileSaving) setProfileDialogOpen(false);
|
||||
if (!open && !profileRequired && !profileSaving && !profileAvatarProcessing) setProfileDialogOpen(false);
|
||||
}}
|
||||
>
|
||||
<DialogContent
|
||||
className="max-w-sm p-5"
|
||||
onInteractOutside={(event) => {
|
||||
if (profileRequired || profileSaving) event.preventDefault();
|
||||
if (profileRequired || profileSaving || profileAvatarProcessing) event.preventDefault();
|
||||
}}
|
||||
>
|
||||
<DialogHeader className="flex-row items-start justify-between gap-3 space-y-0">
|
||||
@@ -908,6 +1013,7 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
|
||||
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}
|
||||
@@ -916,12 +1022,63 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
|
||||
{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 htmlFor="profile-display-name">名字 <span className="text-red-700">*</span></Label><Input id="profile-display-name" value={profileName} maxLength={100} onChange={(event) => 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) => 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) => 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>
|
||||
<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 || profileSyncState?.status === 'loading'} className="border border-foreground/15 bg-brand-soft font-semibold text-foreground shadow-soft">{profileSaving ? '正在同步…' : '保存个人资料'}</Button>
|
||||
<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>
|
||||
@@ -947,9 +1104,12 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
|
||||
sidebarCollapsed && 'min-h-9 w-full justify-center px-0',
|
||||
)}
|
||||
>
|
||||
<span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-accent-soft text-xs font-semibold text-foreground">
|
||||
{accountInitial}
|
||||
</span>
|
||||
<UserAvatar
|
||||
src={accountAvatarUrl}
|
||||
initial={accountInitial}
|
||||
testId="sidebar-account-avatar"
|
||||
className="h-7 w-7 shrink-0"
|
||||
/>
|
||||
{!sidebarCollapsed && (
|
||||
<>
|
||||
<span className="min-w-0 flex-1">
|
||||
@@ -977,9 +1137,12 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
|
||||
>
|
||||
<div className="px-1 py-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-accent-soft text-xs font-semibold text-foreground">
|
||||
{accountInitial}
|
||||
</span>
|
||||
<UserAvatar
|
||||
src={accountAvatarUrl}
|
||||
initial={accountInitial}
|
||||
testId="sidebar-account-menu-avatar"
|
||||
className="h-7 w-7 shrink-0"
|
||||
/>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm font-semibold">{accountFullName}</p>
|
||||
<p className="mt-0.5 text-[10px] font-medium text-muted-foreground">{membershipLabel}</p>
|
||||
|
||||
Reference in New Issue
Block a user