🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
💄 style(project): one project avatar across tabs and settings, saved in place (#21636)
LiJiana1aa18f0bde0
diff --git a/locales/en-US/project.json b/locales/en-US/project.jsonindex 967fa8299a2..19547c76c82 100644--- a/locales/en-US/project.json+++ b/locales/en-US/project.json@@ -269,14 +269,19 @@"settings.knowledgeBases": "Libraries","settings.logo": "Logo","settings.logoDescription": "Shown in the project header, sidebar and switcher.",+ "settings.logoHint": "Click the logo to upload an image or pick an emoji. Changes are saved right away.","settings.logoSizeExceeded": "The logo must be smaller than 2 MB.",+ "settings.logoUpdated": "Logo updated","settings.logoUploadFailed": "Could not upload the logo","settings.members": "Members",+ "settings.nameHint": "Use 255 characters at most.","settings.noDirectories": "No folders in this environment yet. Add an existing folder on a connected device to start working.","settings.noEnvironments": "No environments associated yet","settings.noRepository": "No GitHub repository linked","settings.reuseEnvironment": "Add an existing environment to this project","settings.reuseEnvironmentDescription": "Already created an environment? Select it to link its repository configuration to this project, then add a working directory for this project.",+ "settings.saveFailed": "Could not save the change",+ "settings.saved": "Saved","settings.slugDescription": "Used in the project URL. Changing it updates the address; leave blank to use the project ID.","settings.startDirectoryConversation": "New topic here","settings.title": "Project settings",diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.jsonindex b831d4cf8dc..0f1c98a8eff 100644--- a/locales/zh-CN/project.json+++ b/locales/zh-CN/project.json@@ -269,14 +269,19 @@"settings.knowledgeBases": "资料库","settings.logo": "项目 Logo","settings.logoDescription": "显示在项目头部、侧边栏与项目切换器中。",+ "settings.logoHint": "点击 Logo 上传图片或选择 Emoji,修改后立即保存。","settings.logoSizeExceeded": "Logo 需小于 2 MB。",+ "settings.logoUpdated": "Logo 已更新","settings.logoUploadFailed": "Logo 上传失败","settings.members": "成员",+ "settings.nameHint": "最多 255 个字符。","settings.noDirectories": "还没有工作目录。添加已连接设备上的文件夹后,即可在此新建对话。","settings.noEnvironments": "尚未关联环境","settings.noRepository": "未关联 GitHub 仓库","settings.reuseEnvironment": "将已有环境添加到本项目","settings.reuseEnvironmentDescription": "如果之前已创建过环境,可从列表选择,将它的仓库配置关联到本项目,再为本项目添加工作目录。",+ "settings.saveFailed": "保存失败",+ "settings.saved": "已保存","settings.slugDescription": "用于项目链接。修改后地址会更新,留空则使用项目 ID。","settings.startDirectoryConversation": "在此新建话题","settings.title": "项目设置",diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.tsindex ace4a314609..180c1ee9f03 100644--- a/packages/locales/src/default/project.ts+++ b/packages/locales/src/default/project.ts@@ -72,6 +72,12 @@ export default {'settings.general': 'General','settings.logo': 'Logo','settings.logoDescription': 'Shown in the project header, sidebar and switcher.',+ 'settings.logoHint':+ 'Click the logo to upload an image or pick an emoji. Changes are saved right away.',+ 'settings.logoUpdated': 'Logo updated',+ 'settings.nameHint': 'Use 255 characters at most.',+ 'settings.saveFailed': 'Could not save the change',+ 'settings.saved': 'Saved','settings.logoSizeExceeded': 'The logo must be smaller than 2 MB.','settings.logoUploadFailed': 'Could not upload the logo','settings.advanced': 'Advanced',diff --git a/src/components/SettingCard/index.tsx b/src/components/SettingCard/index.tsxnew file mode 100644index 00000000000..b90eddfa27f--- /dev/null+++ b/src/components/SettingCard/index.tsx@@ -0,0 +1,76 @@+'use client';++import { Block, Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo, type ReactNode } from 'react';++const styles = stylex.create({+ footer: {+ backgroundColor: cssVar.colorFillQuaternary,+ borderBlockStartColor: cssVar.colorFillTertiary,+ borderBlockStartStyle: 'solid',+ borderBlockStartWidth: 1,+ paddingBlock: 12,+ paddingInline: 20,+ },+ hint: {+ color: cssVar.colorTextSecondary,+ fontSize: 13,+ },+});++export interface SettingCardProps {+ /** Footer action, usually the card's own Save button. */+ action?: ReactNode;+ children?: ReactNode;+ description?: ReactNode;+ /** Content beside the title, e.g. an avatar that is edited in place. */+ extra?: ReactNode;+ /** Footer note: a limit, or the field's validation message. */+ hint?: ReactNode;+ title: ReactNode;+}++/**+ * One setting per card, saved on its own: title and description, the field,+ * then a footer with a hint and the card's action.+ */+const SettingCard = memo<SettingCardProps>(+ ({ title, description, children, extra, hint, action }) => (+ <Block variant="outlined">+ <Flexbox gap={12} padding={20}>+ <Flexbox horizontal align="center" gap={16} justify="space-between">+ <Flexbox gap={4}>+ <Text strong as="h3" style={{ fontSize: 16, margin: 0 }}>+ {title}+ </Text>+ {description && (+ <Text style={{ fontSize: 13 }} type="secondary">+ {description}+ </Text>+ )}+ </Flexbox>+ {extra}+ </Flexbox>+ {children}+ </Flexbox>+ {(hint || action) && (+ <Flexbox+ horizontal+ align="center"+ gap={12}+ justify="space-between"+ {...stylex.props(styles.footer)}+ >+ <span {...stylex.props(styles.hint)}>{hint ?? ''}</span>+ {action}+ </Flexbox>+ )}+ </Block>+ ),+);++SettingCard.displayName = 'SettingCard';++export default SettingCard;diff --git a/src/features/CommunityWorkspaceSettings/index.tsx b/src/features/CommunityWorkspaceSettings/index.tsxindex 88cbb4f9955..5641e2e613a 100644--- a/src/features/CommunityWorkspaceSettings/index.tsx+++ b/src/features/CommunityWorkspaceSettings/index.tsx@@ -1,7 +1,7 @@'use client';import { OFFICIAL_URL } from '@lobechat/const';-import { Block, Center, createStaticStyles, cssVar, Flexbox, Icon, Tooltip } from '@lobehub/ui';+import { Center, createStaticStyles, cssVar, Flexbox, Icon, Tooltip } from '@lobehub/ui';import {Button,Input,@@ -24,15 +24,7 @@ import {Trash2,Users,} from 'lucide-react';-import {- memo,- type PropsWithChildren,- type ReactNode,- useCallback,- useEffect,- useMemo,- useState,-} from 'react';+import { memo, type PropsWithChildren, useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import {@@ -46,6 +38,7 @@ import {updateCommunityWorkspaceProfile,} from '@/business/client/services/communityWorkspaceProfile';import EmojiPicker from '@/components/EmojiPicker';+import SettingCard from '@/components/SettingCard';import UserAvatar from '@/components/UserAvatar';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { usePermission } from '@/hooks/usePermission';@@ -60,16 +53,6 @@ const ORGANIZATION_URL_PREFIX = `${OFFICIAL_URL.replace(/^https?:\/\//, '')}/comconst NAMESPACE_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;const styles = createStaticStyles(({ css, cssVar }) => ({- footer: css`- padding-block: 12px;- padding-inline: 20px;- border-block-start: 1px solid ${cssVar.colorFillTertiary};- background: ${cssVar.colorFillQuaternary};- `,- hint: css`- font-size: 13px;- color: ${cssVar.colorTextSecondary};- `,memberNameLink: css`color: inherit;@@ -91,40 +74,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({const isDefaultMarketNamespace = (namespace: string | null): boolean =>!!namespace && /[A-Z]/.test(namespace);-interface SettingCardProps {- action?: ReactNode;- children?: ReactNode;- description?: ReactNode;- hint?: ReactNode;- title: ReactNode;-}--const SettingCard = memo<SettingCardProps>(({ title, description, children, hint, action }) => (- <Block variant="outlined">- <Flexbox gap={12} padding={20}>- <Flexbox gap={4}>- <Text strong as="h3" style={{ fontSize: 16, margin: 0 }}>- {title}- </Text>- {description && (- <Text style={{ fontSize: 13 }} type="secondary">- {description}- </Text>- )}- </Flexbox>- {children}- </Flexbox>- {(hint || action) && (- <Flexbox horizontal align="center" className={styles.footer} gap={12} justify="space-between">- <span className={styles.hint}>{hint ?? ''}</span>- {action}- </Flexbox>- )}- </Block>-));--SettingCard.displayName = 'CommunityWorkspaceSettingCard';-const PageContainer = memo<PropsWithChildren>(({ children }) => (<Flexbox height="100%" style={{ overflowX: 'hidden', overflowY: 'auto' }} width="100%"><Flexboxdiff --git a/src/features/Electron/titlebar/TabBar/TabItem.tsx b/src/features/Electron/titlebar/TabBar/TabItem.tsxindex 86c99ab05db..37a1809e469 100644--- a/src/features/Electron/titlebar/TabBar/TabItem.tsx+++ b/src/features/Electron/titlebar/TabBar/TabItem.tsx@@ -9,6 +9,7 @@ import { memo, useCallback, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';import Avatar from '@/components/Avatar';+import ProjectAvatar from '@/features/Projects/ProjectAvatar';import { electronStylish } from '@/styles/electron';import { type ResolvedTab } from './hooks/useResolvedTabs';@@ -257,7 +258,9 @@ const TabItem = memo<TabItemProps>(const indicator = (<span className={styles.avatarWrapper}>- {meta.avatar ? (+ {meta.avatarSeed ? (+ <ProjectAvatar avatar={meta.avatar} name={meta.avatarSeed} size={16} />+ ) : meta.avatar ? (<AvataremojiScaleWithBackgroundavatar={meta.avatar}diff --git a/src/features/Electron/titlebar/TabBar/hooks/useResolvedTabs.ts b/src/features/Electron/titlebar/TabBar/hooks/useResolvedTabs.tsindex 78668e6e1e1..bd3300df1ae 100644--- a/src/features/Electron/titlebar/TabBar/hooks/useResolvedTabs.ts+++ b/src/features/Electron/titlebar/TabBar/hooks/useResolvedTabs.ts@@ -47,7 +47,12 @@ export const resolveTab = ((titleKey ? t(titleKey, { ns: 'electron' }) : undefined) ??t('navigation.lobehub', { ns: 'electron' });- const avatar = pickMeaningful(live?.avatar) ?? pickMeaningful(tab.cached?.avatar);+ // A live `null` is a confirmed "no avatar", so the snapshot must not bring a deleted one back.+ const avatar =+ live?.avatar === null+ ? undefined+ : (pickMeaningful(live?.avatar) ?? pickMeaningful(tab.cached?.avatar));+ const avatarSeed = pickMeaningful(live?.avatarSeed) ?? pickMeaningful(tab.cached?.avatarSeed);const backgroundColor =pickMeaningful(live?.backgroundColor) ?? pickMeaningful(tab.cached?.backgroundColor);@@ -55,6 +60,7 @@ export const resolveTab = (isActive,meta: {avatar,+ avatarSeed,backgroundColor,icon: staticMeta.icon ?? FALLBACK_ICON,title,diff --git a/src/features/Electron/titlebar/TabBar/resolveRouteMeta.test.ts b/src/features/Electron/titlebar/TabBar/resolveRouteMeta.test.tsindex 18555399b05..fbcb87d3bcd 100644--- a/src/features/Electron/titlebar/TabBar/resolveRouteMeta.test.ts+++ b/src/features/Electron/titlebar/TabBar/resolveRouteMeta.test.ts@@ -77,6 +77,19 @@ describe('guardedMergeCache', () => {expect(merged).toEqual({ avatar: 'a.png', title: 'New' });});+ it('caches the seed of a generated project avatar', () => {+ const merged = guardedMergeCache({ title: 'Fix login · Alpha' }, { avatarSeed: 'Alpha' });+ expect(merged).toEqual({ avatarSeed: 'Alpha', title: 'Fix login · Alpha' });+ });++ it('drops a cached avatar the entity has confirmed it no longer has', () => {+ const merged = guardedMergeCache(+ { avatar: 'logo.png', avatarSeed: 'Alpha', title: 'Alpha' },+ { avatar: null, avatarSeed: 'Alpha' },+ );+ expect(merged).toEqual({ avatarSeed: 'Alpha', title: 'Alpha' });+ });+it('returns prev when next is undefined', () => {const prev = { title: 'Old' };expect(guardedMergeCache(prev, undefined)).toBe(prev);diff --git a/src/features/Electron/titlebar/TabBar/resolveRouteMeta.ts b/src/features/Electron/titlebar/TabBar/resolveRouteMeta.tsindex d4dd99c9f65..315026352b0 100644--- a/src/features/Electron/titlebar/TabBar/resolveRouteMeta.ts+++ b/src/features/Electron/titlebar/TabBar/resolveRouteMeta.ts@@ -34,7 +34,7 @@ export const matchRouteMeta = (routes: RouteObject[], url: string): MatchedRoutereturn { params, static: {} };};-const isMeaningful = (value: string | undefined): value is string =>+const isMeaningful = (value: string | null | undefined): value is string =>typeof value === 'string' && value.length > 0;export const guardedMergeCache = (@@ -46,6 +46,8 @@ export const guardedMergeCache = (const merged: DynamicRouteMeta = { ...prev };if (isMeaningful(next.title)) merged.title = next.title;if (isMeaningful(next.avatar)) merged.avatar = next.avatar;+ else if (next.avatar === null) delete merged.avatar;+ if (isMeaningful(next.avatarSeed)) merged.avatarSeed = next.avatarSeed;if (isMeaningful(next.backgroundColor)) merged.backgroundColor = next.backgroundColor;return Object.keys(merged).length > 0 ? merged : undefined;@@ -53,5 +55,5 @@ export const guardedMergeCache = (export const FALLBACK_ICON = Circle;-export const pickMeaningful = (value: string | undefined): string | undefined =>+export const pickMeaningful = (value: string | null | undefined): string | undefined =>isMeaningful(value) ? value : undefined;diff --git a/src/features/Electron/titlebar/TabBar/resolveTab.test.ts b/src/features/Electron/titlebar/TabBar/resolveTab.test.tsindex aaa6323fed0..9ecaba373b1 100644--- a/src/features/Electron/titlebar/TabBar/resolveTab.test.ts+++ b/src/features/Electron/titlebar/TabBar/resolveTab.test.ts@@ -47,6 +47,34 @@ describe('resolveTab', () => {expect(resolved.meta.icon).toBe(MessageSquare);});+ it('carries a project avatar seed from the snapshot and the live meta', () => {+ const cold = resolveTab(fixtureRoutes, tab('/agent/abc', { avatarSeed: 'Alpha' }), false, t);+ expect(cold.meta.avatarSeed).toBe('Alpha');++ const live = resolveTab(+ fixtureRoutes,+ tab('/agent/abc', { avatarSeed: 'Old name' }),+ true,+ t,+ { avatarSeed: 'Alpha' },+ '/agent/abc',+ );+ expect(live.meta.avatarSeed).toBe('Alpha');+ });++ it('active tab: a live null avatar hides the cached one', () => {+ const resolved = resolveTab(+ fixtureRoutes,+ tab('/agent/abc', { avatar: 'logo.png', avatarSeed: 'Alpha' }),+ true,+ t,+ { avatar: null, avatarSeed: 'Alpha' },+ '/agent/abc',+ );+ expect(resolved.meta.avatar).toBeUndefined();+ expect(resolved.meta.avatarSeed).toBe('Alpha');+ });+it('active tab: live dynamic meta overlays the snapshot', () => {const resolved = resolveTab(fixtureRoutes,diff --git a/src/features/Projects/WorkingDirectories/GeneralSettings.tsx b/src/features/Projects/WorkingDirectories/GeneralSettings.tsxindex 50c14c76e7b..f2402b6385b 100644--- a/src/features/Projects/WorkingDirectories/GeneralSettings.tsx+++ b/src/features/Projects/WorkingDirectories/GeneralSettings.tsx@@ -1,180 +1,186 @@-import { Button, Flexbox, Form, Input, TextArea, toast } from '@lobehub/ui';+import { Button, Flexbox, Input, TextArea } from '@lobehub/ui';import { useState } from 'react';import { useTranslation } from 'react-i18next';-import AsyncError from '@/components/AsyncError';import EmojiPicker from '@/components/EmojiPicker';-import { FORM_STYLE } from '@/const/layoutTokens';+import SettingCard from '@/components/SettingCard';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { useFileStore } from '@/store/file';import type { ProjectDetail } from '@/store/project';-import { useProjectStore } from '@/store/project';import { isProjectSlugValid } from '../createProjectForm';+import { useProjectLogo, useSaveProjectField } from './useProjectGeneralSettings';-const MAX_LOGO_SIZE = 2 * 1024 * 1024;+const NAME_MAX = 255;+const SLUG_MAX = 100;-export function GeneralSettings({ project }: { project: ProjectDetail['project'] }) {+type Project = ProjectDetail['project'];++interface CardProps {+ project: Project;+}++const SaveButton = ({+ disabled,+ loading,+ onClick,+}: {+ disabled: boolean;+ loading: boolean;+ onClick: () => void;+}) => {+ const { t } = useTranslation('common');++ return (+ <Button disabled={disabled || loading} loading={loading} type="primary" onClick={onClick}>+ {t('save')}+ </Button>+ );+};++const LogoCard = ({ project }: CardProps) => {+ const { t } = useTranslation('project');+ const { avatar, busy, onChange, onDelete, onUpload } = useProjectLogo(project);++ return (+ <SettingCard+ description={t('settings.logoDescription')}+ hint={t('settings.logoHint')}+ title={t('settings.logo')}+ extra={+ <EmojiPicker+ allowDelete={!!avatar}+ allowUpload={{ enableEmoji: true }}+ loading={busy}+ shape="square"+ size={80}+ // Seeds the generated avatar shown while the project has no logo.+ title={project.name}+ value={avatar || undefined}+ onChange={onChange}+ onDelete={onDelete}+ onUpload={onUpload}+ />+ }+ />+ );+};++const NameCard = ({ project }: CardProps) => {const { t } = useTranslation('project');+ const { save, saving } = useSaveProjectField(project.id);const [name, setName] = useState(project.name);- const [slug, setSlug] = useState(project.slug ?? '');- const [description, setDescription] = useState(project.description ?? '');- const [avatar, setAvatar] = useState<string | null>(project.avatar ?? null);- const [uploading, setUploading] = useState(false);- const navigate = useWorkspaceAwareNavigate();- const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);- const [pending, setPending] = useState(false);- const [error, setError] = useState<unknown>();- const updateProject = useProjectStore((s) => s.updateProject);-- const uploadLogo = async (file: File) => {- if (file.size > MAX_LOGO_SIZE) {- toast.error(t('settings.logoSizeExceeded'));- return;- }-- setUploading(true);- try {- const result = await uploadWithProgress({ file });- if (!result?.url) {- toast.error(t('settings.logoUploadFailed'));- return;+ const trimmed = name.trim();++ return (+ <SettingCard+ hint={t('settings.nameHint')}+ title={t('create.nameLabel')}+ action={+ <SaveButton+ disabled={!trimmed || trimmed === project.name}+ loading={saving}+ onClick={() => save({ name: trimmed })}+ />}- setAvatar(result.url);- } catch (error) {- console.error('Failed to upload project logo', error);- toast.error(t('settings.logoUploadFailed'));- } finally {- setUploading(false);- }- };+ >+ <Input+ aria-label={t('create.nameLabel')}+ maxLength={NAME_MAX}+ style={{ maxWidth: 420 }}+ value={name}+ onChange={(e) => setName(e.target.value)}+ />+ </SettingCard>+ );+};- const save = async () => {- setPending(true);- setError(undefined);- try {- const saved = await updateProject(project.id, {- name: name.trim(),- slug: slug.trim() || null,- description: description.trim() || null,- avatar,- });- navigate(`/project/${saved.slug ?? saved.id}/settings/general`, { replace: true });- toast.success(t('rename.success'));- } catch (error) {- console.error('Failed to update project', error);- setError(error);- } finally {- setPending(false);- }+const IdentifierCard = ({ project }: CardProps) => {+ const { t } = useTranslation('project');++ return (+ <SettingCard description={t('settings.identifierDescription')} title={t('settings.identifier')}>+ <Input+ readOnly+ aria-label={t('settings.identifier')}+ style={{ maxWidth: 420 }}+ value={project.identifier ?? ''}+ />+ </SettingCard>+ );+};++const SlugCard = ({ project }: CardProps) => {+ const { t } = useTranslation('project');+ const navigate = useWorkspaceAwareNavigate();+ const { save, saving } = useSaveProjectField(project.id);+ const [slug, setSlug] = useState(project.slug ?? '');+ const valid = isProjectSlugValid(slug);++ const saveSlug = async () => {+ const saved = await save({ slug: slug.trim() || null });+ // The settings URL carries the slug, so follow it to the new address.+ if (saved) navigate(`/project/${saved.slug ?? saved.id}/settings/general`, { replace: true });};- const saveDisabled =- pending ||- uploading ||- !name.trim() ||- !isProjectSlugValid(slug) ||- (name.trim() === project.name &&- slug.trim() === (project.slug ?? '') &&- description.trim() === (project.description ?? '') &&- avatar === (project.avatar ?? null));return (- <Flexbox gap={24}>- <Form- {...FORM_STYLE}- collapsible={false}- itemMinWidth="100%"- itemsType="group"- layout="vertical"- variant="filled"- footer={- <Flexbox gap={16}>- {error ? <AsyncError error={error} onRetry={save} /> : null}- <Flexbox horizontal justify="flex-end">- <Button disabled={saveDisabled} loading={pending} type="primary" onClick={save}>- {t('save', { ns: 'common' })}- </Button>- </Flexbox>- </Flexbox>- }- items={[- {- title: t('settings.general'),- children: [- {- label: t('settings.logo'),- desc: t('settings.logoDescription'),- children: (- <EmojiPicker- allowDelete={!!avatar}- allowUpload={{ enableEmoji: true }}- loading={uploading}- shape="square"- size={80}- value={avatar || undefined}- onDelete={() => setAvatar(null)}- onUpload={uploadLogo}- onChange={(next) => {- if (!next.startsWith('data:')) setAvatar(next || null);- }}- />- ),- },- {- label: t('create.nameLabel'),- children: (- <Input- aria-label={t('create.nameLabel')}- disabled={pending}- maxLength={255}- value={name}- onChange={(e) => setName(e.target.value)}- />- ),- },- {- label: t('settings.identifier'),- desc: t('settings.identifierDescription'),- children: (- <Input- readOnly- aria-label={t('settings.identifier')}- value={project.identifier ?? ''}- />- ),- },- {- label: t('create.slugLabel'),- desc: t(- isProjectSlugValid(slug) ? 'settings.slugDescription' : 'create.slugInvalid',- ),- children: (- <Input- aria-invalid={!isProjectSlugValid(slug) || undefined}- aria-label={t('create.slugLabel')}- disabled={pending}- maxLength={100}- value={slug}- onChange={(e) => setSlug(e.target.value.toLowerCase())}- />- ),- },- {- label: t('settings.description'),- children: (- <TextArea- aria-label={t('settings.description')}- autoSize={{ minRows: 3, maxRows: 8 }}- disabled={pending}- value={description}- onChange={(e) => setDescription(e.target.value)}- />- ),- },- ],- },- ]}+ <SettingCard+ description={t('settings.slugDescription')}+ hint={valid ? undefined : t('create.slugInvalid')}+ title={t('create.slugLabel')}+ action={+ <SaveButton+ disabled={!valid || slug.trim() === (project.slug ?? '')}+ loading={saving}+ onClick={saveSlug}+ />+ }+ >+ <Input+ aria-invalid={!valid || undefined}+ aria-label={t('create.slugLabel')}+ maxLength={SLUG_MAX}+ style={{ maxWidth: 420 }}+ value={slug}+ onChange={(e) => setSlug(e.target.value.toLowerCase())}/>+ </SettingCard>+ );+};++const DescriptionCard = ({ project }: CardProps) => {+ const { t } = useTranslation('project');+ const { save, saving } = useSaveProjectField(project.id);+ const [description, setDescription] = useState(project.description ?? '');++ return (+ <SettingCard+ title={t('settings.description')}+ action={+ <SaveButton+ disabled={description.trim() === (project.description ?? '')}+ loading={saving}+ onClick={() => save({ description: description.trim() || null })}+ />+ }+ >+ <TextArea+ aria-label={t('settings.description')}+ autoSize={{ maxRows: 8, minRows: 3 }}+ value={description}+ onChange={(e) => setDescription(e.target.value)}+ />+ </SettingCard>+ );+};++export function GeneralSettings({ project }: CardProps) {+ return (+ <Flexbox gap={16}>+ <LogoCard project={project} />+ <NameCard project={project} />+ <IdentifierCard project={project} />+ <SlugCard project={project} />+ <DescriptionCard project={project} /></Flexbox>);}diff --git a/src/features/Projects/WorkingDirectories/useProjectGeneralSettings.test.ts b/src/features/Projects/WorkingDirectories/useProjectGeneralSettings.test.tsnew file mode 100644index 00000000000..d7eb6a43ffc--- /dev/null+++ b/src/features/Projects/WorkingDirectories/useProjectGeneralSettings.test.ts@@ -0,0 +1,119 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { ProjectDetail } from '@/store/project';++import { useProjectLogo, useSaveProjectField } from './useProjectGeneralSettings';++const mocks = vi.hoisted(() => ({+ toast: { error: vi.fn(), success: vi.fn() },+ updateProject: vi.fn(),+ uploadWithProgress: vi.fn(),+}));++vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('@lobehub/ui', () => ({ toast: mocks.toast }));+vi.mock('@/store/file', () => ({+ useFileStore: (selector: (s: unknown) => unknown) =>+ selector({ uploadWithProgress: mocks.uploadWithProgress }),+}));+vi.mock('@/store/project', () => ({+ useProjectStore: (selector: (s: unknown) => unknown) =>+ selector({ updateProject: mocks.updateProject }),+}));++const project = {+ avatar: null,+ id: 'prj_1',+ name: 'Alpha',+} as unknown as ProjectDetail['project'];++describe('useSaveProjectField', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(console, 'error').mockImplementation(() => {});+ });++ it('saves only the patched field and resolves to the saved project', async () => {+ mocks.updateProject.mockResolvedValue({ ...project, name: 'Beta' });+ const { result } = renderHook(() => useSaveProjectField('prj_1'));++ let saved: unknown;+ await act(async () => {+ saved = await result.current.save({ name: 'Beta' });+ });++ expect(mocks.updateProject).toHaveBeenCalledWith('prj_1', { name: 'Beta' });+ expect(saved).toMatchObject({ name: 'Beta' });+ expect(mocks.toast.success).toHaveBeenCalledWith('settings.saved');+ });++ it('reports a failed save and resolves to undefined', async () => {+ mocks.updateProject.mockRejectedValue(new Error('conflict'));+ const { result } = renderHook(() => useSaveProjectField('prj_1'));++ let saved: unknown = 'unset';+ await act(async () => {+ saved = await result.current.save({ slug: 'taken' });+ });++ expect(saved).toBeUndefined();+ expect(mocks.toast.error).toHaveBeenCalledWith('settings.saveFailed');+ expect(result.current.saving).toBe(false);+ });+});++describe('useProjectLogo', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.updateProject.mockResolvedValue(project);+ });++ it('saves a picked logo straight away', async () => {+ const { result } = renderHook(() => useProjectLogo(project));++ await act(async () => {+ result.current.onChange('🚀');+ });++ expect(mocks.updateProject).toHaveBeenCalledWith('prj_1', { avatar: '🚀' });+ expect(mocks.toast.success).toHaveBeenCalledWith('settings.logoUpdated');+ });++ it('saves a deleted logo as null, once', async () => {+ const { result } = renderHook(() => useProjectLogo({ ...project, avatar: '🚀' }));++ await act(async () => {+ // The picker reports the cleared value before calling onDelete.+ result.current.onChange(null);+ await result.current.onDelete();+ });++ expect(mocks.updateProject).toHaveBeenCalledTimes(1);+ expect(mocks.updateProject).toHaveBeenCalledWith('prj_1', { avatar: null });+ });++ it('saves an uploaded file by its stored URL, not the data URL preview', async () => {+ mocks.uploadWithProgress.mockResolvedValue({ url: 'https://cdn/logo.png' });+ const { result } = renderHook(() => useProjectLogo(project));+ const file = new File(['x'], 'logo.png', { type: 'image/png' });++ await act(async () => {+ result.current.onChange('data:image/png;base64,eA==');+ await result.current.onUpload(file);+ });++ expect(mocks.updateProject).toHaveBeenCalledTimes(1);+ expect(mocks.updateProject).toHaveBeenCalledWith('prj_1', { avatar: 'https://cdn/logo.png' });+ });++ it('does not save a logo that did not change', async () => {+ const { result } = renderHook(() => useProjectLogo({ ...project, avatar: '🚀' }));++ await act(async () => {+ result.current.onChange('🚀');+ });++ expect(mocks.updateProject).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Projects/WorkingDirectories/useProjectGeneralSettings.ts b/src/features/Projects/WorkingDirectories/useProjectGeneralSettings.tsnew file mode 100644index 00000000000..e497659c2c7--- /dev/null+++ b/src/features/Projects/WorkingDirectories/useProjectGeneralSettings.ts@@ -0,0 +1,86 @@+import { toast } from '@lobehub/ui';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import type { projectService } from '@/services/project';+import { useFileStore } from '@/store/file';+import type { ProjectDetail } from '@/store/project';+import { useProjectStore } from '@/store/project';++const MAX_LOGO_SIZE = 2 * 1024 * 1024;++type ProjectPatch = Parameters<typeof projectService.update>[1];++/**+ * Saves one field of the project. The store applies the patch optimistically,+ * so the header, sidebar and tabs pick it up before the request returns.+ * Resolves to the saved project, or `undefined` when the save failed.+ */+export const useSaveProjectField = (projectId: string) => {+ const { t } = useTranslation('project');+ const updateProject = useProjectStore((s) => s.updateProject);+ const [saving, setSaving] = useState(false);++ const save = async (patch: ProjectPatch, successMessage = t('settings.saved')) => {+ setSaving(true);+ try {+ const saved = await updateProject(projectId, patch);+ toast.success(successMessage);+ return saved;+ } catch (error) {+ console.error('Failed to update project', error);+ toast.error(t('settings.saveFailed'));+ } finally {+ setSaving(false);+ }+ };++ return { save, saving };+};++/** The logo saves as soon as it changes: there is no draft to confirm. */+export const useProjectLogo = (project: ProjectDetail['project']) => {+ const { t } = useTranslation('project');+ const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);+ const { save, saving } = useSaveProjectField(project.id);+ const [uploading, setUploading] = useState(false);+ const avatar = project.avatar || null;++ const saveLogo = async (next: string | null) => {+ if (next === avatar) return;+ await save({ avatar: next }, t('settings.logoUpdated'));+ };++ const onUpload = async (file: File) => {+ if (file.size > MAX_LOGO_SIZE) {+ toast.error(t('settings.logoSizeExceeded'));+ return;+ }++ setUploading(true);+ try {+ const result = await uploadWithProgress({ file });+ if (!result?.url) {+ toast.error(t('settings.logoUploadFailed'));+ return;+ }+ await saveLogo(result.url);+ } catch (error) {+ console.error('Failed to upload project logo', error);+ toast.error(t('settings.logoUploadFailed'));+ } finally {+ setUploading(false);+ }+ };++ // Deleting goes through `onDelete`; uploads arrive as data URLs before+ // `onUpload` has stored the file.+ const onChange = (next: string | null | undefined) => {+ if (!next || next.startsWith('data:')) return;+ void saveLogo(next);+ };++ const onDelete = () => saveLogo(null);++ return { avatar, busy: uploading || saving, onChange, onDelete, onUpload };+};diff --git a/src/features/Projects/routeMeta.test.ts b/src/features/Projects/routeMeta.test.tsindex 875101a818e..8b7d73ea5e3 100644--- a/src/features/Projects/routeMeta.test.ts+++ b/src/features/Projects/routeMeta.test.ts@@ -19,10 +19,13 @@ describe('project route metas', () => {// Regression: the project acceptance section reused `acceptanceRouteMeta`,// whose DynamicMeta cannot read an `:acceptanceId` here, so every project- // acceptance tab was persisted with the generic fallback title.- it('gives the project acceptance section its own static title and no runner', () => {+ // acceptance tab was persisted with the generic fallback title. Its own runner+ // only adds the project avatar (see ProjectDynamicMeta.test.ts), and loads lazily.+ it('gives the project acceptance section its own static title', () => {expect(projectAcceptanceRouteMeta.titleKey).toBe('project:sections.acceptance');expect(projectAcceptanceRouteMeta.icon).toBeDefined();- expect(projectAcceptanceRouteMeta.DynamicMeta).toBeUndefined();+ expect(+ (projectAcceptanceRouteMeta.DynamicMeta as unknown as { $$typeof: symbol }).$$typeof,+ ).toBe(Symbol.for('react.lazy'));});});diff --git a/src/features/Projects/routeMeta.ts b/src/features/Projects/routeMeta.tsindex 8ff3540d615..e51025e8b46 100644--- a/src/features/Projects/routeMeta.ts+++ b/src/features/Projects/routeMeta.ts@@ -10,6 +10,11 @@ import { routeMeta } from '@/spa/router/routeMeta';const ProjectConversationDynamicMeta = lazy(() => import('@/features/RouteMeta/ProjectDynamicMeta'),);+const ProjectSectionDynamicMeta = lazy(() =>+ import('@/features/RouteMeta/ProjectDynamicMeta').then((module) => ({+ default: module.ProjectSectionDynamicMeta,+ })),+);export const projectsRouteMeta = routeMeta({icon: FolderClosedIcon,@@ -18,12 +23,14 @@ export const projectsRouteMeta = routeMeta({});export const projectDirectoriesRouteMeta = routeMeta({+ DynamicMeta: ProjectSectionDynamicMeta,icon: FolderClosedIcon,Skeleton: createSurfaceSkeleton('list'),titleKey: 'project:settings.title',});export const projectHomeRouteMeta = routeMeta({+ DynamicMeta: ProjectSectionDynamicMeta,icon: FolderClosedIcon,Skeleton: createSurfaceSkeleton('detail'),titleKey: 'project:sections.home',@@ -40,6 +47,7 @@ export const projectConversationRouteMeta = routeMeta({// reuse `acceptanceRouteMeta` — its DynamicMeta would pin the tab to the// generic fallback label.export const projectAcceptanceRouteMeta = routeMeta({+ DynamicMeta: ProjectSectionDynamicMeta,icon: ClipboardCheckIcon,Skeleton: createSurfaceSkeleton('detail'),titleKey: 'project:sections.acceptance',diff --git a/src/features/RouteMeta/ProjectDynamicMeta.test.ts b/src/features/RouteMeta/ProjectDynamicMeta.test.tsindex 6e273e98d4e..3f4c4ddf5b6 100644--- a/src/features/RouteMeta/ProjectDynamicMeta.test.ts+++ b/src/features/RouteMeta/ProjectDynamicMeta.test.ts@@ -5,7 +5,11 @@ import { useChatStore } from '@/store/chat';import { type ProjectDetail, useProjectStore } from '@/store/project';import type { ChatTopic } from '@/types/topic';-import { useProjectConversationTitle } from './ProjectDynamicMeta';+import {+ ProjectSectionDynamicMeta,+ useProjectConversationTitle,+ useProjectTabAvatar,+} from './ProjectDynamicMeta';vi.mock('./workspaceScope', () => ({matchesRouteWorkspace: () => true,@@ -57,3 +61,58 @@ describe('useProjectConversationTitle', () => {expect(result.current).toBeUndefined();});});++describe('useProjectTabAvatar', () => {+ afterEach(() => {+ useProjectStore.setState({ projectDetailMap: {} });+ });++ it('seeds the generated avatar from the project name when there is no logo', () => {+ seedStores();++ const { result } = renderHook(() => useProjectTabAvatar({ projectId: 'prj_1' }));++ // `null`, not `undefined`: the project has loaded, so a cached logo is stale.+ expect(result.current).toEqual({ avatar: null, avatarSeed: 'Alpha' });+ });++ it("passes the project's own logo through", () => {+ useProjectStore.setState({+ projectDetailMap: {+ prj_1: {+ project: { avatar: '🚀', id: 'prj_1', name: 'Alpha', workspaceId: null },+ } as ProjectDetail,+ },+ });++ const { result } = renderHook(() => useProjectTabAvatar({ projectId: 'prj_1' }));++ expect(result.current).toEqual({ avatar: '🚀', avatarSeed: 'Alpha' });+ });++ it('publishes no avatar before the project detail lands', () => {+ const { result } = renderHook(() => useProjectTabAvatar({ projectId: 'prj_1' }));++ expect(result.current).toEqual({ avatar: undefined, avatarSeed: undefined });+ });+});++describe('ProjectSectionDynamicMeta', () => {+ afterEach(() => {+ useProjectStore.setState({ projectDetailMap: {} });+ });++ it('publishes the project avatar but no title, so the static section label stays', () => {+ seedStores();+ const onResolve = vi.fn();++ renderHook(() => ProjectSectionDynamicMeta({ onResolve, params: { projectId: 'prj_1' } }));++ expect(onResolve).toHaveBeenLastCalledWith({+ avatar: null,+ avatarSeed: 'Alpha',+ backgroundColor: undefined,+ title: undefined,+ });+ });+});diff --git a/src/features/RouteMeta/ProjectDynamicMeta.tsx b/src/features/RouteMeta/ProjectDynamicMeta.tsxindex 4c9c8c323a9..798c49db956 100644--- a/src/features/RouteMeta/ProjectDynamicMeta.tsx+++ b/src/features/RouteMeta/ProjectDynamicMeta.tsx@@ -8,13 +8,27 @@ import { useProjectStore } from '@/store/project';import { usePublishDynamicRouteMeta } from './usePublishDynamicRouteMeta';import { matchesRouteWorkspace, useRouteWorkspaceId } from './workspaceScope';-export const useProjectConversationTitle = (params: RouteMetaParams): string | undefined => {+interface ProjectIdentity {+ /** `null` once the project has loaded without a logo. */+ avatar?: string | null;+ name?: string;+}++const useProjectIdentity = (params: RouteMetaParams): ProjectIdentity => {const routeWorkspaceId = useRouteWorkspaceId(params);- const projectName = useProjectStore((state) => {+ const project = useProjectStore((state) => {const detail = params.projectId ? state.projectDetailMap[params.projectId] : undefined;if (!matchesRouteWorkspace(detail?.project.workspaceId, routeWorkspaceId)) return undefined;- return detail?.project.name || undefined;+ return detail?.project;});++ if (!project) return {};++ return { avatar: project.avatar || null, name: project.name || undefined };+};++export const useProjectConversationTitle = (params: RouteMetaParams): string | undefined => {+ const { name: projectName } = useProjectIdentity(params);const topicTitle = useChatStore((state) =>params.topicId ? topicSelectors.getTopicById(params.topicId)(state)?.title : undefined,);@@ -22,10 +36,28 @@ export const useProjectConversationTitle = (params: RouteMetaParams): string | ureturn [topicTitle, projectName].filter(Boolean).join(' · ') || undefined;};+/**+ * The project's own avatar, seeded from its name like every other project+ * avatar, so its tabs match the project switcher.+ */+export const useProjectTabAvatar = (params: RouteMetaParams) => {+ const { avatar, name } = useProjectIdentity(params);++ return { avatar, avatarSeed: name };+};+const ProjectConversationDynamicMeta = ({ onResolve, params }: DynamicRouteMetaProps) => {const title = useProjectConversationTitle(params);+ const avatar = useProjectTabAvatar(params);++ usePublishDynamicRouteMeta({ ...avatar, title }, onResolve);++ return null;+};- usePublishDynamicRouteMeta({ title }, onResolve);+/** Project sections keep their static label and only take on the project's avatar. */+export const ProjectSectionDynamicMeta = ({ onResolve, params }: DynamicRouteMetaProps) => {+ usePublishDynamicRouteMeta(useProjectTabAvatar(params), onResolve);return null;};diff --git a/src/features/RouteMeta/usePublishDynamicRouteMeta.ts b/src/features/RouteMeta/usePublishDynamicRouteMeta.tsindex a4dbfbd2e90..5fccab84ba1 100644--- a/src/features/RouteMeta/usePublishDynamicRouteMeta.ts+++ b/src/features/RouteMeta/usePublishDynamicRouteMeta.ts@@ -3,10 +3,10 @@ import { useEffect } from 'react';import type { DynamicRouteMeta } from '@/spa/router/routeMeta';export const usePublishDynamicRouteMeta = (- { avatar, backgroundColor, title }: DynamicRouteMeta,+ { avatar, avatarSeed, backgroundColor, title }: DynamicRouteMeta,onResolve: (meta: DynamicRouteMeta) => void,) => {useEffect(() => {- onResolve({ avatar, backgroundColor, title });- }, [avatar, backgroundColor, onResolve, title]);+ onResolve({ avatar, avatarSeed, backgroundColor, title });+ }, [avatar, avatarSeed, backgroundColor, onResolve, title]);};diff --git a/src/spa/router/desktopRouter.meta.desktop.test.ts b/src/spa/router/desktopRouter.meta.desktop.test.tsindex 6e2fb3997cd..01acc1f47bb 100644--- a/src/spa/router/desktopRouter.meta.desktop.test.ts+++ b/src/spa/router/desktopRouter.meta.desktop.test.ts@@ -2,6 +2,7 @@ import { HomeIcon, Image, ImageIcon, Video } from 'lucide-react';import { describe, expect, it } from 'vitest';import { matchRouteMeta } from '@/features/Electron/titlebar/TabBar/resolveRouteMeta';+import { projectAcceptanceRouteMeta } from '@/features/Projects/routeMeta';import { mainAreaMetaRoutes } from './desktopRouter.config.desktop';@@ -71,13 +72,16 @@ describe('mainAreaMetaRoutes (Electron adapter)', () => {// Regression: the project acceptance section reused `acceptanceRouteMeta`,// whose DynamicMeta cannot read an `:acceptanceId` here, so every project- // acceptance tab was persisted with the generic fallback title.- it('resolves project acceptance meta with its own static title and no runner', () => {+ // acceptance tab was persisted with the generic fallback title. Its own runner+ // only adds the project avatar and publishes no title.+ it('resolves project acceptance meta with its own static title, not the record runner', () => {const matched = matchRouteMeta(mainAreaMetaRoutes, '/project/prj_1/acceptance');+ const record = matchRouteMeta(mainAreaMetaRoutes, '/project/prj_1/acceptance/acc_1');expect(matched.static.titleKey).toBe('project:sections.acceptance');expect(matched.static.icon).toBeDefined();- expect(matched.meta?.DynamicMeta).toBeUndefined();+ expect(matched.meta).toBe(projectAcceptanceRouteMeta);+ expect(matched.meta?.DynamicMeta).not.toBe(record.meta?.DynamicMeta);});it('resolves a project acceptance record with the acceptance title runner', () => {diff --git a/src/spa/router/routeMeta.ts b/src/spa/router/routeMeta.tsindex 0ed149fc3c3..9df3fa34913 100644--- a/src/spa/router/routeMeta.ts+++ b/src/spa/router/routeMeta.ts@@ -9,7 +9,16 @@ export interface StaticRouteMeta {}export interface DynamicRouteMeta {- avatar?: string;+ /**+ * `null` means the entity loaded and has no avatar, which clears a cached+ * one; `undefined` means it is not known yet, which keeps the cache.+ */+ avatar?: string | null;+ /**+ * Name a generated avatar is seeded from, for an entity that draws one when it+ * has no image of its own (a project). Unset keeps the initials fallback.+ */+ avatarSeed?: string;backgroundColor?: string;title?: string;}@@ -38,6 +47,7 @@ export interface RouteHandle {export interface ResolvedRouteMeta {avatar?: string;+ avatarSeed?: string;backgroundColor?: string;icon?: LucideIcon;title: string;diff --git a/src/store/electron/actions/currentRouteMeta.ts b/src/store/electron/actions/currentRouteMeta.tsindex 5c39dfb5a29..9319e967ee7 100644--- a/src/store/electron/actions/currentRouteMeta.ts+++ b/src/store/electron/actions/currentRouteMeta.ts@@ -44,6 +44,7 @@ export class CurrentRouteMetaActionImpl {currentRouteMetaUrl === url &&(currentRouteMeta === null) === (meta === null) &¤tRouteMeta?.avatar === meta?.avatar &&+ currentRouteMeta?.avatarSeed === meta?.avatarSeed &¤tRouteMeta?.backgroundColor === meta?.backgroundColor &¤tRouteMeta?.title === meta?.title) {