完善客户端模块与工作区能力
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-13 19:45:30 +08:00
parent 0148b91a15
commit 22add3f01f
97 changed files with 4756 additions and 3226 deletions

View File

@@ -1,5 +1,7 @@
import { useEffect, useState } from 'react';
import { useEffect, useMemo, useState } from 'react';
import {
ChevronDown,
ChevronRight,
FolderKanban,
Loader2,
MessageSquareText,
@@ -23,7 +25,10 @@ import { IMAGE_WORKSPACE_CREATE_PROJECT_EVENT } from '@/lib/image-workspace';
import { cn } from '@/lib/utils';
import { useImageWorkspaceStore } from '@/stores/image-workspace';
import { useAuthStore } from '@/stores/auth';
import type { DesignWorkspaceSummary } from '../../../shared/image-workspace';
import type {
DesignConversationSummary,
DesignWorkspaceSummary,
} from '../../../shared/image-workspace';
type ImageWorkspaceSidebarProps = {
sidebarCollapsed: boolean;
@@ -33,6 +38,39 @@ type ProjectDialogState =
| { mode: 'create'; project: null }
| { mode: 'rename'; project: DesignWorkspaceSummary };
const VISIBLE_CONVERSATION_LIMIT = 5;
const CONVERSATION_PREVIEW_LIMIT = 28;
const PROJECT_ACTION_BUTTON_CLASS = 'flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground pointer-events-none opacity-0 transition-[opacity,background-color,color,transform] group-hover/project:pointer-events-auto group-hover/project:opacity-100 focus-visible:pointer-events-auto focus-visible:opacity-100';
function conversationTimestamp(conversation: DesignConversationSummary): number {
const timestamp = Date.parse(conversation.updatedAt);
return Number.isFinite(timestamp) ? timestamp : 0;
}
function formatConversationTime(timestamp: number): string {
if (!timestamp) return '';
const date = new Date(timestamp);
const now = new Date();
if (date.toDateString() === now.toDateString()) {
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
return date.toLocaleDateString([], { month: 'numeric', day: 'numeric' });
}
function compactConversationPreview(preview: string): string {
const characters = Array.from(preview);
return characters.length > CONVERSATION_PREVIEW_LIMIT
? `${characters.slice(0, CONVERSATION_PREVIEW_LIMIT - 1).join('')}…`
: preview;
}
function conversationPreview(conversation: DesignConversationSummary): string {
return conversation.latestMessagePreview?.trim()
|| conversation.brief.summary.trim()
|| conversation.title.trim()
|| '新会话';
}
export function ImageWorkspaceSidebar({ sidebarCollapsed }: ImageWorkspaceSidebarProps) {
const authenticated = useAuthStore((state) => state.isAuthenticated());
const navigate = useNavigate();
@@ -50,6 +88,8 @@ export function ImageWorkspaceSidebar({ sidebarCollapsed }: ImageWorkspaceSideba
const selectProject = useImageWorkspaceStore((state) => state.selectProject);
const selectConversation = useImageWorkspaceStore((state) => state.selectConversation);
const [projectsOpen, setProjectsOpen] = useState(true);
const [expandedProjectIds, setExpandedProjectIds] = useState<Record<string, boolean>>({});
const [expandedConversationLists, setExpandedConversationLists] = useState<Record<string, boolean>>({});
const [dialog, setDialog] = useState<ProjectDialogState | null>(null);
const [projectName, setProjectName] = useState('');
const [dialogError, setDialogError] = useState<string | null>(null);
@@ -59,6 +99,15 @@ export function ImageWorkspaceSidebar({ sidebarCollapsed }: ImageWorkspaceSideba
if (status === 'idle' || (status === 'auth-required' && authenticated)) void load();
}, [authenticated, load, status]);
useEffect(() => {
if (!activeWorkspaceId) return;
setExpandedProjectIds((current) => (
current[activeWorkspaceId] === true
? current
: { ...current, [activeWorkspaceId]: true }
));
}, [activeWorkspaceId]);
useEffect(() => {
const openCreateDialog = () => {
setProjectName('');
@@ -111,10 +160,27 @@ export function ImageWorkspaceSidebar({ sidebarCollapsed }: ImageWorkspaceSideba
};
const handleSelectProject = (workspaceId: string) => {
setExpandedProjectIds((current) => ({ ...current, [workspaceId]: true }));
void selectProject(workspaceId);
navigate('/image-canvas');
};
const handleToggleProject = (workspaceId: string) => {
if (workspaceId !== activeWorkspaceId) {
handleSelectProject(workspaceId);
return;
}
setExpandedProjectIds((current) => ({
...current,
[workspaceId]: !(current[workspaceId] ?? true),
}));
};
const handleSelectConversation = (conversationId: string) => {
void selectConversation(conversationId);
navigate('/image-canvas');
};
const handleCreateConversation = async () => {
try {
await createConversation();
@@ -124,8 +190,15 @@ export function ImageWorkspaceSidebar({ sidebarCollapsed }: ImageWorkspaceSideba
}
};
const activeProjectConversations = useMemo(() => {
if (!workspace || workspace.workspaceId !== activeWorkspaceId) return [];
return [...workspace.conversations].sort(
(left, right) => conversationTimestamp(right) - conversationTimestamp(left),
);
}, [activeWorkspaceId, workspace]);
return (
<div data-testid="sidebar-image-workspace" className="min-h-0 space-y-1">
<div data-testid="sidebar-image-workspace" className="min-h-0 space-y-1 font-sans">
<Button
type="button"
variant="ghost"
@@ -206,6 +279,43 @@ export function ImageWorkspaceSidebar({ sidebarCollapsed }: ImageWorkspaceSideba
{status === 'ready' ? bootstrap?.workspaces.map((project) => {
const active = project.workspaceId === activeWorkspaceId;
const projectExpanded = expandedProjectIds[project.workspaceId] ?? active;
const projectConversationsOpen = active && projectExpanded;
const conversations = active ? activeProjectConversations : [];
const visibleConversations = conversations.slice(0, VISIBLE_CONVERSATION_LIMIT);
const hiddenConversations = conversations.slice(VISIBLE_CONVERSATION_LIMIT);
const moreConversationsOpen = expandedConversationLists[project.workspaceId]
?? hiddenConversations.some((conversation) => (
conversation.conversationId === activeConversationId
));
const renderConversation = (conversation: DesignConversationSummary) => {
const fullPreview = conversationPreview(conversation);
const selected = conversation.conversationId === activeConversationId;
return (
<button
key={conversation.conversationId}
type="button"
data-testid={`sidebar-image-conversation-${conversation.conversationId}`}
aria-current={selected ? 'page' : undefined}
title={`${conversation.title}:${fullPreview}`}
className={cn(
'group/image-conversation flex w-full min-w-0 items-center gap-1.5 rounded-lg px-1.5 py-1.5 text-left transition-[background-color,color,transform] active:scale-[0.985]',
selected
? 'bg-background text-foreground shadow-soft'
: 'text-muted-foreground hover:bg-background/70 hover:text-foreground',
)}
onClick={() => handleSelectConversation(conversation.conversationId)}
>
<MessageSquareText className="h-3.5 w-3.5 shrink-0" />
<span className="min-w-0 flex-1 truncate text-[11px] font-medium leading-4">
{compactConversationPreview(fullPreview)}
</span>
<span className="shrink-0 whitespace-nowrap text-[10px] text-muted-foreground">
{formatConversationTime(conversationTimestamp(conversation)) || '刚刚'}
</span>
</button>
);
};
return (
<section
key={project.workspaceId}
@@ -217,7 +327,10 @@ export function ImageWorkspaceSidebar({ sidebarCollapsed }: ImageWorkspaceSideba
: 'border-transparent bg-transparent hover:border-border/70 hover:bg-surface-subtle',
)}
>
<div className="flex min-w-0 items-center gap-1">
<div
className="relative flex min-h-9 min-w-0 items-center"
data-testid={`sidebar-image-project-header-${project.workspaceId}`}
>
<button
type="button"
aria-current={active ? 'page' : undefined}
@@ -227,74 +340,96 @@ export function ImageWorkspaceSidebar({ sidebarCollapsed }: ImageWorkspaceSideba
<span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface-input text-foreground">
<FolderKanban className="h-3.5 w-3.5" />
</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium">{project.title}</span>
<span className="block truncate text-[10px] font-medium text-muted-foreground">
{project.conversationCount} 个会话
</span>
</span>
</button>
<button
type="button"
aria-label={`重命名 ${project.title}`}
className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-background hover:text-foreground group-hover/project:opacity-100 focus:opacity-100"
onClick={() => openRenameDialog(project)}
>
<Pencil className="h-3.5 w-3.5" />
<span className="min-w-0 flex-1 truncate text-sm font-semibold">{project.title}</span>
</button>
<div className="pointer-events-none absolute inset-y-0 right-0 flex items-center gap-1">
<button
type="button"
aria-label={projectExpanded ? `收起 ${project.title} 的会话` : `展开 ${project.title} 的会话`}
title={projectExpanded ? `收起 ${project.title} 的会话` : `展开 ${project.title} 的会话`}
aria-expanded={active ? projectExpanded : undefined}
className={cn(PROJECT_ACTION_BUTTON_CLASS, 'hover:bg-background hover:text-foreground active:scale-[0.96]')}
onClick={() => handleToggleProject(project.workspaceId)}
>
<ChevronDown
data-testid={`sidebar-image-project-toggle-icon-${project.workspaceId}`}
className={cn('h-3.5 w-3.5 transition-transform duration-200 ease-out', projectExpanded && 'rotate-180')}
/>
</button>
<button
type="button"
aria-label={`重命名 ${project.title}`}
className={cn(PROJECT_ACTION_BUTTON_CLASS, 'hover:bg-background hover:text-foreground active:scale-[0.96]')}
onClick={() => openRenameDialog(project)}
>
<Pencil className="h-3.5 w-3.5" />
</button>
<button
type="button"
aria-label="新建设计会话"
title="新建设计会话"
aria-busy={creatingConversation}
className={cn(PROJECT_ACTION_BUTTON_CLASS, 'hover:bg-background hover:text-brand active:scale-[0.96]')}
disabled={creatingConversation || !workspace || workspace.workspaceId !== project.workspaceId}
onClick={() => void handleCreateConversation()}
>
{creatingConversation
? <Loader2 className="h-3.5 w-3.5 animate-spin" />
: <Plus className="h-3.5 w-3.5" />}
</button>
</div>
</div>
{active ? (
<div className="mt-1 border-t border-brand/15 pt-1.5">
<div className="flex min-h-10 items-center justify-between gap-2 px-1">
<span className="text-[10px] font-semibold text-muted-foreground">设计会话</span>
<DisclosureContent
open={projectConversationsOpen}
data-testid={`sidebar-image-conversations-${project.workspaceId}`}
innerClassName={cn('px-1', projectConversationsOpen ? 'pb-1 pt-1' : 'h-0')}
>
<section aria-label={`${project.title}的会话列表`}>
{workspace?.workspaceId !== project.workspaceId ? (
<div role="status" className="flex items-center gap-2 px-1.5 py-2 text-[10px] text-muted-foreground">
<Loader2 className="h-3 w-3 animate-spin text-brand" />
正在读取历史会话
</div>
) : conversations.length === 0 ? (
<button
type="button"
aria-label="新建设计会话"
title="新建设计会话"
aria-busy={creatingConversation}
className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-[background-color,color,transform] hover:bg-background hover:text-brand active:scale-[0.96]"
className="mt-1 flex w-full items-center gap-2 rounded-lg border border-dashed border-border/80 px-2 py-2 text-left text-[10px] text-muted-foreground hover:bg-background"
disabled={creatingConversation}
onClick={() => void handleCreateConversation()}
>
{creatingConversation
? <Loader2 className="h-3.5 w-3.5 animate-spin" />
: <Plus className="h-3.5 w-3.5" />}
<Plus className="h-3.5 w-3.5" />开始一条新对话
</button>
</div>
<div className="space-y-0.5 pb-1">
{workspace?.workspaceId === project.workspaceId
? workspace.conversations.slice(0, 6).map((conversation) => {
const selected = conversation.conversationId === activeConversationId;
return (
<button
key={conversation.conversationId}
type="button"
data-testid={`sidebar-image-conversation-${conversation.conversationId}`}
aria-current={selected ? 'page' : undefined}
className={cn(
'flex min-h-10 w-full items-center gap-2 rounded-lg px-2 text-left transition-[background-color,color,transform] active:scale-[0.96]',
selected
? 'bg-background text-foreground shadow-soft'
: 'text-muted-foreground hover:bg-background/70 hover:text-foreground',
)}
onClick={() => void selectConversation(conversation.conversationId)}
>
<MessageSquareText className="h-3.5 w-3.5 shrink-0" />
<span className="min-w-0 flex-1">
<span className="block truncate text-[11px] font-semibold">
{conversation.title}
</span>
<span className="block truncate text-[10px]">
{conversation.brief.summary}
</span>
</span>
</button>
);
})
: null}
</div>
</div>
) : null}
) : (
<div className="mt-0.5 space-y-0.5">
{visibleConversations.map(renderConversation)}
{hiddenConversations.length > 0 ? (
<div className="pt-1">
<button
type="button"
className="flex w-full items-center justify-between px-1.5 py-1 text-left text-[10px] font-semibold text-muted-foreground"
aria-expanded={moreConversationsOpen}
onClick={() => setExpandedConversationLists((current) => ({
...current,
[project.workspaceId]: !moreConversationsOpen,
}))}
>
<span>更多会话({hiddenConversations.length})</span>
<ChevronRight className={cn('h-3.5 w-3.5 transition-transform duration-200 ease-out', moreConversationsOpen && 'rotate-90')} />
</button>
<DisclosureContent
open={moreConversationsOpen}
data-testid={`sidebar-image-more-conversations-${project.workspaceId}`}
className="mt-0.5"
innerClassName="space-y-0.5"
>
{hiddenConversations.map(renderConversation)}
</DisclosureContent>
</div>
) : null}
</div>
)}
</section>
</DisclosureContent>
</section>
);
}) : null}

View File

@@ -85,11 +85,12 @@ export function MainLayout() {
const initializationBlocked = Boolean(activeProject && (!config || !config.initialized) && !isInitializationSafeRoute);
return (
<div data-testid="main-layout" className="flex h-screen flex-col overflow-hidden bg-transparent">
<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
workspaceLayout={isChatWorkspace}
overlay={isPaintingModule}
sidebarPeekOpen={sidebarPeekOpen}
onSidebarPeekChange={handleSidebarPeekChange}
/>
@@ -104,8 +105,9 @@ export function MainLayout() {
<main
data-testid="main-content"
className={cn(
'relative min-h-0 min-w-0 flex-1 overflow-auto bg-background p-5 sm:p-6',
isChatWorkspace && 'basis-0 overflow-hidden p-0',
'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',
isChatWorkspace && !isPaintingModule && 'basis-0 overflow-hidden p-0',
)}
>
<Outlet />

View File

@@ -9,6 +9,7 @@ const moduleToneClasses: Record<AiModuleId, { active: string }> = {
programming: { active: 'bg-brand-soft' },
painting: { active: 'bg-brand-soft' },
learning: { active: 'bg-brand-soft' },
robot: { active: 'bg-brand-soft' },
};
export function ModuleSwitcher({ sidebarCollapsed, compact = false }: { sidebarCollapsed: boolean; compact?: boolean }) {
@@ -18,7 +19,8 @@ export function ModuleSwitcher({ sidebarCollapsed, compact = false }: { sidebarC
const switcherRef = useRef<HTMLDivElement | null>(null);
const activeModuleId = getAiModuleForPath(location.pathname);
const activeModule = aiModules.find((module) => module.id === activeModuleId) ?? aiModules[0];
const getModuleLabel = (module: typeof aiModules[number]) => `${module.subtitle.replace(/^AI\s*/u, '')} ${module.title.replace(/^Makelore\s+/u, '')}`;
const getModuleLabel = (module: typeof aiModules[number]) => module.switcherLabel
?? `${module.subtitle.replace(/^AI\s*/u, '')} ${module.title.replace(/^Makelore\s+/u, '')}`;
const activeModuleLabel = getModuleLabel(activeModule);
const compactTrigger = compact && !sidebarCollapsed;

View File

@@ -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>

View File

@@ -1,6 +1,7 @@
/**
* TitleBar Component
* macOS: light application toolbar with native traffic lights handled by hiddenInset.
* macOS: light application toolbar with native traffic lights overlaid by the
* full-size hidden title bar.
* Windows: drag region with custom minimize/maximize/close controls.
* Linux: use native window chrome (no custom title bar).
*/
@@ -19,15 +20,16 @@ type SidebarPeekChange = (open: boolean, source: SidebarPeekSource) => void;
type TitleBarProps = {
integrated?: boolean;
workspaceLayout?: boolean;
overlay?: boolean;
sidebarPeekOpen?: boolean;
onSidebarPeekChange?: SidebarPeekChange;
};
export function TitleBar({ integrated = false, workspaceLayout = false, sidebarPeekOpen = false, onSidebarPeekChange }: TitleBarProps) {
export function TitleBar({ integrated = false, workspaceLayout = false, overlay = false, sidebarPeekOpen = false, onSidebarPeekChange }: TitleBarProps) {
const platform = window.electron?.platform;
if (platform === 'darwin') {
return <ProductTitleBar integrated={integrated} workspaceLayout={workspaceLayout} nativeTrafficLights sidebarPeekOpen={sidebarPeekOpen} onSidebarPeekChange={onSidebarPeekChange} />;
return <ProductTitleBar integrated={integrated} workspaceLayout={workspaceLayout} overlay={overlay} nativeTrafficLights sidebarPeekOpen={sidebarPeekOpen} onSidebarPeekChange={onSidebarPeekChange} />;
}
// Linux keeps the native frame/title bar for better IME compatibility.
@@ -35,12 +37,13 @@ export function TitleBar({ integrated = false, workspaceLayout = false, sidebarP
return null;
}
return <WindowsTitleBar integrated={integrated} workspaceLayout={workspaceLayout} sidebarPeekOpen={sidebarPeekOpen} onSidebarPeekChange={onSidebarPeekChange} />;
return <WindowsTitleBar integrated={integrated} workspaceLayout={workspaceLayout} overlay={overlay} sidebarPeekOpen={sidebarPeekOpen} onSidebarPeekChange={onSidebarPeekChange} />;
}
function ProductTitleBar({
integrated,
workspaceLayout = false,
overlay = false,
children,
nativeTrafficLights = false,
sidebarPeekOpen = false,
@@ -48,6 +51,7 @@ function ProductTitleBar({
}: {
integrated: boolean;
workspaceLayout?: boolean;
overlay?: boolean;
children?: React.ReactNode;
nativeTrafficLights?: boolean;
sidebarPeekOpen?: boolean;
@@ -67,7 +71,7 @@ function ProductTitleBar({
// The project sidebar preview is rendered below the title bar, so mirror
// its full width in the title bar for ordinary pages. The chat workspace
// has an independent conversation rail and must keep its pinned columns.
const sidebarPreviewTitlebarVisible = sidebarCollapsed && sidebarPeekOpen && !workspaceLayout;
const sidebarPreviewTitlebarVisible = sidebarCollapsed && sidebarPeekOpen && !workspaceLayout && !overlay;
const sidebarTitlebarHidden = sidebarCollapsed && !sidebarPreviewTitlebarVisible;
const conversationSurfaceOffset = sidebarTitlebarHidden
? (nativeTrafficLights ? '-132px' : '-52px')
@@ -104,16 +108,38 @@ function ProductTitleBar({
{sidebarToggle}
</div>
);
const titlebarLogo = (
<div
data-testid="titlebar-logo"
className={cn(
'pointer-events-none absolute top-1/2 z-10 h-6 w-24 -translate-y-1/2 overflow-hidden transition-[left,right] ease-out motion-reduce:transition-none',
overlay ? 'bg-transparent' : 'bg-background',
)}
style={{
right: overlay ? '0px' : 'var(--agent-browser-titlebar-logo-gap, 48px)',
transitionDuration: 'var(--agent-browser-panel-transition-duration, 180ms)',
}}
>
<img
src={logoWordmarkSource}
alt="Makelore logo"
data-logo-variant="wordmark"
data-logo-source="original-wordmark"
className="h-full w-full object-cover object-center mix-blend-multiply"
/>
</div>
);
return (
<div
data-testid="product-titlebar"
className={cn(
'relative z-30 flex h-10 shrink-0 text-foreground',
overlay && 'pointer-events-none absolute inset-x-0 top-0 z-[300] bg-transparent',
(!nativeTrafficLights || !integrated) && 'drag-region',
!workspaceLayout && 'glass-surface',
integrated && (workspaceLayout ? 'bg-transparent' : sidebarTitlebarHidden ? 'bg-background' : 'bg-background/70'),
integrated && sidebarTitlebarHidden && !workspaceLayout && 'border-b border-border/80',
!workspaceLayout && !overlay && 'glass-surface',
integrated && !overlay && (workspaceLayout ? 'bg-transparent' : sidebarTitlebarHidden ? 'bg-background' : 'bg-background/70'),
integrated && !overlay && sidebarTitlebarHidden && !workspaceLayout && 'border-b border-border/80',
)}
>
{integrated ? (
@@ -135,6 +161,7 @@ function ProductTitleBar({
sidebarPreviewTitlebarVisible ? 'sidebar-peek-surface' : 'sidebar-glass-surface',
'border-r border-border/80',
),
overlay && 'pointer-events-none border-r-0 bg-transparent',
nativeTrafficLights && 'pl-[88px]',
)}
onPointerEnter={sidebarPreviewTitlebarVisible ? () => handleSidebarPeekEnter('titlebar') : undefined}
@@ -148,8 +175,9 @@ function ProductTitleBar({
data-testid="titlebar-main-surface"
className={cn(
'relative flex min-w-0 flex-1 bg-background transition-[margin-right] ease-out motion-reduce:transition-none',
overlay && 'pointer-events-none border-b-0 bg-transparent',
nativeTrafficLights && 'drag-region',
workspaceLayout || sidebarTitlebarHidden ? 'border-b-0' : 'border-b border-border/80',
!overlay && (workspaceLayout || sidebarTitlebarHidden ? 'border-b-0' : 'border-b border-border/80'),
)}
style={{
marginRight: 'var(--agent-browser-panel-width, 0px)',
@@ -163,7 +191,7 @@ function ProductTitleBar({
style={{ left: conversationSurfaceOffset }}
/>
) : null}
{!workspaceLayout ? (
{!workspaceLayout && !overlay ? (
<div
data-testid="titlebar-project-context"
className={cn(
@@ -174,25 +202,11 @@ function ProductTitleBar({
<span className="truncate text-sm font-semibold">{activeProject?.name ?? 'Makelore 工作台'}</span>
</div>
) : null}
<div
data-testid="titlebar-logo"
className="pointer-events-none absolute top-1/2 z-10 h-6 w-24 -translate-y-1/2 overflow-hidden bg-background transition-[right] ease-out motion-reduce:transition-none"
style={{
right: 'var(--agent-browser-titlebar-logo-gap, 48px)',
transitionDuration: 'var(--agent-browser-panel-transition-duration, 180ms)',
}}
>
<img
src={logoWordmarkSource}
alt="Makelore logo"
data-logo-variant="wordmark"
data-logo-source="original-wordmark"
className="h-full w-full object-cover object-center"
/>
</div>
{!overlay ? titlebarLogo : null}
<div
className={cn(
'no-drag absolute inset-y-0 right-0 z-10 flex items-center justify-end gap-1 px-2',
overlay && 'pointer-events-auto',
)}
>
{children}
@@ -201,11 +215,12 @@ function ProductTitleBar({
) : (
<div className="flex min-w-0 flex-1 items-center justify-end gap-1 px-2">{children}</div>
)}
{integrated && overlay ? titlebarLogo : null}
</div>
);
}
function WindowsTitleBar({ integrated, workspaceLayout, sidebarPeekOpen, onSidebarPeekChange }: Omit<TitleBarProps, 'integrated'> & { integrated: boolean }) {
function WindowsTitleBar({ integrated, workspaceLayout, overlay, sidebarPeekOpen, onSidebarPeekChange }: Omit<TitleBarProps, 'integrated'> & { integrated: boolean }) {
const [maximized, setMaximized] = useState(false);
useEffect(() => {
@@ -232,8 +247,8 @@ function WindowsTitleBar({ integrated, workspaceLayout, sidebarPeekOpen, onSideb
};
return (
<ProductTitleBar integrated={integrated} workspaceLayout={workspaceLayout} sidebarPeekOpen={sidebarPeekOpen} onSidebarPeekChange={onSidebarPeekChange}>
<div className="no-drag flex h-full">
<ProductTitleBar integrated={integrated} workspaceLayout={workspaceLayout} overlay={overlay} sidebarPeekOpen={sidebarPeekOpen} onSidebarPeekChange={onSidebarPeekChange}>
<div className="no-drag pointer-events-auto flex h-full">
<button
onClick={handleMinimize}
className="motion-press flex h-full w-11 items-center justify-center text-muted-foreground hover:bg-surface-subtle"