Skip to content

🤯 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.

✨ feat(agent): add profile artwork generation (#17929)

Arvin Xu5952f4c3f29e
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index aa595e6a754..151803d6f1c 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -679,6 +679,22 @@
"settingAgent.agentTools.tabAgent": "Agent Tools",
"settingAgent.agentTools.tabUser": "User Tools",
"settingAgent.agentTools.tabWorkspace": "Workspace Tools",
+ "settingAgent.artwork.avatar.generate": "Generate avatar",
+ "settingAgent.artwork.avatar.generateAction": "Generate from Agent Profile",
+ "settingAgent.artwork.avatar.generating": "Creating an avatar that matches this Agent…",
+ "settingAgent.artwork.avatar.image": "Image avatar",
+ "settingAgent.artwork.background.empty": "Add a background to give this Agent a visual identity",
+ "settingAgent.artwork.background.emptyHint": "Add a cover image",
+ "settingAgent.artwork.background.generate": "Generate background",
+ "settingAgent.artwork.background.generating": "Creating a matching background…",
+ "settingAgent.artwork.background.remove": "Remove background",
+ "settingAgent.artwork.background.upload": "Upload background",
+ "settingAgent.artwork.cancel": "Cancel generation",
+ "settingAgent.artwork.generateFailed": "Could not generate the image. Try again.",
+ "settingAgent.artwork.generatingHint": "This usually takes about 60 seconds. You can keep editing while it finishes.",
+ "settingAgent.artwork.retry": "Try again",
+ "settingAgent.artwork.sizeExceeded": "Image must be smaller than 1 MB",
+ "settingAgent.artwork.uploadFailed": "Could not upload the image. Try again.",
"settingAgent.avatar.sizeExceeded": "Image size exceeds 1MB limit, please choose a smaller image",
"settingAgent.avatar.title": "Avatar",
"settingAgent.backgroundColor.title": "Background Color",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index c4f4868c9d9..1ce5e79d531 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -679,6 +679,22 @@
"settingAgent.agentTools.tabAgent": "Agent 工具",
"settingAgent.agentTools.tabUser": "用户工具",
"settingAgent.agentTools.tabWorkspace": "Workspace 工具",
+ "settingAgent.artwork.avatar.generate": "生成头像",
+ "settingAgent.artwork.avatar.generateAction": "根据助理档案生成",
+ "settingAgent.artwork.avatar.generating": "正在生成符合助理形象的头像…",
+ "settingAgent.artwork.avatar.image": "图片头像",
+ "settingAgent.artwork.background.empty": "添加背景,让助理拥有更鲜明的视觉形象",
+ "settingAgent.artwork.background.emptyHint": "添加封面图片",
+ "settingAgent.artwork.background.generate": "生成背景",
+ "settingAgent.artwork.background.generating": "正在生成与头像协调的背景…",
+ "settingAgent.artwork.background.remove": "移除背景",
+ "settingAgent.artwork.background.upload": "上传背景",
+ "settingAgent.artwork.cancel": "取消生成",
+ "settingAgent.artwork.generateFailed": "暂时无法生成图片,请重试",
+ "settingAgent.artwork.generatingHint": "通常需要约 60 秒,生成期间可以继续编辑其他内容",
+ "settingAgent.artwork.retry": "重试",
+ "settingAgent.artwork.sizeExceeded": "图片大小不能超过 1 MB",
+ "settingAgent.artwork.uploadFailed": "暂时无法上传图片,请重试",
"settingAgent.avatar.sizeExceeded": "图片大小超过 1MB 限制,请选择更小的图片",
"settingAgent.avatar.title": "助理头像",
"settingAgent.backgroundColor.title": "头像背景色",
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 14f98c018e2..ffd50e7ff72 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -736,6 +736,23 @@ export default {
'plugin.store': 'Skill Store',
'settingAgent.avatar.sizeExceeded': 'Image size exceeds 1MB limit, please choose a smaller image',
'settingAgent.avatar.title': 'Avatar',
+ 'settingAgent.artwork.avatar.generate': 'Generate avatar',
+ 'settingAgent.artwork.avatar.generateAction': 'Generate from Agent Profile',
+ 'settingAgent.artwork.avatar.generating': 'Creating an avatar that matches this Agent…',
+ 'settingAgent.artwork.avatar.image': 'Image avatar',
+ 'settingAgent.artwork.background.empty': 'Add a background to give this Agent a visual identity',
+ 'settingAgent.artwork.background.emptyHint': 'Add a cover image',
+ 'settingAgent.artwork.background.generate': 'Generate background',
+ 'settingAgent.artwork.background.generating': 'Creating a matching background…',
+ 'settingAgent.artwork.background.remove': 'Remove background',
+ 'settingAgent.artwork.background.upload': 'Upload background',
+ 'settingAgent.artwork.cancel': 'Cancel generation',
+ 'settingAgent.artwork.generateFailed': 'Could not generate the image. Try again.',
+ 'settingAgent.artwork.generatingHint':
+ 'This usually takes about 60 seconds. You can keep editing while it finishes.',
+ 'settingAgent.artwork.retry': 'Try again',
+ 'settingAgent.artwork.sizeExceeded': 'Image must be smaller than 1 MB',
+ 'settingAgent.artwork.uploadFailed': 'Could not upload the image. Try again.',
'settingAgent.backgroundColor.title': 'Background Color',
'settingAgent.description.desc': 'A brief introduction to your agent, not for character setting',
'settingAgent.description.placeholder': 'Enter agent description',
diff --git a/packages/prompts/src/prompts/agentArtwork/index.test.ts b/packages/prompts/src/prompts/agentArtwork/index.test.ts
new file mode 100644
index 00000000000..bf0493d3f7b
--- /dev/null
+++ b/packages/prompts/src/prompts/agentArtwork/index.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildAgentArtworkPrompt } from './index';
+
+describe('buildAgentArtworkPrompt', () => {
+ it('injects escaped Agent identity and description into the avatar prompt', () => {
+ const prompt = buildAgentArtworkPrompt({
+ description: 'Helps with TypeScript & React',
+ id: 'agent-1',
+ kind: 'avatar',
+ name: 'Coco "Coder"',
+ title: 'Coding assistant',
+ });
+
+ expect(prompt).toContain(
+ '<agent id="agent-1" name="Coco &quot;Coder&quot;" title="Coding assistant">',
+ );
+ expect(prompt).toContain('<description>Helps with TypeScript &amp; React</description>');
+ expect(prompt).toContain('full-bleed composition');
+ expect(prompt).toContain('square profile icon');
+ });
+
+ it('includes the system role in a wide background prompt', () => {
+ const prompt = buildAgentArtworkPrompt({
+ id: 'researcher',
+ kind: 'background',
+ systemRole: 'Find and synthesize reliable evidence.',
+ });
+
+ expect(prompt).toContain('<system_role>Find and synthesize reliable evidence.</system_role>');
+ expect(prompt).toContain('wide cinematic profile cover');
+ });
+
+ it('coordinates a background with an attached avatar reference', () => {
+ const prompt = buildAgentArtworkPrompt({
+ id: 'designer',
+ kind: 'background',
+ referenceImageUrl: 'https://example.com/avatar.png',
+ });
+
+ expect(prompt).toContain('attached existing avatar as the visual source of truth');
+ expect(prompt).toContain('dominant color palette');
+ expect(prompt).toContain('Do not enlarge, repeat, or place the avatar itself in the cover');
+ });
+
+ it('coordinates an avatar with an attached background reference', () => {
+ const prompt = buildAgentArtworkPrompt({
+ id: 'designer',
+ kind: 'avatar',
+ referenceImageUrl: 'https://example.com/background.png',
+ });
+
+ expect(prompt).toContain('attached existing profile background as the visual source of truth');
+ expect(prompt).toContain('same identity system');
+ });
+});
diff --git a/packages/prompts/src/prompts/agentArtwork/index.ts b/packages/prompts/src/prompts/agentArtwork/index.ts
new file mode 100644
index 00000000000..8b4e9c867f9
--- /dev/null
+++ b/packages/prompts/src/prompts/agentArtwork/index.ts
@@ -0,0 +1,65 @@
+import { escapeXmlAttr, escapeXmlContent } from '../search/xmlEscape';
+
+export type AgentArtworkKind = 'avatar' | 'background';
+
+export interface AgentArtworkPromptInput {
+ description?: string | null;
+ id: string;
+ kind: AgentArtworkKind;
+ name?: string | null;
+ referenceImageUrl?: string | null;
+ systemRole?: string | null;
+ title?: string | null;
+}
+
+const formatAgentContext = ({
+ description,
+ id,
+ name,
+ systemRole,
+ title,
+}: Omit<AgentArtworkPromptInput, 'kind'>): string => {
+ const attributes = [`id="${escapeXmlAttr(id)}"`];
+
+ if (name?.trim()) attributes.push(`name="${escapeXmlAttr(name.trim())}"`);
+ if (title?.trim()) attributes.push(`title="${escapeXmlAttr(title.trim())}"`);
+
+ const details = [
+ description?.trim() && `<description>${escapeXmlContent(description.trim())}</description>`,
+ systemRole?.trim() && `<system_role>${escapeXmlContent(systemRole.trim())}</system_role>`,
+ ].filter(Boolean);
+
+ return `<agent ${attributes.join(' ')}>${details.join('')}</agent>`;
+};
+
+export const buildAgentArtworkPrompt = (input: AgentArtworkPromptInput): string => {
+ const agentContext = formatAgentContext({
+ description: input.description,
+ id: input.id,
+ name: input.name,
+ systemRole: input.systemRole?.slice(0, 1200),
+ title: input.title,
+ });
+
+ if (input.kind === 'avatar') {
+ const referenceDirection = input.referenceImageUrl?.trim()
+ ? `\n\nUse the attached existing profile background as the visual source of truth. Preserve its dominant color palette, illustration style, materials, lighting, atmosphere, and recurring motifs while distilling them into a single avatar subject. The avatar must feel designed as part of the same identity system, not merely depict a related topic.`
+ : '';
+
+ return `Create a distinctive square profile icon for the AI agent described below.
+
+${agentContext}
+
+Translate the agent's identity, purpose, and personality into one coherent visual concept. Use a single centered subject, a simple silhouette, polished editorial illustration, calm colors, and high contrast. Fill the entire square canvas edge to edge with the artwork: use a full-bleed composition with no white background, no white matte, no empty margin, no padding, no frame, and no border. No words, no letters, and no logo. The result must remain clear as a small app avatar.${referenceDirection}`;
+ }
+
+ const referenceDirection = input.referenceImageUrl?.trim()
+ ? `\n\nUse the attached existing avatar as the visual source of truth. Preserve its dominant color palette, illustration style, materials, lighting, atmosphere, and recurring motifs, then expand that visual world into a wide environment. Do not enlarge, repeat, or place the avatar itself in the cover. The cover and avatar must feel designed as one identity system.`
+ : '';
+
+ return `Create a wide cinematic profile cover for the AI agent described below.
+
+${agentContext}
+
+Translate the agent's identity, purpose, and personality into an abstract editorial environment. Use a calm premium visual language, generous negative space, and a balanced composition. Do not use a person portrait, words, letters, a logo, or a border.${referenceDirection}`;
+};
diff --git a/packages/prompts/src/prompts/index.ts b/packages/prompts/src/prompts/index.ts
index 63fe43b3319..1c786782e21 100644
--- a/packages/prompts/src/prompts/index.ts
+++ b/packages/prompts/src/prompts/index.ts
@@ -1,3 +1,4 @@
+export * from './agentArtwork';
export * from './agentBuilder';
export * from './agentDocuments';
export * from './agentGroup';
diff --git a/src/features/AgentProfileArtwork/index.tsx b/src/features/AgentProfileArtwork/index.tsx
new file mode 100644
index 00000000000..733912d27a1
--- /dev/null
+++ b/src/features/AgentProfileArtwork/index.tsx
@@ -0,0 +1,490 @@
+'use client';
+
+import { ActionIcon, Alert, Avatar, Center, Flexbox, Icon, Text, Tooltip } from '@lobehub/ui';
+import { Button, toast } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { ImageIcon, Trash2, UploadIcon, WandSparkles } from 'lucide-react';
+import { memo, useCallback, useId, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import EmojiPicker from '@/components/EmojiPicker';
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+import { useAgentStore } from '@/store/agent';
+import { agentArtworkSelectors } from '@/store/agent/selectors';
+import { useAiInfraStore } from '@/store/aiInfra';
+import { aiProviderSelectors } from '@/store/aiInfra/selectors';
+import { useFileStore } from '@/store/file';
+
+import { openFilePicker, resolveAgentBackground } from './utils';
+
+const MAX_ARTWORK_SIZE = 1024 * 1024;
+
+const styles = createStaticStyles(({ css }) => ({
+ avatar: css`
+ position: absolute;
+ z-index: 4;
+ inset-block-end: 0;
+ inset-inline-start: 24px;
+
+ border: 4px solid ${cssVar.colorBgContainer};
+ border-radius: calc(${cssVar.borderRadiusLG} + 4px);
+
+ background: ${cssVar.colorBgContainer};
+
+ .ant-avatar:focus {
+ outline: none;
+ }
+ `,
+ avatarGenerating: css`
+ pointer-events: none;
+
+ position: absolute;
+ z-index: 3;
+ inset: 4px;
+
+ border-radius: ${cssVar.borderRadiusLG};
+
+ background: color-mix(in srgb, ${cssVar.colorBgContainer} 82%, transparent);
+ backdrop-filter: blur(8px);
+ `,
+ background: css`
+ position: relative;
+
+ overflow: hidden;
+
+ width: calc(100% + 32px);
+ height: 160px;
+ margin-inline: -16px;
+ border-radius: ${cssVar.borderRadiusLG};
+
+ background: transparent;
+ background-position: center;
+ background-size: cover;
+
+ transition: height ${cssVar.motionDurationMid};
+ `,
+ backgroundActions: css`
+ position: absolute;
+ z-index: 2;
+ inset-block-start: 12px;
+ inset-inline-end: 12px;
+
+ opacity: 0;
+
+ transition: opacity ${cssVar.motionDurationFast};
+
+ .agent-background:hover &,
+ .agent-background:focus-within & {
+ opacity: 1;
+ }
+ `,
+ avatarPicker: css`
+ .ant-tabs-tab:has([id$='-tab-generate']) {
+ order: -1;
+ }
+ `,
+ compactBackground: css`
+ height: 80px;
+ `,
+ emptyBackgroundActions: css`
+ position: absolute;
+ inset: 0;
+ opacity: 0;
+ transition: opacity ${cssVar.motionDurationFast};
+
+ .agent-background:hover &,
+ .agent-background:focus-within & {
+ opacity: 1;
+ }
+ `,
+ emptyBackgroundHint: css`
+ color: ${cssVar.colorTextSecondary};
+ `,
+ generatedAction: css`
+ width: 100%;
+ `,
+ generatedPreview: css`
+ position: relative;
+
+ overflow: hidden;
+
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ generationFeedback: css`
+ position: absolute;
+ z-index: 3;
+ inset: 0;
+
+ padding: 16px;
+
+ color: ${cssVar.colorText};
+
+ background: color-mix(in srgb, ${cssVar.colorBgContainer} 88%, transparent);
+ backdrop-filter: blur(12px);
+ `,
+ generationHint: css`
+ font-size: 13px;
+ color: ${cssVar.colorTextSecondary};
+ text-align: center;
+ `,
+ generationActions: css`
+ margin-block-start: 4px;
+ `,
+ generationTitle: css`
+ font-weight: 500;
+ `,
+ previewGenerationFeedback: css`
+ inset: 1px;
+ border-radius: calc(${cssVar.borderRadiusLG} - 1px);
+ `,
+ visuallyHiddenInput: css`
+ pointer-events: none;
+
+ position: fixed;
+
+ overflow: hidden;
+
+ width: 1px;
+ height: 1px;
+
+ opacity: 0;
+ `,
+ scrim: css`
+ position: absolute;
+ inset: 0;
+ background: linear-gradient(to bottom, transparent 45%, rgb(0 0 0 / 16%));
+ `,
+}));
+
+interface AgentProfileArtworkProps {
+ agentId: string;
+ avatar?: string | null;
+ background?: string | null;
+ canEdit: boolean;
+ description?: string | null;
+ locale: string;
+ name?: string | null;
+ onAvatarChange: (avatar: string | null) => void;
+ onBackgroundChange: (background: string | null) => void;
+ systemRole?: string | null;
+ title?: string | null;
+}
+
+export const AgentProfileArtwork = memo<AgentProfileArtworkProps>(
+ ({
+ avatar,
+ agentId,
+ background,
+ canEdit,
+ description,
+ locale,
+ name,
+ systemRole,
+ title,
+ onAvatarChange,
+ onBackgroundChange,
+ }) => {
+ const { t } = useTranslation('setting');
+ const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);
+ const canGenerate = useAiInfraStore(
+ (state) => aiProviderSelectors.enabledImageModelList(state).length > 0,
+ );
+ const generateAgentArtwork = useAgentStore((s) => s.generateAgentArtwork);
+ const cancelAgentArtworkGeneration = useAgentStore((s) => s.cancelAgentArtworkGeneration);
+ const generation = useAgentStore(agentArtworkSelectors.generationByAgentId(agentId));
+ const backgroundInputRef = useRef<HTMLInputElement>(null);
+ const backgroundInputId = useId();
+ const [avatarUploading, setAvatarUploading] = useState(false);
+ const [backgroundUploading, setBackgroundUploading] = useState(false);
+ const generating = generation?.status === 'generating' ? generation.kind : null;
+ const generationError = generation?.status === 'error' ? generation.kind : null;
+ const backgroundGenerationActive = generation?.kind === 'background';
+ const backgroundUrl = resolveAgentBackground(background);
+
+ const openBackgroundFilePicker = useCallback(() => {
+ const input = backgroundInputRef.current;
+ if (!input) return;
+
+ openFilePicker(input);
+ }, []);
+
+ const upload = useCallback(
+ async (kind: 'avatar' | 'background', file: File) => {
+ if (!canEdit) return;
+ if (file.size > MAX_ARTWORK_SIZE) {
+ toast.error(t('settingAgent.artwork.sizeExceeded'));
+ return;
+ }
+
+ const setUploading = kind === 'avatar' ? setAvatarUploading : setBackgroundUploading;
+ setUploading(true);
+ try {
+ const result = await uploadWithProgress({ file });
+ if (!result?.url) throw new Error('Upload returned no URL');
+ if (kind === 'avatar') onAvatarChange(result.url);
+ else onBackgroundChange(result.url);
+ } catch (error) {
+ console.error('Failed to upload agent artwork:', error);
+ toast.error(t('settingAgent.artwork.uploadFailed'));
+ } finally {
+ setUploading(false);
+ }
+ },
+ [canEdit, onAvatarChange, onBackgroundChange, t, uploadWithProgress],
+ );
+
+ const generateArtwork = useCallback(
+ async (kind: 'avatar' | 'background') => {
+ if (!canEdit || !canGenerate) return;
+
+ try {
+ await generateAgentArtwork({
+ description,
+ id: agentId,
+ kind,
+ name,
+ referenceImageUrl: kind === 'background' ? avatar : backgroundUrl,
+ systemRole,
+ title,
+ });
+ } catch {
+ // The Agent store owns the persistent error state rendered below.
+ }
+ },
+ [
+ agentId,
+ avatar,
+ backgroundUrl,
+ canEdit,
+ canGenerate,
+ description,
+ generateAgentArtwork,
+ name,
+ systemRole,
+ title,
+ ],
+ );
+
+ return (
+ <div style={{ paddingBlockEnd: 36, position: 'relative' }}>
+ <div
+ className={`${styles.background} ${!backgroundUrl && !backgroundGenerationActive ? styles.compactBackground : ''} agent-background`}
+ style={{ backgroundImage: backgroundUrl ? `url(${backgroundUrl})` : undefined }}
+ >
+ {backgroundUrl ? <div className={styles.scrim} /> : null}
+ {generating === 'background' ? (
+ <Center className={styles.generationFeedback}>
+ <Flexbox align={'center'} gap={10}>
+ <NeuralNetworkLoading size={32} />
+ <Flexbox align={'center'} gap={4}>
+ <Text className={styles.generationTitle}>
+ {t('settingAgent.artwork.background.generating')}
+ </Text>
+ <Text className={styles.generationHint}>
+ {t('settingAgent.artwork.generatingHint')}
+ </Text>
+ <Button
+ className={styles.generationActions}
+ size={'small'}
+ type={'fill'}
+ onClick={() => void cancelAgentArtworkGeneration(agentId)}
+ >
+ {t('settingAgent.artwork.cancel')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ </Center>
+ ) : generationError === 'background' ? (
+ <Center className={styles.generationFeedback}>
+ <Flexbox align={'center'} gap={10}>
+ <Text>{t('settingAgent.artwork.generateFailed')}</Text>
+ <Button
+ icon={WandSparkles}
+ size={'small'}
+ onClick={() => void generateArtwork('background')}
+ >
+ {t('settingAgent.artwork.retry')}
+ </Button>
+ </Flexbox>
+ </Center>
+ ) : null}
+ {!backgroundUrl && canEdit && !backgroundGenerationActive ? (
+ <Center className={styles.emptyBackgroundActions}>
+ <Flexbox align={'center'} gap={8}>
+ <Text className={styles.emptyBackgroundHint}>
+ {t('settingAgent.artwork.background.emptyHint')}
+ </Text>
+ <Flexbox horizontal gap={8}>
+ <Button
+ icon={UploadIcon}
+ loading={backgroundUploading}
+ size={'small'}
+ onClick={openBackgroundFilePicker}
+ >
+ {t('settingAgent.artwork.background.upload')}
+ </Button>
+ {canGenerate ? (
+ <Button
+ icon={WandSparkles}
+ loading={generating === 'background'}
+ size={'small'}
+ onClick={() => void generateArtwork('background')}
+ >
+ {t('settingAgent.artwork.background.generate')}
+ </Button>
+ ) : null}
+ </Flexbox>
+ </Flexbox>
+ </Center>
+ ) : null}
+ {canEdit && !backgroundGenerationActive ? (
+ <Flexbox
+ horizontal
+ className={styles.backgroundActions}
+ gap={4}
+ style={{ display: backgroundUrl ? undefined : 'none' }}
+ >
+ <Tooltip title={t('settingAgent.artwork.background.upload')}>
+ <ActionIcon
+ glass
+ icon={UploadIcon}
+ loading={backgroundUploading}
+ onClick={openBackgroundFilePicker}
+ />
+ </Tooltip>
+ {canGenerate ? (
+ <Tooltip title={t('settingAgent.artwork.background.generate')}>
+ <ActionIcon
+ glass
+ icon={WandSparkles}
+ loading={generating === 'background'}
+ onClick={() => void generateArtwork('background')}
+ />
+ </Tooltip>
+ ) : null}
+ {backgroundUrl ? (
+ <Tooltip title={t('settingAgent.artwork.background.remove')}>
+ <ActionIcon glass icon={Trash2} onClick={() => onBackgroundChange(null)} />
+ </Tooltip>
+ ) : null}
+ </Flexbox>
+ ) : null}
+ </div>
+ <div className={styles.avatar}>
+ <EmojiPicker
+ allowModelAvatar
+ allowDelete={canEdit && !!avatar}
+ allowUpload={canEdit}
+ loading={avatarUploading}
+ locale={locale}
+ open={canEdit ? undefined : false}
+ popupClassName={`${styles.avatarPicker} agent-avatar-artwork-picker`}
+ popupProps={{ placement: 'bottomLeft' }}
+ shape={'square'}
+ size={72}
+ value={avatar || undefined}
+ customTabs={
+ canGenerate
+ ? [
+ {
+ label: (
+ <Tooltip title={t('settingAgent.artwork.avatar.image')}>
+ <Icon icon={ImageIcon} size={{ size: 20, strokeWidth: 2.5 }} />
+ </Tooltip>
+ ),
+ render: () => (
+ <Flexbox gap={16} padding={20} width={348}>
+ <Center className={styles.generatedPreview} height={156}>
+ <Avatar avatar={avatar || undefined} shape={'square'} size={112} />
+ {generating === 'avatar' ? (
+ <Center
+ className={`${styles.generationFeedback} ${styles.previewGenerationFeedback}`}
+ >
+ <Flexbox align={'center'} gap={10}>
+ <NeuralNetworkLoading size={32} />
+ <Flexbox align={'center'} gap={4}>
+ <Text className={styles.generationTitle}>
+ {t('settingAgent.artwork.avatar.generating')}
+ </Text>
+ <Text className={styles.generationHint}>
+ {t('settingAgent.artwork.generatingHint')}
+ </Text>
+ <Button
+ className={styles.generationActions}
+ size={'small'}
+ type={'fill'}
+ onClick={() => void cancelAgentArtworkGeneration(agentId)}
+ >
+ {t('settingAgent.artwork.cancel')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ </Center>
+ ) : null}
+ </Center>
+ {generating !== 'avatar' ? (
+ <Button
+ className={styles.generatedAction}
+ icon={WandSparkles}
+ onClick={() => void generateArtwork('avatar')}
+ >
+ {t('settingAgent.artwork.avatar.generateAction')}
+ </Button>
+ ) : null}
+ {generationError === 'avatar' ? (
+ <Alert
+ showIcon
+ title={t('settingAgent.artwork.generateFailed')}
+ type={'error'}
+ />
+ ) : null}
+ </Flexbox>
+ ),
+ value: 'generate',
+ },
+ ]
+ : undefined
+ }
+ onChange={(value) => onAvatarChange(value)}
+ onDelete={() => onAvatarChange(null)}
+ onUpload={(file) => upload('avatar', file)}
+ onOpenChange={(open) => {
+ if (!open || !canGenerate) return;
+
+ requestAnimationFrame(() => {
+ const tabs = document.querySelectorAll('.agent-avatar-artwork-picker [role="tab"]');
+ (tabs.item(tabs.length - 1) as HTMLElement | null)?.click();
+ });
+ }}
+ />
+ {generating === 'avatar' ? (
+ <Center className={styles.avatarGenerating}>
+ <NeuralNetworkLoading size={28} />
+ </Center>
+ ) : null}
+ </div>
+ <input
+ accept="image/*"
+ aria-label={t('settingAgent.artwork.background.upload')}
+ className={styles.visuallyHiddenInput}
+ id={backgroundInputId}
+ ref={backgroundInputRef}
+ tabIndex={-1}
+ type="file"
+ onChange={(event) => {
+ const file = event.target.files?.[0];
+ event.target.value = '';
+ if (file) void upload('background', file);
+ }}
+ />
+ </div>
+ );
+ },
+);
+
+AgentProfileArtwork.displayName = 'AgentProfileArtwork';
+
+export { resolveAgentBackground } from './utils';
diff --git a/src/features/AgentProfileArtwork/utils.test.ts b/src/features/AgentProfileArtwork/utils.test.ts
new file mode 100644
index 00000000000..d10af8ba9b0
--- /dev/null
+++ b/src/features/AgentProfileArtwork/utils.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { selectAgentArtworkModel } from '@/store/agent/slices/artwork/utils';
+import type { EnabledProviderWithModels } from '@/types/aiProvider';
+
+import { openFilePicker, resolveAgentBackground } from './utils';
+
+describe('openFilePicker', () => {
+ it('uses the native picker while preserving click as a compatibility fallback', () => {
+ const input = document.createElement('input');
+ const click = vi.spyOn(input, 'click').mockImplementation(() => {});
+ const showPicker = vi.fn();
+ input.showPicker = showPicker;
+
+ openFilePicker(input);
+
+ expect(showPicker).toHaveBeenCalledOnce();
+ expect(click).not.toHaveBeenCalled();
+
+ showPicker.mockImplementation(() => {
+ throw new Error('showPicker is unavailable');
+ });
+ openFilePicker(input);
+
+ expect(click).toHaveBeenCalledOnce();
+ });
+});
+
+const createProvider = (id: string, modelIds: string[]): EnabledProviderWithModels => ({
+ children: modelIds.map((modelId) => ({ abilities: {}, id: modelId })),
+ id,
+ name: id,
+ source: 'builtin',
+});
+
+describe('resolveAgentBackground', () => {
+ it.each(['#fff', 'rgb(0, 0, 0)', 'transparent', 'red', 'rgba(0,0,0,0)'])(
+ 'ignores the legacy color value %s',
+ (value) => {
+ expect(resolveAgentBackground(value)).toBeUndefined();
+ },
+ );
+
+ it.each([
+ 'https://example.com/cover.webp',
+ 'http://example.com/cover.png',
+ '/f/file-id',
+ 'data:image/png;base64,abc',
+ ])('keeps the image source %s', (value) => {
+ expect(resolveAgentBackground(value)).toBe(value);
+ });
+});
+
+describe('selectAgentArtworkModel', () => {
+ it('prefers gpt-image-2 when another provider appears first', () => {
+ const selection = selectAgentArtworkModel([
+ createProvider('google', ['imagen-4']),
+ createProvider('openai', ['gpt-image-2']),
+ ]);
+
+ expect(selection?.provider.id).toBe('openai');
+ expect(selection?.model.id).toBe('gpt-image-2');
+ });
+
+ it('falls back to the first available image model', () => {
+ expect(selectAgentArtworkModel([createProvider('fal', ['flux'])])?.model.id).toBe('flux');
+ });
+});
diff --git a/src/features/AgentProfileArtwork/utils.ts b/src/features/AgentProfileArtwork/utils.ts
new file mode 100644
index 00000000000..6cf0dc98941
--- /dev/null
+++ b/src/features/AgentProfileArtwork/utils.ts
@@ -0,0 +1,20 @@
+const IMAGE_SOURCE_PATTERN = /^(?:https?:\/\/|\/|data:image\/)/i;
+
+export const openFilePicker = (input: HTMLInputElement): void => {
+ try {
+ input.showPicker();
+ } catch {
+ input.click();
+ }
+};
+
+/**
+ * Agent `backgroundColor` historically stored CSS colors. It now stores the
+ * profile cover image without requiring a database migration. Only image-like
+ * sources are accepted, so legacy colors quietly resolve to no cover.
+ */
+export const resolveAgentBackground = (value?: string | null): string | undefined => {
+ const source = value?.trim();
+
+ return source && IMAGE_SOURCE_PATTERN.test(source) ? source : undefined;
+};
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsx
index d6cbe357f06..7453fb2143a 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsx
@@ -24,6 +24,7 @@ const mocks = vi.hoisted(() => {
},
agentStoreListeners: new Set<() => void>(),
actionIconProps: { all: [] as Record<string, unknown>[] },
+ artworkProps: { last: undefined as Record<string, unknown> | undefined },
createAgentIdentityModal: vi.fn(),
refreshAgentConfig: vi.fn(),
emojiPickerProps: { last: undefined as Record<string, unknown> | undefined },
@@ -85,15 +86,11 @@ vi.mock('antd', () => ({
message: { error: vi.fn() },
}));
-vi.mock('@/components/EmojiPicker', () => ({
- default: vi.fn((props: Record<string, unknown>) => {
- mocks.emojiPickerProps.last = props;
- return <button type="button">avatar</button>;
- }),
-}));
-
-vi.mock('@/features/AgentSetting/AgentMeta/BackgroundSwatches', () => ({
- default: () => <div />,
+vi.mock('@/features/AgentProfileArtwork', () => ({
+ AgentProfileArtwork: (props: Record<string, unknown>) => {
+ mocks.artworkProps.last = props;
+ return <div>artwork</div>;
+ },
}));
vi.mock('@/hooks/usePermission', () => ({
@@ -124,6 +121,8 @@ vi.mock('@/store/agent/selectors', () => ({
agentSelectors: {
getAgentMetaById: (agentId: string) => (state: typeof mocks.agentStoreState) =>
state.agentMap[agentId] || {},
+ getAgentConfigById: (agentId: string) => (state: typeof mocks.agentStoreState) =>
+ state.agentMap[agentId] || {},
getAgentSlugById: (agentId: string) => (state: typeof mocks.agentStoreState) =>
state.agentMap[agentId]?.slug,
},
@@ -185,6 +184,7 @@ describe('AgentHeader', () => {
mocks.emojiPickerProps.last = undefined;
mocks.inputProps.all = [];
mocks.actionIconProps.all = [];
+ mocks.artworkProps.last = undefined;
mocks.permissionState.allowed = false;
mocks.randomAgentName.mockReturnValue('Zoe');
mocks.sidebarAgents = [];
@@ -194,10 +194,10 @@ describe('AgentHeader', () => {
vi.useRealTimers();
});
- it('keeps the emoji picker closed when edits are not allowed', () => {
+ it('keeps the artwork editor read-only when edits are not allowed', () => {
render(<AgentHeader />);
- expect(mocks.emojiPickerProps.last?.open).toBe(false);
+ expect(mocks.artworkProps.last?.canEdit).toBe(false);
});
it('opens the identity form instead of editing inline', () => {
@@ -333,31 +333,22 @@ describe('AgentHeader', () => {
expect(view.container.textContent).not.toContain('settingAgent.personalName.pickForMe');
});
- it('keeps an asynchronous avatar upload bound to the agent that started it', async () => {
+ it('keeps an artwork update bound to the agent that started it', () => {
mocks.permissionState.allowed = true;
mocks.agentStoreState.agentMap = {
'agent-a': { title: 'Agent A' },
'agent-b': { title: 'Agent B' },
};
- let resolveUpload: ((result: { url: string }) => void) | undefined;
- mocks.uploadWithProgress.mockImplementation(
- () =>
- new Promise<{ url: string }>((resolve) => {
- resolveUpload = resolve;
- }),
- );
render(<AgentHeader />);
- const upload = mocks.emojiPickerProps.last?.onUpload as (file: File) => Promise<void>;
- const uploadPromise = upload(new File(['avatar'], 'avatar.png', { type: 'image/png' }));
+ const onAvatarChange = mocks.artworkProps.last?.onAvatarChange as (avatar: string) => void;
act(() => {
mocks.agentStoreState.activeAgentId = 'agent-b';
mocks.agentStoreListeners.forEach((listener) => listener());
});
- await act(async () => {
- resolveUpload?.({ url: 'https://example.com/agent-a.png' });
- await uploadPromise;
+ act(() => {
+ onAvatarChange('https://example.com/agent-a.png');
});
expect(mocks.updateAgentMetaById).toHaveBeenCalledExactlyOnceWith('agent-a', {
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.tsx
index e8ab5a1a1c5..b8275b46014 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.tsx
@@ -1,27 +1,23 @@
'use client';
-import { ActionIcon, Flexbox, Icon, Skeleton, Text, Tooltip } from '@lobehub/ui';
-import { Button, toast } from '@lobehub/ui/base-ui';
+import { ActionIcon, Flexbox, Text, Tooltip } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
import { cssVar } from 'antd-style';
import isEqual from 'fast-deep-equal';
-import { PaletteIcon, PencilIcon, SparklesIcon } from 'lucide-react';
-import { memo, Suspense, useCallback, useState } from 'react';
+import { PencilIcon, SparklesIcon } from 'lucide-react';
+import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import EmojiPicker from '@/components/EmojiPicker';
import { createAgentIdentityModal } from '@/features/AgentIdentityModal';
-import BackgroundSwatches from '@/features/AgentSetting/AgentMeta/BackgroundSwatches';
+import { AgentProfileArtwork } from '@/features/AgentProfileArtwork';
import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
-import { useFileStore } from '@/store/file';
import { useGlobalStore } from '@/store/global';
import { globalGeneralSelectors } from '@/store/global/selectors';
import { useAutoName } from './useAutoName';
-const MAX_AVATAR_SIZE = 1024 * 1024; // 1MB limit for server actions
-
const AgentHeader = memo(() => {
const { t } = useTranslation(['setting', 'common']);
const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);
@@ -29,6 +25,7 @@ const AgentHeader = memo(() => {
const agentId = useAgentStore((s) => s.activeAgentId || '');
const meta = useAgentStore(agentSelectors.getAgentMetaById(agentId), isEqual);
+ const config = useAgentStore(agentSelectors.getAgentConfigById(agentId), isEqual);
const slug = useAgentStore(agentSelectors.getAgentSlugById(agentId));
const updateMetaById = useAgentStore((s) => s.updateAgentMetaById);
const { autoName, naming } = useAutoName(agentId);
@@ -36,126 +33,41 @@ const AgentHeader = memo(() => {
// falls back to the plain label rather than showing an action nobody can take.
const showNamePrompt = !meta.name?.trim() && canEdit;
- // File upload
- const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);
- const [uploading, setUploading] = useState(false);
-
- // Handle avatar change (immediate save)
- const handleAvatarChange = (emoji: string) => {
- if (!canEdit) return;
-
- updateMetaById(agentId, { avatar: emoji });
- };
-
- // Handle avatar upload
- const handleAvatarUpload = useCallback(
- async (file: File) => {
- if (!canEdit) return;
-
- if (file.size > MAX_AVATAR_SIZE) {
- toast.error(t('settingAgent.avatar.sizeExceeded', { ns: 'setting' }));
- return;
- }
-
- setUploading(true);
- try {
- const result = await uploadWithProgress({ file });
- if (result?.url) {
- updateMetaById(agentId, { avatar: result.url });
- }
- } finally {
- setUploading(false);
- }
- },
- [agentId, canEdit, uploadWithProgress, updateMetaById, t],
- );
-
- // Handle avatar delete
- const handleAvatarDelete = useCallback(() => {
- if (!canEdit) return;
-
- updateMetaById(agentId, { avatar: null });
- }, [agentId, canEdit, updateMetaById]);
-
- // Handle background color change (immediate save)
- const handleBackgroundColorChange = (color?: string) => {
- if (!canEdit) return;
-
- if (color !== undefined) {
- updateMetaById(agentId, { backgroundColor: color });
- }
- };
-
return (
<Flexbox
gap={16}
- paddingBlock={16}
+ paddingBlock={'16px 0'}
style={{
cursor: 'default',
+ marginInline: -16,
+ width: 'calc(100% + 32px)',
}}
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
}}
>
- {/* Avatar Section */}
- <EmojiPicker
- allowModelAvatar
- allowDelete={canEdit && !!meta.avatar}
- allowUpload={canEdit}
- loading={uploading}
+ <AgentProfileArtwork
+ agentId={agentId}
+ avatar={meta.avatar}
+ background={meta.backgroundColor}
+ canEdit={canEdit}
+ description={meta.description}
locale={locale}
- open={canEdit ? undefined : false}
- shape={'square'}
- size={72}
- value={meta.avatar}
- background={
- meta.backgroundColor && meta.backgroundColor !== 'rgba(0,0,0,0)'
- ? meta.backgroundColor
- : undefined
- }
- customTabs={[
- {
- label: (
- <Tooltip title={t('settingAgent.backgroundColor.title', { ns: 'setting' })}>
- <Icon icon={PaletteIcon} size={{ size: 20, strokeWidth: 2.5 }} />
- </Tooltip>
- ),
- render: () => (
- <Flexbox padding={8} width={332}>
- <Suspense
- fallback={
- <Flexbox gap={8}>
- <Skeleton.Button block style={{ height: 38 }} />
- <Skeleton.Button block style={{ height: 38 }} />
- </Flexbox>
- }
- >
- <BackgroundSwatches
- disabled={!canEdit}
- gap={8}
- shape={'square'}
- size={38}
- value={meta.backgroundColor}
- onChange={handleBackgroundColorChange}
- />
- </Suspense>
- </Flexbox>
- ),
- value: 'background',
- },
- ]}
- popupProps={{
- placement: 'bottomLeft',
+ name={meta.name}
+ systemRole={config?.systemRole}
+ title={meta.title}
+ onAvatarChange={(avatar) => {
+ if (canEdit) void updateMetaById(agentId, { avatar });
+ }}
+ onBackgroundChange={(backgroundColor) => {
+ if (canEdit) void updateMetaById(agentId, { backgroundColor });
}}
- onChange={handleAvatarChange}
- onDelete={handleAvatarDelete}
- onUpload={handleAvatarUpload}
/>
{/* Identity Section — display only. Editing all three fields happens in a
form modal; inline inputs crowded the header and left no room for a
per-field label or error. */}
- <Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>
+ <Flexbox flex={1} gap={8} paddingInline={24} style={{ minWidth: 0 }}>
{/* The headline is the NAME slot. It does not borrow the role the way
list surfaces do — the role has its own line right below, and falling
back would print it twice (an agent titled "Lobe AI" read
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx
index ef8c6f07742..5a17a6b9625 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx
@@ -37,7 +37,7 @@ const styles = createStaticStyles(({ css }) => ({
container-type: inline-size;
`,
configPanel: css`
- padding: 16px;
+ padding: 24px;
border: 1px solid ${cssVar.colorBorderSecondary};
border-radius: ${cssVar.borderRadiusLG};
background: ${cssVar.colorFillQuaternary};
diff --git a/src/store/agent/initialState.ts b/src/store/agent/initialState.ts
index cc94c663793..c638e30068b 100644
--- a/src/store/agent/initialState.ts
+++ b/src/store/agent/initialState.ts
@@ -1,11 +1,13 @@
import { type AgentSliceState } from './slices/agent';
import { initialAgentSliceState } from './slices/agent';
+import { type AgentArtworkSliceState, initialAgentArtworkSliceState } from './slices/artwork';
import { type BuiltinAgentSliceState } from './slices/builtin';
import { initialBuiltinAgentSliceState } from './slices/builtin';
-export type AgentStoreState = AgentSliceState & BuiltinAgentSliceState;
+export type AgentStoreState = AgentArtworkSliceState & AgentSliceState & BuiltinAgentSliceState;
export const initialState: AgentStoreState = {
+ ...initialAgentArtworkSliceState,
...initialAgentSliceState,
...initialBuiltinAgentSliceState,
};
diff --git a/src/store/agent/selectors/agentByIdSelectors.test.ts b/src/store/agent/selectors/agentByIdSelectors.test.ts
index 8724de96b37..97888961143 100644
--- a/src/store/agent/selectors/agentByIdSelectors.test.ts
+++ b/src/store/agent/selectors/agentByIdSelectors.test.ts
@@ -3,6 +3,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';
import { type AgentStoreState } from '@/store/agent/initialState';
import { initialAgentSliceState } from '@/store/agent/slices/agent/initialState';
+import { initialAgentArtworkSliceState } from '@/store/agent/slices/artwork/initialState';
import { initialBuiltinAgentSliceState } from '@/store/agent/slices/builtin/initialState';
import { agentByIdSelectors } from './agentByIdSelectors';
@@ -14,6 +15,7 @@ vi.mock('@lobechat/const', async (importOriginal) => ({
}));
const createState = (overrides: Partial<AgentStoreState> = {}): AgentStoreState => ({
+ ...initialAgentArtworkSliceState,
...initialAgentSliceState,
...initialBuiltinAgentSliceState,
...overrides,
diff --git a/src/store/agent/selectors/builtinAgentSelectors.test.ts b/src/store/agent/selectors/builtinAgentSelectors.test.ts
index f79460ab76d..2bf837207c3 100644
--- a/src/store/agent/selectors/builtinAgentSelectors.test.ts
+++ b/src/store/agent/selectors/builtinAgentSelectors.test.ts
@@ -4,11 +4,13 @@ import { describe, expect, it } from 'vitest';
import { type AgentStoreState } from '@/store/agent/initialState';
import { initialAgentSliceState } from '@/store/agent/slices/agent/initialState';
+import { initialAgentArtworkSliceState } from '@/store/agent/slices/artwork/initialState';
import { initialBuiltinAgentSliceState } from '@/store/agent/slices/builtin';
import { builtinAgentSelectors } from './builtinAgentSelectors';
const createState = (overrides: Partial<AgentStoreState> = {}): AgentStoreState => ({
+ ...initialAgentArtworkSliceState,
...initialAgentSliceState,
...initialBuiltinAgentSliceState,
...overrides,
diff --git a/src/store/agent/selectors/chatConfigByIdSelectors.test.ts b/src/store/agent/selectors/chatConfigByIdSelectors.test.ts
index 4dffd194978..1c0a3d5eef1 100644
--- a/src/store/agent/selectors/chatConfigByIdSelectors.test.ts
+++ b/src/store/agent/selectors/chatConfigByIdSelectors.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from 'vitest';
import { type AgentStoreState } from '@/store/agent/initialState';
import { initialAgentSliceState } from '@/store/agent/slices/agent/initialState';
+import { initialAgentArtworkSliceState } from '@/store/agent/slices/artwork/initialState';
import { initialBuiltinAgentSliceState } from '@/store/agent/slices/builtin/initialState';
import { chatConfigByIdSelectors } from './chatConfigByIdSelectors';
@@ -16,6 +17,7 @@ vi.mock('@lobechat/model-runtime', () => ({
// isDesktop defaults to false in test environment (no __ELECTRON__)
const createState = (overrides: Partial<AgentStoreState> = {}): AgentStoreState => ({
+ ...initialAgentArtworkSliceState,
...initialAgentSliceState,
...initialBuiltinAgentSliceState,
...overrides,
diff --git a/src/store/agent/selectors/chatConfigSelectors.test.ts b/src/store/agent/selectors/chatConfigSelectors.test.ts
index 2ab7fedb13b..a7f05d6f46e 100644
--- a/src/store/agent/selectors/chatConfigSelectors.test.ts
+++ b/src/store/agent/selectors/chatConfigSelectors.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from 'vitest';
import { type AgentStoreState } from '@/store/agent/initialState';
import { initialAgentSliceState } from '@/store/agent/slices/agent/initialState';
+import { initialAgentArtworkSliceState } from '@/store/agent/slices/artwork/initialState';
import { initialBuiltinAgentSliceState } from '@/store/agent/slices/builtin/initialState';
import { agentChatConfigSelectors } from './chatConfigSelectors';
@@ -14,6 +15,7 @@ vi.mock('@lobechat/model-runtime', () => ({
}));
const createState = (overrides: Partial<AgentStoreState> = {}): AgentStoreState => ({
+ ...initialAgentArtworkSliceState,
...initialAgentSliceState,
...initialBuiltinAgentSliceState,
...overrides,
diff --git a/src/store/agent/selectors/index.ts b/src/store/agent/selectors/index.ts
index ade20abd39d..d01f3142ea2 100644
--- a/src/store/agent/selectors/index.ts
+++ b/src/store/agent/selectors/index.ts
@@ -1,3 +1,4 @@
+export { agentArtworkSelectors } from '../slices/artwork/selectors';
export * from './agentByIdSelectors';
export * from './builtinAgentSelectors';
export * from './chatConfigByIdSelectors';
diff --git a/src/store/agent/selectors/selectors.test.ts b/src/store/agent/selectors/selectors.test.ts
index 573c9c3f058..a5f12c4bc53 100644
--- a/src/store/agent/selectors/selectors.test.ts
+++ b/src/store/agent/selectors/selectors.test.ts
@@ -12,11 +12,13 @@ import { describe, expect, it } from 'vitest';
import { type AgentStoreState } from '@/store/agent/initialState';
import { initialAgentSliceState } from '@/store/agent/slices/agent/initialState';
+import { initialAgentArtworkSliceState } from '@/store/agent/slices/artwork/initialState';
import { initialBuiltinAgentSliceState } from '@/store/agent/slices/builtin';
import { agentSelectors, currentAgentConfig } from './selectors';
const createState = (overrides: Partial<AgentStoreState> = {}): AgentStoreState => ({
+ ...initialAgentArtworkSliceState,
...initialAgentSliceState,
...initialBuiltinAgentSliceState,
...overrides,
diff --git a/src/store/agent/slices/artwork/action.test.ts b/src/store/agent/slices/artwork/action.test.ts
new file mode 100644
index 00000000000..a86d1dd1d81
--- /dev/null
+++ b/src/store/agent/slices/artwork/action.test.ts
@@ -0,0 +1,193 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { generationService } from '@/services/generation';
+import { generationTopicService } from '@/services/generationTopic';
+import { imageService } from '@/services/image';
+import { getAiInfraStoreState } from '@/store/aiInfra';
+import { AsyncTaskStatus } from '@/types/asyncTask';
+
+import { useAgentStore } from '../../store';
+
+vi.mock('zustand/traditional');
+
+vi.mock('@/services/generation', () => ({
+ generationService: { deleteGeneration: vi.fn(), getGenerationStatus: vi.fn() },
+}));
+
+vi.mock('@/services/generationTopic', () => ({
+ generationTopicService: { createTopic: vi.fn() },
+}));
+
+vi.mock('@/services/image', () => ({
+ imageService: { createImage: vi.fn() },
+}));
+
+vi.mock('@/store/aiInfra', () => ({
+ getAiInfraStoreState: vi.fn(),
+}));
+
+const input = {
+ description: 'Writes and reviews TypeScript',
+ id: 'agent-a',
+ kind: 'avatar' as const,
+ name: 'Coco',
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ useAgentStore.setState({ agentArtworkGenerationMap: {} });
+ vi.mocked(getAiInfraStoreState).mockReturnValue({
+ enabledImageModelList: [
+ {
+ children: [{ abilities: {}, id: 'gpt-image-2' }],
+ id: 'openai',
+ name: 'OpenAI',
+ source: 'builtin',
+ },
+ ],
+ } as ReturnType<typeof getAiInfraStoreState>);
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('AgentArtworkAction', () => {
+ it('keeps a per-agent generating state until the image is saved', async () => {
+ let startGeneration: (value: string) => void = () => {};
+ vi.mocked(generationTopicService.createTopic).mockReturnValue(
+ new Promise((resolve) => {
+ startGeneration = resolve;
+ }),
+ );
+ vi.mocked(imageService.createImage).mockResolvedValue({
+ data: { generations: [{ asyncTaskId: 'task-1', id: 'generation-1' }] },
+ success: true,
+ } as never);
+ vi.mocked(generationService.getGenerationStatus).mockResolvedValue({
+ generation: { asset: { url: 'https://example.com/avatar.webp' } },
+ status: AsyncTaskStatus.Success,
+ } as never);
+ const updateAgentMetaById = vi.fn().mockResolvedValue(undefined);
+ useAgentStore.setState({ updateAgentMetaById });
+
+ const promise = useAgentStore.getState().generateAgentArtwork(input);
+
+ expect(useAgentStore.getState().agentArtworkGenerationMap?.['agent-a']).toEqual({
+ kind: 'avatar',
+ status: 'generating',
+ });
+
+ startGeneration('topic-1');
+ await promise;
+
+ expect(updateAgentMetaById).toHaveBeenCalledWith('agent-a', {
+ avatar: 'https://example.com/avatar.webp',
+ });
+ expect(useAgentStore.getState().agentArtworkGenerationMap?.['agent-a']).toBeUndefined();
+ });
+
+ it('passes the existing avatar as a reference image when generating a background', async () => {
+ vi.mocked(getAiInfraStoreState).mockReturnValue({
+ enabledImageModelList: [
+ {
+ children: [
+ {
+ abilities: {},
+ id: 'gpt-image-2',
+ parameters: { imageUrls: { default: [], maxCount: 1 }, prompt: { default: '' } },
+ },
+ ],
+ id: 'openai',
+ name: 'OpenAI',
+ source: 'builtin',
+ },
+ ],
+ } as unknown as ReturnType<typeof getAiInfraStoreState>);
+ vi.mocked(generationTopicService.createTopic).mockResolvedValue('topic-1');
+ vi.mocked(imageService.createImage).mockResolvedValue({
+ data: { generations: [{ asyncTaskId: 'task-1', id: 'generation-1' }] },
+ success: true,
+ } as never);
+ vi.mocked(generationService.getGenerationStatus).mockResolvedValue({
+ generation: { asset: { url: 'https://example.com/background.webp' } },
+ status: AsyncTaskStatus.Success,
+ } as never);
+ useAgentStore.setState({ updateAgentMetaById: vi.fn().mockResolvedValue(undefined) });
+
+ await useAgentStore.getState().generateAgentArtwork({
+ ...input,
+ kind: 'background',
+ referenceImageUrl: 'https://example.com/avatar.webp',
+ });
+
+ expect(imageService.createImage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ params: expect.objectContaining({
+ imageUrls: ['https://example.com/avatar.webp'],
+ prompt: expect.stringContaining('attached existing avatar as the visual source of truth'),
+ }),
+ }),
+ );
+ });
+
+ it('keeps a retryable error state when generation cannot start', async () => {
+ vi.mocked(generationTopicService.createTopic).mockResolvedValue('topic-1');
+ vi.mocked(imageService.createImage).mockResolvedValue({ success: false } as never);
+
+ await expect(useAgentStore.getState().generateAgentArtwork(input)).rejects.toThrow(
+ 'Image generation could not be started',
+ );
+
+ expect(useAgentStore.getState().agentArtworkGenerationMap?.['agent-a']).toEqual({
+ error: 'Image generation could not be started',
+ kind: 'avatar',
+ status: 'error',
+ });
+ });
+
+ it('cancels polling, deletes the generation, and clears the loading state', async () => {
+ vi.mocked(generationTopicService.createTopic).mockResolvedValue('topic-1');
+ vi.mocked(imageService.createImage).mockResolvedValue({
+ data: { generations: [{ asyncTaskId: 'task-1', id: 'generation-1' }] },
+ success: true,
+ } as never);
+ vi.mocked(generationService.getGenerationStatus).mockResolvedValue({
+ status: AsyncTaskStatus.Processing,
+ } as never);
+ const updateAgentMetaById = vi.fn().mockResolvedValue(undefined);
+ useAgentStore.setState({ updateAgentMetaById });
+
+ const promise = useAgentStore.getState().generateAgentArtwork(input);
+ await vi.waitFor(() => expect(generationService.getGenerationStatus).toHaveBeenCalled());
+ await useAgentStore.getState().cancelAgentArtworkGeneration('agent-a');
+ await promise;
+
+ expect(generationService.deleteGeneration).toHaveBeenCalledWith('generation-1');
+ expect(updateAgentMetaById).not.toHaveBeenCalled();
+ expect(useAgentStore.getState().agentArtworkGenerationMap?.['agent-a']).toBeUndefined();
+ });
+
+ it('deletes a generation that starts after cancellation was requested', async () => {
+ let finishCreateImage: (value: unknown) => void = () => {};
+ vi.mocked(generationTopicService.createTopic).mockResolvedValue('topic-1');
+ vi.mocked(imageService.createImage).mockReturnValue(
+ new Promise((resolve) => {
+ finishCreateImage = resolve;
+ }) as never,
+ );
+
+ const promise = useAgentStore.getState().generateAgentArtwork(input);
+ await vi.waitFor(() => expect(imageService.createImage).toHaveBeenCalled());
+ await useAgentStore.getState().cancelAgentArtworkGeneration('agent-a');
+ finishCreateImage({
+ data: { generations: [{ asyncTaskId: 'task-1', id: 'generation-1' }] },
+ success: true,
+ });
+ await promise;
+
+ expect(generationService.deleteGeneration).toHaveBeenCalledWith('generation-1');
+ expect(generationService.getGenerationStatus).not.toHaveBeenCalled();
+ expect(useAgentStore.getState().agentArtworkGenerationMap?.['agent-a']).toBeUndefined();
+ });
+});
diff --git a/src/store/agent/slices/artwork/action.ts b/src/store/agent/slices/artwork/action.ts
new file mode 100644
index 00000000000..265f639f626
--- /dev/null
+++ b/src/store/agent/slices/artwork/action.ts
@@ -0,0 +1,195 @@
+import type { AgentArtworkPromptInput } from '@lobechat/prompts';
+import { buildAgentArtworkPrompt } from '@lobechat/prompts';
+
+import { generationService } from '@/services/generation';
+import { generationTopicService } from '@/services/generationTopic';
+import { imageService } from '@/services/image';
+import { getAiInfraStoreState } from '@/store/aiInfra';
+import { aiProviderSelectors } from '@/store/aiInfra/selectors';
+import type { StoreSetter } from '@/store/types';
+import { AsyncTaskStatus } from '@/types/asyncTask';
+
+import type { AgentStore } from '../../store';
+import type { AgentArtworkGenerationState } from './initialState';
+import { selectAgentArtworkModel } from './utils';
+
+const POLL_INTERVAL = 1500;
+const POLL_LIMIT = 120;
+
+const wait = (duration: number, signal: AbortSignal) =>
+ new Promise<void>((resolve, reject) => {
+ const timeout = setTimeout(resolve, duration);
+ signal.addEventListener(
+ 'abort',
+ () => {
+ clearTimeout(timeout);
+ reject(signal.reason);
+ },
+ { once: true },
+ );
+ });
+
+interface AgentArtworkGenerationJob {
+ controller: AbortController;
+ generationId?: string;
+}
+
+type Setter = StoreSetter<AgentStore>;
+
+export const createAgentArtworkSlice = (set: Setter, get: () => AgentStore, _api?: unknown) =>
+ new AgentArtworkActionImpl(set, get, _api);
+
+export class AgentArtworkActionImpl {
+ readonly #generationJobs = new Map<string, AgentArtworkGenerationJob>();
+ readonly #get: () => AgentStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => AgentStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ #getGeneratedImageUrl = async (
+ generationId: string,
+ asyncTaskId: string,
+ signal: AbortSignal,
+ ) => {
+ for (let count = 0; count < POLL_LIMIT; count += 1) {
+ signal.throwIfAborted();
+ const result = await generationService.getGenerationStatus(generationId, asyncTaskId);
+
+ if (result.status === AsyncTaskStatus.Success) {
+ const asset = result.generation?.asset;
+ const url = asset?.url || asset?.thumbnailUrl || asset?.originalUrl;
+ if (!url) throw new Error('Generated image has no usable URL');
+
+ return url;
+ }
+
+ if (result.status === AsyncTaskStatus.Error) {
+ const body = result.error?.body;
+ const detail = typeof body === 'string' ? body : body?.detail;
+ throw new Error(detail || 'Image generation failed');
+ }
+
+ await wait(POLL_INTERVAL, signal);
+ }
+
+ throw new Error('Image generation timed out');
+ };
+
+ cancelAgentArtworkGeneration = async (agentId: string): Promise<void> => {
+ const job = this.#generationJobs.get(agentId);
+ if (!job) {
+ this.#setGenerationState(agentId, undefined);
+ return;
+ }
+
+ job.controller.abort(new DOMException('Agent artwork generation cancelled', 'AbortError'));
+ this.#setGenerationState(agentId, undefined);
+
+ if (job.generationId) await generationService.deleteGeneration(job.generationId);
+ };
+
+ #setGenerationState = (agentId: string, value: AgentArtworkGenerationState | undefined) => {
+ this.#set(
+ (state) => {
+ const agentArtworkGenerationMap = { ...state.agentArtworkGenerationMap };
+ if (value) agentArtworkGenerationMap[agentId] = value;
+ else delete agentArtworkGenerationMap[agentId];
+
+ return { agentArtworkGenerationMap };
+ },
+ false,
+ 'setAgentArtworkGenerationState',
+ );
+ };
+
+ generateAgentArtwork = async (input: AgentArtworkPromptInput): Promise<void> => {
+ if (this.#get().agentArtworkGenerationMap[input.id]?.status === 'generating') return;
+
+ const job: AgentArtworkGenerationJob = { controller: new AbortController() };
+ this.#generationJobs.set(input.id, job);
+ this.#setGenerationState(input.id, { kind: input.kind, status: 'generating' });
+
+ try {
+ const enabledImageModelList =
+ aiProviderSelectors.enabledImageModelList(getAiInfraStoreState());
+ const selection = selectAgentArtworkModel(enabledImageModelList);
+ if (!selection) throw new Error('No image generation model is available');
+
+ const { model, provider } = selection;
+ const referenceImageUrl = input.referenceImageUrl?.trim();
+ const supportsReferenceImage =
+ !!referenceImageUrl && !!model.parameters && 'imageUrls' in model.parameters;
+ const supportedSizes =
+ model.parameters && 'size' in model.parameters ? model.parameters.size?.enum : undefined;
+ const preferredSizes =
+ input.kind === 'avatar'
+ ? ['1024x1024', '2048x2048']
+ : ['2048x1152', '1536x1024', '3840x2160'];
+ const size = preferredSizes.find((item) => supportedSizes?.includes(item));
+ const generationTopicId = await generationTopicService.createTopic(
+ 'image',
+ 'private',
+ input.kind === 'avatar' ? 'Agent avatar' : 'Agent background',
+ );
+ const aspectRatio = input.kind === 'avatar' ? '1:1' : '16:9';
+ const params = {
+ ...(model.parameters && 'aspectRatio' in model.parameters ? { aspectRatio } : {}),
+ ...(supportsReferenceImage ? { imageUrls: [referenceImageUrl] } : {}),
+ ...(size ? { size } : {}),
+ prompt: buildAgentArtworkPrompt({
+ ...input,
+ referenceImageUrl: supportsReferenceImage ? referenceImageUrl : undefined,
+ }),
+ };
+ const result = await imageService.createImage({
+ generationTopicId,
+ imageNum: 1,
+ model: model.id,
+ params,
+ provider: provider.id,
+ });
+ const generation = result.data?.generations[0];
+ const generationId = generation?.id;
+ const asyncTaskId = generation?.asyncTaskId;
+
+ if (!result.success || !generationId || !asyncTaskId) {
+ throw new Error('Image generation could not be started');
+ }
+
+ job.generationId = generationId;
+ if (job.controller.signal.aborted) {
+ await generationService.deleteGeneration(generationId);
+ job.controller.signal.throwIfAborted();
+ }
+ const url = await this.#getGeneratedImageUrl(
+ generationId,
+ asyncTaskId,
+ job.controller.signal,
+ );
+ job.controller.signal.throwIfAborted();
+ await this.#get().updateAgentMetaById(
+ input.id,
+ input.kind === 'avatar' ? { avatar: url } : { backgroundColor: url },
+ );
+ this.#setGenerationState(input.id, undefined);
+ } catch (error) {
+ if (job.controller.signal.aborted) return;
+
+ console.error('Failed to generate agent artwork:', error);
+ this.#setGenerationState(input.id, {
+ error: error instanceof Error ? error.message : 'Image generation failed',
+ kind: input.kind,
+ status: 'error',
+ });
+ throw error;
+ } finally {
+ if (this.#generationJobs.get(input.id) === job) this.#generationJobs.delete(input.id);
+ }
+ };
+}
+
+export type AgentArtworkSliceAction = Pick<AgentArtworkActionImpl, keyof AgentArtworkActionImpl>;
diff --git a/src/store/agent/slices/artwork/index.ts b/src/store/agent/slices/artwork/index.ts
new file mode 100644
index 00000000000..3e0ed63d8ba
--- /dev/null
+++ b/src/store/agent/slices/artwork/index.ts
@@ -0,0 +1,7 @@
+export { type AgentArtworkSliceAction, createAgentArtworkSlice } from './action';
+export {
+ type AgentArtworkGenerationState,
+ type AgentArtworkSliceState,
+ initialAgentArtworkSliceState,
+} from './initialState';
+export { selectAgentArtworkModel } from './utils';
diff --git a/src/store/agent/slices/artwork/initialState.ts b/src/store/agent/slices/artwork/initialState.ts
new file mode 100644
index 00000000000..2aa60f1afea
--- /dev/null
+++ b/src/store/agent/slices/artwork/initialState.ts
@@ -0,0 +1,15 @@
+import type { AgentArtworkKind } from '@lobechat/prompts';
+
+export interface AgentArtworkGenerationState {
+ error?: string;
+ kind: AgentArtworkKind;
+ status: 'error' | 'generating';
+}
+
+export interface AgentArtworkSliceState {
+ agentArtworkGenerationMap: Record<string, AgentArtworkGenerationState>;
+}
+
+export const initialAgentArtworkSliceState: AgentArtworkSliceState = {
+ agentArtworkGenerationMap: {},
+};
diff --git a/src/store/agent/slices/artwork/selectors.ts b/src/store/agent/slices/artwork/selectors.ts
new file mode 100644
index 00000000000..dc15f930727
--- /dev/null
+++ b/src/store/agent/slices/artwork/selectors.ts
@@ -0,0 +1,8 @@
+import type { AgentStore } from '../../store';
+
+const generationByAgentId = (agentId: string) => (state: AgentStore) =>
+ state.agentArtworkGenerationMap[agentId];
+
+export const agentArtworkSelectors = {
+ generationByAgentId,
+};
diff --git a/src/store/agent/slices/artwork/utils.ts b/src/store/agent/slices/artwork/utils.ts
new file mode 100644
index 00000000000..f307eef9519
--- /dev/null
+++ b/src/store/agent/slices/artwork/utils.ts
@@ -0,0 +1,15 @@
+import type { EnabledProviderWithModels } from '@/types/aiProvider';
+
+const PREFERRED_ARTWORK_MODEL = 'gpt-image-2';
+
+export const selectAgentArtworkModel = (providers: EnabledProviderWithModels[]) => {
+ for (const provider of providers) {
+ const model = provider.children.find(({ id }) => id === PREFERRED_ARTWORK_MODEL);
+ if (model) return { model, provider };
+ }
+
+ const provider = providers[0];
+ const model = provider?.children[0];
+
+ return provider && model ? { model, provider } : undefined;
+};
diff --git a/src/store/agent/store.ts b/src/store/agent/store.ts
index aacf5d2259b..1ebee0c54c1 100644
--- a/src/store/agent/store.ts
+++ b/src/store/agent/store.ts
@@ -10,6 +10,7 @@ import { type AgentStoreState } from './initialState';
import { initialState } from './initialState';
import { type AgentSliceAction } from './slices/agent';
import { createAgentSlice } from './slices/agent';
+import { type AgentArtworkSliceAction, createAgentArtworkSlice } from './slices/artwork';
import { type BotSliceAction } from './slices/bot';
import { createBotSlice } from './slices/bot';
import { type BuiltinAgentSliceAction } from './slices/builtin';
@@ -23,6 +24,7 @@ import { createPluginSlice } from './slices/plugin';
export interface AgentStore
extends
+ AgentArtworkSliceAction,
AgentSliceAction,
BotSliceAction,
BuiltinAgentSliceAction,
@@ -32,6 +34,7 @@ export interface AgentStore
AgentStoreState {}
type AgentStoreAction = AgentSliceAction &
+ AgentArtworkSliceAction &
BotSliceAction &
BuiltinAgentSliceAction &
KnowledgeSliceAction &
@@ -47,6 +50,7 @@ const createStore: StateCreator<AgentStore, [['zustand/devtools', never]]> = (
) => ({
...initialState,
...flattenActions<AgentStoreAction>([
+ createAgentArtworkSlice(...parameters),
createAgentSlice(...parameters),
createBotSlice(...parameters),
createBuiltinAgentSlice(...parameters),
diff --git a/src/store/aiInfra/slices/aiProvider/__tests__/action.test.ts b/src/store/aiInfra/slices/aiProvider/__tests__/action.test.ts
index a7f6d588119..cc4ab468118 100644
--- a/src/store/aiInfra/slices/aiProvider/__tests__/action.test.ts
+++ b/src/store/aiInfra/slices/aiProvider/__tests__/action.test.ts
@@ -14,6 +14,9 @@ import {
resolveUserScopedBuiltinModelState,
} from '../action';
+vi.mock('@/store/user', () => ({ useUserStore: vi.fn() }));
+vi.mock('@/store/user/selectors', () => ({ authSelectors: { isLoaded: vi.fn() } }));
+
const createChatModel = (overrides: Partial<EnabledAiModel> = {}): EnabledAiModel => ({
abilities: overrides.abilities ?? { functionCall: true },
contextWindowTokens: overrides.contextWindowTokens ?? 8192,