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.

♻️ refactor(artwork): make the avatar studio reusable beyond Agents (#18123)

Arvin Xu91a6eed75462
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 489036fb75a..9664c7eac4d 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -224,6 +224,24 @@
"analytics.telemetry.desc": "Help us improve {{appName}} with anonymous usage data",
"analytics.telemetry.title": "Send Anonymous Usage Data",
"analytics.title": "Analytics",
+ "artworkStudio.cancel": "Cancel generation",
+ "artworkStudio.diyTitle": "Make your own",
+ "artworkStudio.enableModel": "Enable a model",
+ "artworkStudio.generate": "Generate avatar",
+ "artworkStudio.generateFailed": "Could not generate the image. Try again.",
+ "artworkStudio.generateTitle": "Generate with AI",
+ "artworkStudio.generatingHint": "This usually takes about 60 seconds. You can keep editing while it finishes.",
+ "artworkStudio.lobeStyle": "Lobe official style",
+ "artworkStudio.moreStyles": "More styles",
+ "artworkStudio.noModel": "Enable an image generation model to use one-click generation.",
+ "artworkStudio.recommended": "Recommended",
+ "artworkStudio.style.clay": "3D Clay",
+ "artworkStudio.style.geometric": "Flat Geometric",
+ "artworkStudio.style.lobe": "Soft 3D mascot with a bold color backdrop",
+ "artworkStudio.style.pixel": "Pixel Art",
+ "artworkStudio.style.sticker": "Sticker",
+ "artworkStudio.style.watercolor": "Watercolor",
+ "artworkStudio.upload": "Upload image",
"checking": "Checking...",
"checkingPermissions": "Checking permissions...",
"creds.actions.delete": "Delete",
@@ -715,25 +733,10 @@
"settingAgent.artwork.retry": "Try again",
"settingAgent.artwork.sizeExceeded": "Image must be smaller than 1 MB",
"settingAgent.artwork.studio.diyHint": "Upload your own image (under 1 MB), or click the avatar on the profile to pick an emoji.",
- "settingAgent.artwork.studio.diyTitle": "Make your own",
- "settingAgent.artwork.studio.enableModel": "Enable a model",
- "settingAgent.artwork.studio.generate": "Generate avatar",
"settingAgent.artwork.studio.generateHint": "Pick a style and we'll create an avatar from this Agent's profile.",
- "settingAgent.artwork.studio.generateTitle": "Generate with AI",
- "settingAgent.artwork.studio.lobeStyle": "Lobe official style",
- "settingAgent.artwork.studio.moreStyles": "More styles",
- "settingAgent.artwork.studio.noModel": "Enable an image generation model to use one-click generation.",
"settingAgent.artwork.studio.open": "Customize appearance",
"settingAgent.artwork.studio.openAction": "Open the avatar studio",
- "settingAgent.artwork.studio.recommended": "Recommended",
"settingAgent.artwork.studio.title": "Agent Appearance",
- "settingAgent.artwork.studio.upload": "Upload image",
- "settingAgent.artwork.style.clay": "3D Clay",
- "settingAgent.artwork.style.geometric": "Flat Geometric",
- "settingAgent.artwork.style.lobe": "Soft 3D mascot with a bold color backdrop",
- "settingAgent.artwork.style.pixel": "Pixel Art",
- "settingAgent.artwork.style.sticker": "Sticker",
- "settingAgent.artwork.style.watercolor": "Watercolor",
"settingAgent.artwork.styleMenu": "Generation style",
"settingAgent.artwork.uploadFailed": "Could not upload the image. Try again.",
"settingAgent.avatar.sizeExceeded": "Image size exceeds 1MB limit, please choose a smaller image",
@@ -2224,8 +2227,13 @@
"workspace.create.submit": "Create workspace",
"workspace.create.title": "Create a new workspace",
"workspace.description.title": "Description",
- "workspace.general.avatar.description": "This is your workspace's avatar. Click on the avatar to upload a custom one from your files.",
+ "workspace.general.avatar.description": "This is your workspace's avatar. Upload your own, or generate one in the Lobe official style.",
+ "workspace.general.avatar.generating": "Creating an avatar that matches this workspace…",
"workspace.general.avatar.hint": "An avatar is optional but strongly recommended.",
+ "workspace.general.avatar.studio.diyHint": "Upload your own image — square works best, under 5 MB.",
+ "workspace.general.avatar.studio.generateHint": "Pick a style and we'll create an avatar from this workspace's name and description.",
+ "workspace.general.avatar.studio.open": "Customize appearance",
+ "workspace.general.avatar.studio.title": "Workspace Appearance",
"workspace.general.avatar.title": "Workspace Avatar",
"workspace.general.avatar.tooLarge": "Avatar file must be smaller than 5MB.",
"workspace.general.avatar.uploadFailed": "Failed to upload avatar",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 3290af1dbd3..b01a8a6a6df 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -224,6 +224,24 @@
"analytics.telemetry.desc": "通过匿名使用数据帮助我们改进 {{appName}}",
"analytics.telemetry.title": "发送匿名使用数据",
"analytics.title": "数据统计",
+ "artworkStudio.cancel": "取消生成",
+ "artworkStudio.diyTitle": "自行制作",
+ "artworkStudio.enableModel": "去启用",
+ "artworkStudio.generate": "一键生成",
+ "artworkStudio.generateFailed": "暂时无法生成图片,请重试",
+ "artworkStudio.generateTitle": "AI 一键生成",
+ "artworkStudio.generatingHint": "通常需要约 60 秒,生成期间可以继续编辑其他内容",
+ "artworkStudio.lobeStyle": "Lobe 官方风格",
+ "artworkStudio.moreStyles": "更多风格",
+ "artworkStudio.noModel": "启用图像生成模型后即可一键生成",
+ "artworkStudio.recommended": "推荐",
+ "artworkStudio.style.clay": "3D 黏土",
+ "artworkStudio.style.geometric": "扁平几何",
+ "artworkStudio.style.lobe": "软 3D 吉祥物 · 大色块背景",
+ "artworkStudio.style.pixel": "像素风",
+ "artworkStudio.style.sticker": "贴纸插画",
+ "artworkStudio.style.watercolor": "水彩手绘",
+ "artworkStudio.upload": "上传图片",
"checking": "检查中…",
"checkingPermissions": "检查权限中…",
"creds.actions.delete": "删除",
@@ -715,25 +733,10 @@
"settingAgent.artwork.retry": "重试",
"settingAgent.artwork.sizeExceeded": "图片大小不能超过 1 MB",
"settingAgent.artwork.studio.diyHint": "上传一张自己的图片(1MB 以内),或在资料页头像中选择 Emoji",
- "settingAgent.artwork.studio.diyTitle": "自行制作",
- "settingAgent.artwork.studio.enableModel": "去启用",
- "settingAgent.artwork.studio.generate": "一键生成",
"settingAgent.artwork.studio.generateHint": "选择风格,我们会根据 Agent 的资料生成专属形象",
- "settingAgent.artwork.studio.generateTitle": "AI 一键生成",
- "settingAgent.artwork.studio.lobeStyle": "Lobe 官方风格",
- "settingAgent.artwork.studio.moreStyles": "更多风格",
- "settingAgent.artwork.studio.noModel": "启用图像生成模型后即可一键生成",
"settingAgent.artwork.studio.open": "自定义形象",
"settingAgent.artwork.studio.openAction": "打开形象工作室",
- "settingAgent.artwork.studio.recommended": "推荐",
"settingAgent.artwork.studio.title": "Agent 形象",
- "settingAgent.artwork.studio.upload": "上传图片",
- "settingAgent.artwork.style.clay": "3D 黏土",
- "settingAgent.artwork.style.geometric": "扁平几何",
- "settingAgent.artwork.style.lobe": "软 3D 吉祥物 · 大色块背景",
- "settingAgent.artwork.style.pixel": "像素风",
- "settingAgent.artwork.style.sticker": "贴纸插画",
- "settingAgent.artwork.style.watercolor": "水彩手绘",
"settingAgent.artwork.styleMenu": "生成风格",
"settingAgent.artwork.uploadFailed": "暂时无法上传图片,请重试",
"settingAgent.avatar.sizeExceeded": "图片大小超过 1MB 限制,请选择更小的图片",
@@ -2224,8 +2227,13 @@
"workspace.create.submit": "创建工作区",
"workspace.create.title": "创建新工作区",
"workspace.description.title": "描述",
- "workspace.general.avatar.description": "这是您的工作区头像。点击头像即可从本地文件上传自定义头像。",
+ "workspace.general.avatar.description": "这是您的工作区头像。可以上传自己的图片,也可以一键生成 Lobe 官方风格形象。",
+ "workspace.general.avatar.generating": "正在生成符合工作区气质的头像…",
"workspace.general.avatar.hint": "头像是可选的,但强烈推荐。",
+ "workspace.general.avatar.studio.diyHint": "上传一张自己的图片,建议正方形,5MB 以内",
+ "workspace.general.avatar.studio.generateHint": "选择风格,我们会根据工作区的名称和简介生成专属形象",
+ "workspace.general.avatar.studio.open": "自定义形象",
+ "workspace.general.avatar.studio.title": "工作区形象",
"workspace.general.avatar.title": "工作区头像",
"workspace.general.avatar.tooLarge": "头像文件必须小于 5MB。",
"workspace.general.avatar.uploadFailed": "上传头像失败",
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 53c42bd3803..cffcb1c7a15 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -71,6 +71,25 @@ export default {
'accountDeletion.workspaceBlocked.reasonPaid': 'Paid plan active',
'accountDeletion.workspaceBlocked.title': 'Transfer your workspaces first',
'advancedSettings': 'Advanced Settings',
+ 'artworkStudio.cancel': 'Cancel generation',
+ 'artworkStudio.diyTitle': 'Make your own',
+ 'artworkStudio.enableModel': 'Enable a model',
+ 'artworkStudio.generate': 'Generate avatar',
+ 'artworkStudio.generateFailed': 'Could not generate the image. Try again.',
+ 'artworkStudio.generateTitle': 'Generate with AI',
+ 'artworkStudio.generatingHint':
+ 'This usually takes about 60 seconds. You can keep editing while it finishes.',
+ 'artworkStudio.lobeStyle': 'Lobe official style',
+ 'artworkStudio.moreStyles': 'More styles',
+ 'artworkStudio.noModel': 'Enable an image generation model to use one-click generation.',
+ 'artworkStudio.recommended': 'Recommended',
+ 'artworkStudio.style.clay': '3D Clay',
+ 'artworkStudio.style.geometric': 'Flat Geometric',
+ 'artworkStudio.style.lobe': 'Soft 3D mascot with a bold color backdrop',
+ 'artworkStudio.style.pixel': 'Pixel Art',
+ 'artworkStudio.style.sticker': 'Sticker',
+ 'artworkStudio.style.watercolor': 'Watercolor',
+ 'artworkStudio.upload': 'Upload image',
'agentCronJobs.addJob': 'Add Scheduled Task',
'agentCronJobs.clearTopics': 'Clear Topics',
'agentCronJobs.clearTopicsFailed': 'Failed to clear topics',
@@ -793,27 +812,11 @@ export default {
'settingAgent.artwork.sizeExceeded': 'Image must be smaller than 1 MB',
'settingAgent.artwork.studio.diyHint':
'Upload your own image (under 1 MB), or click the avatar on the profile to pick an emoji.',
- 'settingAgent.artwork.studio.diyTitle': 'Make your own',
- 'settingAgent.artwork.studio.enableModel': 'Enable a model',
- 'settingAgent.artwork.studio.generate': 'Generate avatar',
'settingAgent.artwork.studio.generateHint':
"Pick a style and we'll create an avatar from this Agent's profile.",
- 'settingAgent.artwork.studio.generateTitle': 'Generate with AI',
- 'settingAgent.artwork.studio.lobeStyle': 'Lobe official style',
- 'settingAgent.artwork.studio.moreStyles': 'More styles',
- 'settingAgent.artwork.studio.noModel':
- 'Enable an image generation model to use one-click generation.',
'settingAgent.artwork.studio.open': 'Customize appearance',
'settingAgent.artwork.studio.openAction': 'Open the avatar studio',
- 'settingAgent.artwork.studio.recommended': 'Recommended',
'settingAgent.artwork.studio.title': 'Agent Appearance',
- 'settingAgent.artwork.studio.upload': 'Upload image',
- 'settingAgent.artwork.style.clay': '3D Clay',
- 'settingAgent.artwork.style.geometric': 'Flat Geometric',
- 'settingAgent.artwork.style.lobe': 'Soft 3D mascot with a bold color backdrop',
- 'settingAgent.artwork.style.pixel': 'Pixel Art',
- 'settingAgent.artwork.style.sticker': 'Sticker',
- 'settingAgent.artwork.style.watercolor': 'Watercolor',
'settingAgent.artwork.styleMenu': 'Generation style',
'settingAgent.artwork.uploadFailed': 'Could not upload the image. Try again.',
'settingAgent.backgroundColor.title': 'Background Color',
@@ -2356,8 +2359,15 @@ When I am ___, I need ___
'workspace.create.title': 'Create a new workspace',
'workspace.description.title': 'Description',
'workspace.general.avatar.description':
- "This is your workspace's avatar. Click on the avatar to upload a custom one from your files.",
+ "This is your workspace's avatar. Upload your own, or generate one in the Lobe official style.",
+ 'workspace.general.avatar.generating': 'Creating an avatar that matches this workspace…',
'workspace.general.avatar.hint': 'An avatar is optional but strongly recommended.',
+ 'workspace.general.avatar.studio.diyHint':
+ 'Upload your own image — square works best, under 5 MB.',
+ 'workspace.general.avatar.studio.generateHint':
+ "Pick a style and we'll create an avatar from this workspace's name and description.",
+ 'workspace.general.avatar.studio.open': 'Customize appearance',
+ 'workspace.general.avatar.studio.title': 'Workspace Appearance',
'workspace.general.avatar.title': 'Workspace Avatar',
'workspace.general.avatar.tooLarge': 'Avatar file must be smaller than 5MB.',
'workspace.general.avatar.uploadFailed': 'Failed to upload avatar',
diff --git a/packages/prompts/src/prompts/agentArtwork/index.test.ts b/packages/prompts/src/prompts/agentArtwork/index.test.ts
index e595e797c93..185e0b64794 100644
--- a/packages/prompts/src/prompts/agentArtwork/index.test.ts
+++ b/packages/prompts/src/prompts/agentArtwork/index.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'vitest';
-import { AGENT_ARTWORK_STYLES, buildAgentArtworkPrompt } from './index';
+import {
+ AGENT_ARTWORK_STYLES,
+ buildAgentArtworkPrompt,
+ buildWorkspaceArtworkPrompt,
+} from './index';
describe('buildAgentArtworkPrompt', () => {
it('injects escaped Agent identity and description into the avatar prompt', () => {
@@ -147,3 +151,53 @@ describe('buildAgentArtworkPrompt', () => {
expect(prompt).not.toContain('illustration style');
});
});
+
+describe('buildWorkspaceArtworkPrompt', () => {
+ it('injects escaped workspace identity and description', () => {
+ const prompt = buildWorkspaceArtworkPrompt({
+ description: 'Design & research for climate tooling',
+ id: 'ws-1',
+ name: 'Acme "Labs"',
+ });
+
+ expect(prompt).toContain('<workspace id="ws-1" name="Acme &quot;Labs&quot;">');
+ expect(prompt).toContain(
+ '<description>Design &amp; research for climate tooling</description>',
+ );
+ expect(prompt).toContain('square profile icon for the team workspace');
+ expect(prompt).toContain('full-bleed composition');
+ });
+
+ it('re-points the mascot direction from the agent to the team', () => {
+ const prompt = buildWorkspaceArtworkPrompt({ id: 'ws-1' });
+
+ expect(prompt).toContain('mascot-style 3D emoji character');
+ expect(prompt).toContain("the team's character");
+ expect(prompt).not.toContain("the agent's personality");
+ });
+
+ it('steers the motif toward the team instead of AI clichés', () => {
+ const prompt = buildWorkspaceArtworkPrompt({ id: 'ws-1' });
+
+ expect(prompt).toContain('Avoid generic AI and technology clichés');
+ expect(prompt).toContain('what this team actually works on');
+ });
+
+ it('asks style references to inspire a new character for the team', () => {
+ const prompt = buildWorkspaceArtworkPrompt({
+ id: 'ws-1',
+ styleReferenceImageUrls: ['https://example.com/ref-a.webp', 'https://example.com/ref-b.webp'],
+ });
+
+ expect(prompt).toContain('as the target character style');
+ expect(prompt).toContain('invent a new character for the team described above');
+ });
+
+ it('renders a distinct direction for every style preset', () => {
+ const prompts = AGENT_ARTWORK_STYLES.map((style) =>
+ buildWorkspaceArtworkPrompt({ id: 'ws-1', style }),
+ );
+
+ expect(new Set(prompts).size).toBe(AGENT_ARTWORK_STYLES.length);
+ });
+});
diff --git a/packages/prompts/src/prompts/agentArtwork/index.ts b/packages/prompts/src/prompts/agentArtwork/index.ts
index 2bdfc0dc573..a19fe705d89 100644
--- a/packages/prompts/src/prompts/agentArtwork/index.ts
+++ b/packages/prompts/src/prompts/agentArtwork/index.ts
@@ -53,6 +53,33 @@ const BACKGROUND_STYLE_OVERRIDES: Partial<Record<AgentArtworkStyle, string>> = {
*/
const MOTIF_DIRECTION = `Ground the imagery in the agent's specific domain and personality. Avoid generic AI and technology clichés — starry space scenes, glowing particles, circuit boards, neural-network lines, holographic grids — unless the agent's subject matter is explicitly about them.`;
+const AVATAR_CANVAS_DIRECTION = `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.`;
+
+/**
+ * `character` is for avatars, where the references define the TARGET subject
+ * feel (the official mascot look) — the wording asks for that same energy while
+ * fencing off the literal faces / hats / subjects, since copying those would
+ * make every avatar look like the same mascot. `surface` is for covers, which
+ * forbid portraits and may only borrow rendering qualities.
+ */
+const buildStyleReferenceDirection = (
+ count: number,
+ mode: 'character' | 'surface',
+ subject: string,
+): string => {
+ if (count === 0) return '';
+
+ const imageWord = count === 1 ? 'image' : 'images';
+ const possessive = count === 1 ? 'its' : 'their';
+
+ return mode === 'character'
+ ? `\n\nUse the attached ${imageWord} as the target character style — the same mascot-like head-dominant look, single-color skin, material, lighting, and color energy. Do not copy ${possessive} exact faces, hats, or subjects — invent a new character for the ${subject} described above.`
+ : `\n\nUse the attached ${imageWord} only as a rendering-style reference — match ${possessive} materials, lighting, color saturation, and level of finish. Do not copy ${possessive} subjects or compositions.`;
+};
+
+const countStyleReferences = (urls?: string[] | null): number =>
+ urls?.filter((url) => url.trim()).length ?? 0;
+
export interface AgentArtworkPromptInput {
description?: string | null;
id: string;
@@ -105,19 +132,12 @@ export const buildAgentArtworkPrompt = (input: AgentArtworkPromptInput): string
? (BACKGROUND_STYLE_OVERRIDES[style] ?? STYLE_DIRECTIONS[style])
: STYLE_DIRECTIONS[style];
- const styleReferenceCount =
- input.styleReferenceImageUrls?.filter((url) => url.trim()).length ?? 0;
- // For avatars the references define the TARGET character feel (the official
- // mascot look), so the wording asks for that same energy while fencing off
- // the literal faces / hats / subjects — copying those would make every agent
- // look like the same mascot. Covers must not inherit the character wording
- // (they forbid portraits), so they only borrow surface qualities.
- const styleReferenceDirection =
- styleReferenceCount > 0
- ? input.kind === 'avatar'
- ? `\n\nUse the attached ${styleReferenceCount === 1 ? 'image' : 'images'} as the target character style — the same mascot-like head-dominant look, single-color skin, material, lighting, and color energy. Do not copy ${styleReferenceCount === 1 ? 'its' : 'their'} exact faces, hats, or subjects — invent a new character for the agent described above.`
- : `\n\nUse the attached ${styleReferenceCount === 1 ? 'image' : 'images'} only as a rendering-style reference — match ${styleReferenceCount === 1 ? 'its' : 'their'} materials, lighting, color saturation, and level of finish. Do not copy ${styleReferenceCount === 1 ? 'its' : 'their'} subjects or compositions.`
- : '';
+ const styleReferenceCount = countStyleReferences(input.styleReferenceImageUrls);
+ const styleReferenceDirection = buildStyleReferenceDirection(
+ styleReferenceCount,
+ input.kind === 'avatar' ? 'character' : 'surface',
+ 'agent',
+ );
const counterpartReferenceUrl = styleReferenceCount > 0 ? undefined : input.referenceImageUrl;
if (input.kind === 'avatar') {
@@ -132,7 +152,7 @@ export const buildAgentArtworkPrompt = (input: AgentArtworkPromptInput): string
${agentContext}
-Translate the agent's identity, purpose, and personality into one coherent visual concept. Use a single centered subject with a simple silhouette. ${styleDirection} ${MOTIF_DIRECTION} 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.${styleReferenceDirection}${referenceDirection}`;
+Translate the agent's identity, purpose, and personality into one coherent visual concept. Use a single centered subject with a simple silhouette. ${styleDirection} ${MOTIF_DIRECTION} ${AVATAR_CANVAS_DIRECTION}${styleReferenceDirection}${referenceDirection}`;
}
const referenceDirection = counterpartReferenceUrl?.trim()
@@ -145,3 +165,65 @@ ${agentContext}
Translate the agent's identity, purpose, and personality into an abstract environment. ${styleDirection} ${MOTIF_DIRECTION} Use generous negative space and a balanced composition. Do not use a person portrait, words, letters, a logo, or a border.${styleReferenceDirection}${referenceDirection}`;
};
+
+/**
+ * A workspace is a team rather than a character, so the mascot direction's
+ * "the agent's personality" phrasing has to be re-pointed at the team. Only the
+ * presets whose wording names the agent need an override.
+ */
+const WORKSPACE_STYLE_OVERRIDES: Partial<Record<AgentArtworkStyle, string>> = {
+ lobe: STYLE_DIRECTIONS.lobe.replace("the agent's personality", "the team's character"),
+};
+
+const WORKSPACE_MOTIF_DIRECTION = `Ground the imagery in what this team actually works on. Avoid generic AI and technology clichés — starry space scenes, glowing particles, circuit boards, neural-network lines, holographic grids — unless the team's work is explicitly about them.`;
+
+export interface WorkspaceArtworkPromptInput {
+ description?: string | null;
+ id: string;
+ name?: string | null;
+ style?: AgentArtworkStyle | null;
+ /** See {@link AgentArtworkPromptInput.styleReferenceImageUrls}. */
+ styleReferenceImageUrls?: string[] | null;
+}
+
+const formatWorkspaceContext = ({
+ description,
+ id,
+ name,
+}: Omit<WorkspaceArtworkPromptInput, 'style' | 'styleReferenceImageUrls'>): string => {
+ const attributes = [`id="${escapeXmlAttr(id)}"`];
+
+ if (name?.trim()) attributes.push(`name="${escapeXmlAttr(name.trim())}"`);
+
+ const details = description?.trim()
+ ? `<description>${escapeXmlContent(description.trim())}</description>`
+ : '';
+
+ return `<workspace ${attributes.join(' ')}>${details}</workspace>`;
+};
+
+/**
+ * Square brand avatar for a team workspace. Workspaces have no cover artwork
+ * and no system role, so this is deliberately avatar-only and much narrower
+ * than {@link buildAgentArtworkPrompt}.
+ */
+export const buildWorkspaceArtworkPrompt = (input: WorkspaceArtworkPromptInput): string => {
+ const workspaceContext = formatWorkspaceContext({
+ description: input.description,
+ id: input.id,
+ name: input.name,
+ });
+ const style = input.style ?? DEFAULT_AGENT_ARTWORK_STYLE;
+ const styleDirection = WORKSPACE_STYLE_OVERRIDES[style] ?? STYLE_DIRECTIONS[style];
+ const styleReferenceDirection = buildStyleReferenceDirection(
+ countStyleReferences(input.styleReferenceImageUrls),
+ 'character',
+ 'team',
+ );
+
+ return `Create a distinctive square profile icon for the team workspace described below.
+
+${workspaceContext}
+
+Translate the team's name, focus, and character into one coherent visual concept. Use a single centered subject with a simple silhouette. ${styleDirection} ${WORKSPACE_MOTIF_DIRECTION} ${AVATAR_CANVAS_DIRECTION}${styleReferenceDirection}`;
+};
diff --git a/src/features/AgentArtworkStudio/Content.tsx b/src/features/AgentArtworkStudio/Content.tsx
index 7e652703b3d..84a021c8aeb 100644
--- a/src/features/AgentArtworkStudio/Content.tsx
+++ b/src/features/AgentArtworkStudio/Content.tsx
@@ -1,158 +1,24 @@
'use client';
-import { imageUrl } from '@lobechat/const';
-import {
- AGENT_ARTWORK_STYLES,
- type AgentArtworkStyle,
- DEFAULT_AGENT_ARTWORK_STYLE,
-} from '@lobechat/prompts';
-import { Avatar, Center, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
-import { Alert, Button, toast, useModalContext } from '@lobehub/ui/base-ui';
-import { createStaticStyles, cssVar } from 'antd-style';
-import { Check, SettingsIcon, UploadIcon, WandSparkles } from 'lucide-react';
-import { memo, useCallback, useRef, useState } from 'react';
+import type { AgentArtworkStyle } from '@lobechat/prompts';
+import { toast } from '@lobehub/ui/base-ui';
+import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
-import {
- avatarRemountKey,
- openFilePicker,
- resolveAgentBackground,
-} from '@/features/AgentProfileArtwork/utils';
-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { resolveAgentBackground } from '@/features/AgentProfileArtwork/utils';
+import { ArtworkStudioContent, styleReferencesForArtworkStyle } from '@/features/ArtworkStudio';
import { useAgentStore } from '@/store/agent';
import { agentArtworkSelectors, agentSelectors } from '@/store/agent/selectors';
-import { useAiInfraStore } from '@/store/aiInfra';
-import { aiProviderSelectors } from '@/store/aiInfra/selectors';
import { useFileStore } from '@/store/file';
-import {
- LOBE_STYLE_REFERENCE_IMAGE_URLS,
- styleReferencesForArtworkStyle,
-} from './lobeStyleReferences';
-
const MAX_AVATAR_SIZE = 1024 * 1024;
-const GALLERY_STYLES = AGENT_ARTWORK_STYLES.filter((item) => item !== 'lobe');
-
-const styles = createStaticStyles(({ css }) => ({
- galleryCheck: css`
- position: absolute;
- z-index: 1;
- inset-block-start: 6px;
- inset-inline-end: 6px;
-
- width: 20px;
- height: 20px;
- border-radius: 50%;
-
- color: ${cssVar.colorTextLightSolid};
-
- background: ${cssVar.colorPrimary};
- `,
- galleryGrid: css`
- display: grid;
-
- /* One row of five, per review: the set is curated to exactly five styles. */
- grid-template-columns: repeat(5, 1fr);
- gap: 8px;
- `,
- galleryItem: css`
- cursor: pointer;
- border-radius: ${cssVar.borderRadiusLG};
-
- &:hover img {
- filter: brightness(1.06);
- }
- `,
- galleryLabel: css`
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- text-align: center;
- `,
- galleryThumb: css`
- aspect-ratio: 1;
- width: 100%;
- border-radius: ${cssVar.borderRadiusLG};
-
- object-fit: cover;
-
- transition: filter ${cssVar.motionDurationFast};
- `,
- galleryThumbWrap: css`
- position: relative;
- `,
- generationOverlay: css`
- position: absolute;
- z-index: 2;
- inset: 0;
-
- border-radius: calc(${cssVar.borderRadiusLG} - 1px);
-
- background: color-mix(in srgb, ${cssVar.colorBgContainer} 88%, transparent);
- backdrop-filter: blur(12px);
- `,
- hint: css`
- font-size: 13px;
- color: ${cssVar.colorTextSecondary};
- `,
- lobeCard: css`
- cursor: pointer;
- border-radius: ${cssVar.borderRadiusLG};
- background: ${cssVar.colorFillQuaternary};
- transition: background ${cssVar.motionDurationFast};
-
- &:hover {
- background: ${cssVar.colorFillTertiary};
- }
- `,
- lobeCardActive: css`
- background: ${cssVar.colorFillSecondary};
-
- &:hover {
- background: ${cssVar.colorFillSecondary};
- }
- `,
- noModelBlock: css`
- border-radius: ${cssVar.borderRadiusLG};
- background: ${cssVar.colorFillQuaternary};
- `,
- preview: css`
- position: relative;
-
- overflow: hidden;
- flex: none;
-
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadiusLG};
-
- background: ${cssVar.colorFillQuaternary};
- `,
- sectionTitle: css`
- font-weight: 500;
- `,
- visuallyHiddenInput: css`
- pointer-events: none;
-
- position: fixed;
-
- overflow: hidden;
-
- width: 1px;
- height: 1px;
-
- opacity: 0;
- `,
-}));
-
interface AgentArtworkStudioContentProps {
agentId: string;
}
const AgentArtworkStudioContent = memo<AgentArtworkStudioContentProps>(({ agentId }) => {
const { t } = useTranslation('setting');
- const { close } = useModalContext();
- const navigate = useWorkspaceAwareNavigate();
const meta = useAgentStore(agentSelectors.getAgentMetaById(agentId));
const systemRole = useAgentStore(
(s) => agentSelectors.getAgentConfigById(agentId)(s)?.systemRole,
@@ -162,16 +28,11 @@ const AgentArtworkStudioContent = memo<AgentArtworkStudioContentProps>(({ agentI
const cancelAgentArtworkGeneration = useAgentStore((s) => s.cancelAgentArtworkGeneration);
const updateAgentMetaById = useAgentStore((s) => s.updateAgentMetaById);
const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);
- const canGenerate = useAiInfraStore(
- (state) => aiProviderSelectors.enabledImageModelList(state).length > 0,
- );
- const uploadInputRef = useRef<HTMLInputElement>(null);
const [uploading, setUploading] = useState(false);
- const [style, setStyle] = useState<AgentArtworkStyle>(DEFAULT_AGENT_ARTWORK_STYLE);
const generating = generation?.status === 'generating' && generation.kind === 'avatar';
- const generationError = generation?.status === 'error' && generation.kind === 'avatar';
+ const generationFailed = generation?.status === 'error' && generation.kind === 'avatar';
const generate = useCallback(
(nextStyle: AgentArtworkStyle) => {
@@ -222,199 +83,19 @@ const AgentArtworkStudioContent = memo<AgentArtworkStudioContentProps>(({ agentI
[agentId, t, updateAgentMetaById, uploadWithProgress],
);
- const selectStyle = useCallback((next: AgentArtworkStyle) => setStyle(next), []);
-
- const keySelect = useCallback(
- (next: AgentArtworkStyle) => (event: { key: string; preventDefault: () => void }) => {
- if (event.key === 'Enter' || event.key === ' ') {
- event.preventDefault();
- setStyle(next);
- }
- },
- [],
- );
-
return (
- <Flexbox horizontal gap={32} padding={24} wrap={'wrap'}>
- {/* DIY path: the live avatar plus upload. The preview doubles as the
- generation stage so both paths land on the same picture. */}
- <Flexbox gap={16} style={{ flex: 'none', width: 232 }}>
- <Center className={styles.preview} height={232} width={232}>
- {/* Keyed by the url: Avatar latches an internal `isImgError` on the
- first failed load and never clears it when `avatar` changes, so a
- previously broken avatar would keep the freshly generated one
- invisible until a reload. */}
- <Avatar
- avatar={meta.avatar || undefined}
- key={avatarRemountKey(meta.avatar)}
- shape={'square'}
- size={180}
- />
- {generating ? (
- <Center className={styles.generationOverlay}>
- <Flexbox align={'center'} gap={10}>
- <NeuralNetworkLoading size={32} />
- <Flexbox align={'center'} gap={4}>
- <Text className={styles.sectionTitle}>
- {t('settingAgent.artwork.avatar.generating')}
- </Text>
- <Text className={styles.hint} style={{ textAlign: 'center' }}>
- {t('settingAgent.artwork.generatingHint')}
- </Text>
- <Button
- size={'small'}
- style={{ marginBlockStart: 4 }}
- type={'fill'}
- onClick={() => void cancelAgentArtworkGeneration(agentId)}
- >
- {t('settingAgent.artwork.cancel')}
- </Button>
- </Flexbox>
- </Flexbox>
- </Center>
- ) : null}
- </Center>
- <Flexbox gap={8}>
- <Text className={styles.sectionTitle}>{t('settingAgent.artwork.studio.diyTitle')}</Text>
- <Text className={styles.hint}>{t('settingAgent.artwork.studio.diyHint')}</Text>
- <Button
- icon={UploadIcon}
- loading={uploading}
- onClick={() => {
- const input = uploadInputRef.current;
- if (input) openFilePicker(input);
- }}
- >
- {t('settingAgent.artwork.studio.upload')}
- </Button>
- </Flexbox>
- </Flexbox>
-
- {/* One-click path: brand style first, then the generated style gallery. */}
- <Flexbox gap={16} style={{ flex: 1, minWidth: 280 }}>
- <Flexbox gap={4}>
- <Text className={styles.sectionTitle}>
- {t('settingAgent.artwork.studio.generateTitle')}
- </Text>
- <Text className={styles.hint}>{t('settingAgent.artwork.studio.generateHint')}</Text>
- </Flexbox>
-
- {canGenerate ? (
- <>
- <Flexbox
- horizontal
- align={'center'}
- className={`${styles.lobeCard} ${style === 'lobe' ? styles.lobeCardActive : ''}`}
- gap={12}
- padding={12}
- role={'button'}
- tabIndex={0}
- onClick={() => selectStyle('lobe')}
- onKeyDown={keySelect('lobe')}
- >
- <Flexbox horizontal flex={'none'} gap={4}>
- {LOBE_STYLE_REFERENCE_IMAGE_URLS.map((url) => (
- <Avatar avatar={url} key={url} shape={'square'} size={40} />
- ))}
- </Flexbox>
- <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
- <Flexbox horizontal align={'center'} gap={8}>
- <Text className={styles.sectionTitle}>
- {t('settingAgent.artwork.studio.lobeStyle')}
- </Text>
- <Tag color={'processing'} size={'small'}>
- {t('settingAgent.artwork.studio.recommended')}
- </Tag>
- </Flexbox>
- <Text ellipsis className={styles.hint}>
- {t('settingAgent.artwork.style.lobe')}
- </Text>
- </Flexbox>
- {style === 'lobe' ? (
- <Icon color={cssVar.colorPrimary} icon={Check} size={18} style={{ flex: 'none' }} />
- ) : null}
- </Flexbox>
-
- <Flexbox gap={8}>
- <Text className={styles.hint}>{t('settingAgent.artwork.studio.moreStyles')}</Text>
- <div className={styles.galleryGrid}>
- {GALLERY_STYLES.map((item) => (
- <Flexbox
- className={styles.galleryItem}
- gap={6}
- key={item}
- role={'button'}
- tabIndex={0}
- onClick={() => selectStyle(item)}
- onKeyDown={keySelect(item)}
- >
- <div className={styles.galleryThumbWrap}>
- <img
- alt={t(`settingAgent.artwork.style.${item}`)}
- className={styles.galleryThumb}
- src={imageUrl(`agent-artwork-styles/style-${item}.jpg`)}
- />
- {style === item ? (
- <Center className={styles.galleryCheck}>
- <Icon icon={Check} size={13} />
- </Center>
- ) : null}
- </div>
- <Text ellipsis className={styles.galleryLabel}>
- {t(`settingAgent.artwork.style.${item}`)}
- </Text>
- </Flexbox>
- ))}
- </div>
- </Flexbox>
-
- <Flexbox gap={8} style={{ marginBlockStart: 'auto' }}>
- <Button
- disabled={generating}
- icon={WandSparkles}
- type={'primary'}
- onClick={() => generate(style)}
- >
- {t('settingAgent.artwork.studio.generate')}
- </Button>
- {generationError ? (
- <Alert showIcon title={t('settingAgent.artwork.generateFailed')} type={'error'} />
- ) : null}
- </Flexbox>
- </>
- ) : (
- <Center className={styles.noModelBlock} flex={1} gap={12} padding={24}>
- <Text className={styles.hint} style={{ textAlign: 'center' }}>
- {t('settingAgent.artwork.studio.noModel')}
- </Text>
- <Button
- icon={SettingsIcon}
- type={'primary'}
- onClick={() => {
- close();
- navigate('/settings/provider/all');
- }}
- >
- {t('settingAgent.artwork.studio.enableModel')}
- </Button>
- </Center>
- )}
- </Flexbox>
-
- <input
- accept="image/*"
- aria-label={t('settingAgent.artwork.studio.upload')}
- className={styles.visuallyHiddenInput}
- ref={uploadInputRef}
- tabIndex={-1}
- type="file"
- onChange={(event) => {
- const file = event.target.files?.[0];
- event.target.value = '';
- if (file) void upload(file);
- }}
- />
- </Flexbox>
+ <ArtworkStudioContent
+ avatar={meta.avatar}
+ diyHint={t('settingAgent.artwork.studio.diyHint')}
+ generateHint={t('settingAgent.artwork.studio.generateHint')}
+ generating={generating}
+ generatingTitle={t('settingAgent.artwork.avatar.generating')}
+ generationFailed={generationFailed}
+ uploading={uploading}
+ onCancel={() => void cancelAgentArtworkGeneration(agentId)}
+ onGenerate={generate}
+ onUpload={(file) => void upload(file)}
+ />
);
});
diff --git a/src/features/AgentArtworkStudio/index.tsx b/src/features/AgentArtworkStudio/index.tsx
index 0a05fd5c711..b7a32021e4e 100644
--- a/src/features/AgentArtworkStudio/index.tsx
+++ b/src/features/AgentArtworkStudio/index.tsx
@@ -5,7 +5,7 @@ import { t } from 'i18next';
import AgentArtworkStudioContent from './Content';
-export { styleReferencesForArtworkStyle } from './lobeStyleReferences';
+export { styleReferencesForArtworkStyle } from '@/features/ArtworkStudio';
/**
* Large avatar workshop for one agent: make your own (upload) or one-click
diff --git a/src/features/AgentProfileArtwork/index.tsx b/src/features/AgentProfileArtwork/index.tsx
index 35add8f4920..57e9068bc85 100644
--- a/src/features/AgentProfileArtwork/index.tsx
+++ b/src/features/AgentProfileArtwork/index.tsx
@@ -304,7 +304,7 @@ export const AgentProfileArtwork = memo<AgentProfileArtworkProps>(
AGENT_ARTWORK_STYLES.map((style) => ({
icon: style === artworkStyle ? Check : undefined,
key: style,
- label: t(`settingAgent.artwork.style.${style}`),
+ label: t(`artworkStudio.style.${style}`),
onClick: () => {
setArtworkStyle(style);
void generateArtwork(kind, style);
diff --git a/src/features/AgentProfileArtwork/utils.test.ts b/src/features/AgentProfileArtwork/utils.test.ts
index 6b33538eed7..85c2858901a 100644
--- a/src/features/AgentProfileArtwork/utils.test.ts
+++ b/src/features/AgentProfileArtwork/utils.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest';
-import { selectAgentArtworkModel } from '@/store/agent/slices/artwork/utils';
+import { selectAgentArtworkModel } from '@/services/artworkGeneration/selectModel';
import type { EnabledProviderWithModels } from '@/types/aiProvider';
import { avatarRemountKey, openFilePicker, resolveAgentBackground } from './utils';
diff --git a/src/features/ArtworkStudio/Content.tsx b/src/features/ArtworkStudio/Content.tsx
new file mode 100644
index 00000000000..c163f7b7f8e
--- /dev/null
+++ b/src/features/ArtworkStudio/Content.tsx
@@ -0,0 +1,381 @@
+'use client';
+
+import { imageUrl } from '@lobechat/const';
+import {
+ AGENT_ARTWORK_STYLES,
+ type AgentArtworkStyle,
+ DEFAULT_AGENT_ARTWORK_STYLE,
+} from '@lobechat/prompts';
+import { Alert, Avatar, Center, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
+import { Button, useModalContext } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { Check, SettingsIcon, UploadIcon, WandSparkles } from 'lucide-react';
+import { memo, useCallback, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+import { avatarRemountKey, openFilePicker } from '@/features/AgentProfileArtwork/utils';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useAiInfraStore } from '@/store/aiInfra';
+import { aiProviderSelectors } from '@/store/aiInfra/selectors';
+
+import { LOBE_STYLE_REFERENCE_IMAGE_URLS } from './styleReferences';
+
+const GALLERY_STYLES = AGENT_ARTWORK_STYLES.filter((item) => item !== 'lobe');
+
+const styles = createStaticStyles(({ css }) => ({
+ galleryCheck: css`
+ position: absolute;
+ z-index: 1;
+ inset-block-start: 6px;
+ inset-inline-end: 6px;
+
+ width: 20px;
+ height: 20px;
+ border-radius: 50%;
+
+ color: ${cssVar.colorTextLightSolid};
+
+ background: ${cssVar.colorPrimary};
+ `,
+ galleryGrid: css`
+ display: grid;
+
+ /* One row of five, per review: the set is curated to exactly five styles. */
+ grid-template-columns: repeat(5, 1fr);
+ gap: 8px;
+ `,
+ galleryItem: css`
+ cursor: pointer;
+ border-radius: ${cssVar.borderRadiusLG};
+
+ &:hover img {
+ filter: brightness(1.06);
+ }
+ `,
+ galleryLabel: css`
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ text-align: center;
+ `,
+ galleryThumb: css`
+ aspect-ratio: 1;
+ width: 100%;
+ border-radius: ${cssVar.borderRadiusLG};
+
+ object-fit: cover;
+
+ transition: filter ${cssVar.motionDurationFast};
+ `,
+ galleryThumbWrap: css`
+ position: relative;
+ `,
+ generationOverlay: css`
+ position: absolute;
+ z-index: 2;
+ inset: 0;
+
+ border-radius: calc(${cssVar.borderRadiusLG} - 1px);
+
+ background: color-mix(in srgb, ${cssVar.colorBgContainer} 88%, transparent);
+ backdrop-filter: blur(12px);
+ `,
+ hint: css`
+ font-size: 13px;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ lobeCard: css`
+ cursor: pointer;
+ border-radius: ${cssVar.borderRadiusLG};
+ background: ${cssVar.colorFillQuaternary};
+ transition: background ${cssVar.motionDurationFast};
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ lobeCardActive: css`
+ background: ${cssVar.colorFillSecondary};
+
+ &:hover {
+ background: ${cssVar.colorFillSecondary};
+ }
+ `,
+ noModelBlock: css`
+ border-radius: ${cssVar.borderRadiusLG};
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ preview: css`
+ position: relative;
+
+ overflow: hidden;
+ flex: none;
+
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ sectionTitle: css`
+ font-weight: 500;
+ `,
+ visuallyHiddenInput: css`
+ pointer-events: none;
+
+ position: fixed;
+
+ overflow: hidden;
+
+ width: 1px;
+ height: 1px;
+
+ opacity: 0;
+ `,
+}));
+
+export interface ArtworkStudioContentProps {
+ /** Current avatar url; falsy renders the empty avatar placeholder. */
+ avatar?: string | null;
+ /** Copy under the "make your own" heading — names the subject being dressed. */
+ diyHint: string;
+ /** Copy under the "generate with AI" heading. */
+ generateHint: string;
+ generating?: boolean;
+ /** Headline shown over the preview while a generation runs. */
+ generatingTitle: string;
+ /** True when the last generation attempt failed and can be retried. */
+ generationFailed?: boolean;
+ onCancel: () => void;
+ onGenerate: (style: AgentArtworkStyle) => void;
+ onUpload: (file: File) => void;
+ uploading?: boolean;
+}
+
+/**
+ * Avatar workshop shared by every subject that can own one (Agents, workspaces):
+ * make your own on the left, one-click generation in a preset style on the
+ * right. Purely presentational — the caller owns the avatar value, the
+ * generation lifecycle, and where the result is persisted.
+ */
+const ArtworkStudioContent = memo<ArtworkStudioContentProps>(
+ ({
+ avatar,
+ diyHint,
+ generateHint,
+ generatingTitle,
+ generating,
+ generationFailed,
+ onCancel,
+ onGenerate,
+ onUpload,
+ uploading,
+ }) => {
+ const { t } = useTranslation('setting');
+ const { close } = useModalContext();
+ const navigate = useWorkspaceAwareNavigate();
+ const canGenerate = useAiInfraStore(
+ (state) => aiProviderSelectors.enabledImageModelList(state).length > 0,
+ );
+
+ const uploadInputRef = useRef<HTMLInputElement>(null);
+ const [style, setStyle] = useState<AgentArtworkStyle>(DEFAULT_AGENT_ARTWORK_STYLE);
+
+ const selectStyle = useCallback((next: AgentArtworkStyle) => setStyle(next), []);
+
+ const keySelect = useCallback(
+ (next: AgentArtworkStyle) => (event: { key: string; preventDefault: () => void }) => {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ setStyle(next);
+ }
+ },
+ [],
+ );
+
+ return (
+ <Flexbox horizontal gap={32} padding={24} wrap={'wrap'}>
+ {/* DIY path: the live avatar plus upload. The preview doubles as the
+ generation stage so both paths land on the same picture. */}
+ <Flexbox gap={16} style={{ flex: 'none', width: 232 }}>
+ <Center className={styles.preview} height={232} width={232}>
+ {/* Keyed by the url: Avatar latches an internal `isImgError` on the
+ first failed load and never clears it when `avatar` changes, so a
+ previously broken avatar would keep the freshly generated one
+ invisible until a reload. */}
+ <Avatar
+ avatar={avatar || undefined}
+ key={avatarRemountKey(avatar)}
+ shape={'square'}
+ size={180}
+ />
+ {generating ? (
+ <Center className={styles.generationOverlay}>
+ <Flexbox align={'center'} gap={10}>
+ <NeuralNetworkLoading size={32} />
+ <Flexbox align={'center'} gap={4}>
+ <Text className={styles.sectionTitle}>{generatingTitle}</Text>
+ <Text className={styles.hint} style={{ textAlign: 'center' }}>
+ {t('artworkStudio.generatingHint')}
+ </Text>
+ <Button
+ size={'small'}
+ style={{ marginBlockStart: 4 }}
+ type={'fill'}
+ onClick={onCancel}
+ >
+ {t('artworkStudio.cancel')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ </Center>
+ ) : null}
+ </Center>
+ <Flexbox gap={8}>
+ <Text className={styles.sectionTitle}>{t('artworkStudio.diyTitle')}</Text>
+ <Text className={styles.hint}>{diyHint}</Text>
+ <Button
+ icon={UploadIcon}
+ loading={uploading}
+ onClick={() => {
+ const input = uploadInputRef.current;
+ if (input) openFilePicker(input);
+ }}
+ >
+ {t('artworkStudio.upload')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+
+ {/* One-click path: brand style first, then the generated style gallery. */}
+ <Flexbox gap={16} style={{ flex: 1, minWidth: 280 }}>
+ <Flexbox gap={4}>
+ <Text className={styles.sectionTitle}>{t('artworkStudio.generateTitle')}</Text>
+ <Text className={styles.hint}>{generateHint}</Text>
+ </Flexbox>
+
+ {canGenerate ? (
+ <>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={`${styles.lobeCard} ${style === 'lobe' ? styles.lobeCardActive : ''}`}
+ gap={12}
+ padding={12}
+ role={'button'}
+ tabIndex={0}
+ onClick={() => selectStyle('lobe')}
+ onKeyDown={keySelect('lobe')}
+ >
+ <Flexbox horizontal flex={'none'} gap={4}>
+ {LOBE_STYLE_REFERENCE_IMAGE_URLS.map((url) => (
+ <Avatar avatar={url} key={url} shape={'square'} size={40} />
+ ))}
+ </Flexbox>
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text className={styles.sectionTitle}>{t('artworkStudio.lobeStyle')}</Text>
+ <Tag color={'processing'} size={'small'}>
+ {t('artworkStudio.recommended')}
+ </Tag>
+ </Flexbox>
+ <Text ellipsis className={styles.hint}>
+ {t('artworkStudio.style.lobe')}
+ </Text>
+ </Flexbox>
+ {style === 'lobe' ? (
+ <Icon
+ color={cssVar.colorPrimary}
+ icon={Check}
+ size={18}
+ style={{ flex: 'none' }}
+ />
+ ) : null}
+ </Flexbox>
+
+ <Flexbox gap={8}>
+ <Text className={styles.hint}>{t('artworkStudio.moreStyles')}</Text>
+ <div className={styles.galleryGrid}>
+ {GALLERY_STYLES.map((item) => (
+ <Flexbox
+ className={styles.galleryItem}
+ gap={6}
+ key={item}
+ role={'button'}
+ tabIndex={0}
+ onClick={() => selectStyle(item)}
+ onKeyDown={keySelect(item)}
+ >
+ <div className={styles.galleryThumbWrap}>
+ <img
+ alt={t(`artworkStudio.style.${item}`)}
+ className={styles.galleryThumb}
+ src={imageUrl(`agent-artwork-styles/style-${item}.jpg`)}
+ />
+ {style === item ? (
+ <Center className={styles.galleryCheck}>
+ <Icon icon={Check} size={13} />
+ </Center>
+ ) : null}
+ </div>
+ <Text ellipsis className={styles.galleryLabel}>
+ {t(`artworkStudio.style.${item}`)}
+ </Text>
+ </Flexbox>
+ ))}
+ </div>
+ </Flexbox>
+
+ <Flexbox gap={8} style={{ marginBlockStart: 'auto' }}>
+ <Button
+ disabled={generating}
+ icon={WandSparkles}
+ type={'primary'}
+ onClick={() => onGenerate(style)}
+ >
+ {t('artworkStudio.generate')}
+ </Button>
+ {generationFailed ? (
+ <Alert showIcon title={t('artworkStudio.generateFailed')} type={'error'} />
+ ) : null}
+ </Flexbox>
+ </>
+ ) : (
+ <Center className={styles.noModelBlock} flex={1} gap={12} padding={24}>
+ <Text className={styles.hint} style={{ textAlign: 'center' }}>
+ {t('artworkStudio.noModel')}
+ </Text>
+ <Button
+ icon={SettingsIcon}
+ type={'primary'}
+ onClick={() => {
+ close();
+ navigate('/settings/provider/all');
+ }}
+ >
+ {t('artworkStudio.enableModel')}
+ </Button>
+ </Center>
+ )}
+ </Flexbox>
+
+ <input
+ accept="image/*"
+ aria-label={t('artworkStudio.upload')}
+ className={styles.visuallyHiddenInput}
+ ref={uploadInputRef}
+ tabIndex={-1}
+ type="file"
+ onChange={(event) => {
+ const file = event.target.files?.[0];
+ event.target.value = '';
+ if (file) onUpload(file);
+ }}
+ />
+ </Flexbox>
+ );
+ },
+);
+
+ArtworkStudioContent.displayName = 'ArtworkStudioContent';
+
+export default ArtworkStudioContent;
diff --git a/src/features/ArtworkStudio/index.ts b/src/features/ArtworkStudio/index.ts
new file mode 100644
index 00000000000..ce1699c02f2
--- /dev/null
+++ b/src/features/ArtworkStudio/index.ts
@@ -0,0 +1,5 @@
+export { default as ArtworkStudioContent, type ArtworkStudioContentProps } from './Content';
+export { LOBE_STYLE_REFERENCE_IMAGE_URLS, styleReferencesForArtworkStyle } from './styleReferences';
+// Re-exported so a surface can render the studio without taking a direct
+// dependency on `@lobechat/prompts`.
+export type { AgentArtworkStyle } from '@lobechat/prompts';
diff --git a/src/features/AgentArtworkStudio/lobeStyleReferences.ts b/src/features/ArtworkStudio/styleReferences.ts
similarity index 100%
rename from src/features/AgentArtworkStudio/lobeStyleReferences.ts
rename to src/features/ArtworkStudio/styleReferences.ts
diff --git a/src/services/artworkGeneration/generateArtworkImage.ts b/src/services/artworkGeneration/generateArtworkImage.ts
new file mode 100644
index 00000000000..910566b1c58
--- /dev/null
+++ b/src/services/artworkGeneration/generateArtworkImage.ts
@@ -0,0 +1,170 @@
+import type { AgentArtworkKind } 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 { AsyncTaskStatus } from '@/types/asyncTask';
+
+import { selectAgentArtworkModel } from './selectModel';
+
+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 },
+ );
+ });
+
+const pollGeneratedImageUrl = 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');
+};
+
+/**
+ * References that actually survived the chosen model's capabilities — the
+ * prompt has to describe exactly what got attached, or the wording promises
+ * the model an image it never received.
+ */
+export interface AttachedArtworkReferences {
+ referenceImageUrl?: string;
+ styleReferenceImageUrls: string[];
+}
+
+export interface GenerateArtworkImageOptions {
+ buildPrompt: (references: AttachedArtworkReferences) => string;
+ kind: AgentArtworkKind;
+ /**
+ * Fires as soon as the remote generation exists, so a caller that owns the
+ * cancel affordance can delete it after the fact.
+ */
+ onGenerationCreated?: (generationId: string) => void;
+ referenceImageUrl?: string | null;
+ signal: AbortSignal;
+ styleReferenceImageUrls?: string[] | null;
+ /** Title of the private generation topic the image is filed under. */
+ topicTitle: string;
+}
+
+/**
+ * Runs one artwork generation end to end — model pick, reference budgeting,
+ * topic creation, submission, polling — and resolves with the image url.
+ *
+ * Shared by every "one-click artwork" surface (Agent avatars and covers,
+ * workspace avatars), so it deliberately knows nothing about where the
+ * resulting url is saved.
+ */
+export const generateArtworkImage = async ({
+ buildPrompt,
+ kind,
+ onGenerationCreated,
+ referenceImageUrl,
+ signal,
+ styleReferenceImageUrls,
+ topicTitle,
+}: GenerateArtworkImageOptions): Promise<string> => {
+ 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 supportsImageInput = !!model.parameters && 'imageUrls' in model.parameters;
+ const imageInputLimit = supportsImageInput
+ ? (model.parameters?.imageUrls?.maxCount ?? Number.POSITIVE_INFINITY)
+ : 0;
+ // Style references win over the counterpart-artwork reference; the prompt
+ // builders apply the same precedence so wording matches attachments.
+ const attachedStyleReferences = (styleReferenceImageUrls ?? [])
+ .map((url) => url.trim())
+ .filter(Boolean)
+ .slice(0, imageInputLimit);
+ const counterpartReferenceUrl =
+ attachedStyleReferences.length > 0 ? undefined : referenceImageUrl?.trim();
+ const supportsReferenceImage = !!counterpartReferenceUrl && supportsImageInput;
+ const imageUrls =
+ attachedStyleReferences.length > 0
+ ? attachedStyleReferences
+ : supportsReferenceImage
+ ? [counterpartReferenceUrl]
+ : undefined;
+ const supportedSizes =
+ model.parameters && 'size' in model.parameters ? model.parameters.size?.enum : undefined;
+ const preferredSizes =
+ kind === 'avatar' ? ['1024x1024', '2048x2048'] : ['2048x1152', '1536x1024', '3840x2160'];
+ const size = preferredSizes.find((item) => supportedSizes?.includes(item));
+ const generationTopicId = await generationTopicService.createTopic(
+ 'image',
+ 'private',
+ topicTitle,
+ );
+ const aspectRatio = kind === 'avatar' ? '1:1' : '16:9';
+ const params = {
+ ...(model.parameters && 'aspectRatio' in model.parameters ? { aspectRatio } : {}),
+ ...(imageUrls ? { imageUrls } : {}),
+ ...(size ? { size } : {}),
+ prompt: buildPrompt({
+ referenceImageUrl: supportsReferenceImage ? counterpartReferenceUrl : undefined,
+ styleReferenceImageUrls: attachedStyleReferences,
+ }),
+ };
+ 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');
+ }
+
+ onGenerationCreated?.(generationId);
+ // Cancellation can land while `createImage` is still in flight, in which case
+ // nothing else will ever clean up the generation we just created.
+ if (signal.aborted) {
+ await generationService.deleteGeneration(generationId);
+ signal.throwIfAborted();
+ }
+
+ const url = await pollGeneratedImageUrl(generationId, asyncTaskId, signal);
+ signal.throwIfAborted();
+
+ return url;
+};
diff --git a/src/services/artworkGeneration/index.ts b/src/services/artworkGeneration/index.ts
new file mode 100644
index 00000000000..3c130106e33
--- /dev/null
+++ b/src/services/artworkGeneration/index.ts
@@ -0,0 +1,13 @@
+export {
+ type AttachedArtworkReferences,
+ generateArtworkImage,
+ type GenerateArtworkImageOptions,
+} from './generateArtworkImage';
+export { selectAgentArtworkModel } from './selectModel';
+export {
+ generateWorkspaceAvatarImage,
+ type GenerateWorkspaceAvatarImageOptions,
+} from './workspaceAvatar';
+// Re-exported so downstream consumers can type their style parameters without
+// taking a direct dependency on `@lobechat/prompts`.
+export type { AgentArtworkKind, AgentArtworkStyle } from '@lobechat/prompts';
diff --git a/src/store/agent/slices/artwork/utils.test.ts b/src/services/artworkGeneration/selectModel.test.ts
similarity index 96%
rename from src/store/agent/slices/artwork/utils.test.ts
rename to src/services/artworkGeneration/selectModel.test.ts
index 74a479f96ee..3533044beb8 100644
--- a/src/store/agent/slices/artwork/utils.test.ts
+++ b/src/services/artworkGeneration/selectModel.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest';
import type { EnabledProviderWithModels } from '@/types/aiProvider';
-import { selectAgentArtworkModel } from './utils';
+import { selectAgentArtworkModel } from './selectModel';
const provider = (id: string, modelIds: string[]) =>
({
diff --git a/src/store/agent/slices/artwork/utils.ts b/src/services/artworkGeneration/selectModel.ts
similarity index 100%
rename from src/store/agent/slices/artwork/utils.ts
rename to src/services/artworkGeneration/selectModel.ts
diff --git a/src/services/artworkGeneration/workspaceAvatar.ts b/src/services/artworkGeneration/workspaceAvatar.ts
new file mode 100644
index 00000000000..c176bcffe2a
--- /dev/null
+++ b/src/services/artworkGeneration/workspaceAvatar.ts
@@ -0,0 +1,45 @@
+import type { AgentArtworkStyle } from '@lobechat/prompts';
+import { buildWorkspaceArtworkPrompt } from '@lobechat/prompts';
+
+import { generateArtworkImage } from './generateArtworkImage';
+
+export interface GenerateWorkspaceAvatarImageOptions {
+ description?: string | null;
+ id: string;
+ name?: string | null;
+ onGenerationCreated?: (generationId: string) => void;
+ signal: AbortSignal;
+ style: AgentArtworkStyle;
+ /** Brand-style reference images, resolved by the calling UI layer. */
+ styleReferenceImageUrls?: string[];
+}
+
+/**
+ * Generates one workspace avatar and resolves with its url — the workspace
+ * counterpart to the Agent artwork action. Lives here rather than in the
+ * caller so that the prompt contract stays next to the generation engine.
+ */
+export const generateWorkspaceAvatarImage = ({
+ description,
+ id,
+ name,
+ onGenerationCreated,
+ signal,
+ style,
+ styleReferenceImageUrls,
+}: GenerateWorkspaceAvatarImageOptions): Promise<string> =>
+ generateArtworkImage({
+ buildPrompt: (references) =>
+ buildWorkspaceArtworkPrompt({
+ description,
+ id,
+ name,
+ style,
+ styleReferenceImageUrls: references.styleReferenceImageUrls,
+ }),
+ kind: 'avatar',
+ onGenerationCreated,
+ signal,
+ styleReferenceImageUrls,
+ topicTitle: 'Workspace avatar',
+ });
diff --git a/src/store/agent/slices/artwork/action.ts b/src/store/agent/slices/artwork/action.ts
index cc569183b65..66050859ee2 100644
--- a/src/store/agent/slices/artwork/action.ts
+++ b/src/store/agent/slices/artwork/action.ts
@@ -1,33 +1,12 @@
import type { AgentArtworkPromptInput } from '@lobechat/prompts';
import { buildAgentArtworkPrompt } from '@lobechat/prompts';
+import { generateArtworkImage } from '@/services/artworkGeneration';
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;
@@ -50,35 +29,6 @@ export class AgentArtworkActionImpl {
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) {
@@ -114,80 +64,18 @@ export class AgentArtworkActionImpl {
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 supportsImageInput = !!model.parameters && 'imageUrls' in model.parameters;
- const imageInputLimit = supportsImageInput
- ? (model.parameters?.imageUrls?.maxCount ?? Number.POSITIVE_INFINITY)
- : 0;
- // Style references win over the counterpart-artwork reference; the prompt
- // builder applies the same precedence so wording matches attachments.
- const styleReferenceImageUrls = (input.styleReferenceImageUrls ?? [])
- .map((url) => url.trim())
- .filter(Boolean)
- .slice(0, imageInputLimit);
- const referenceImageUrl =
- styleReferenceImageUrls.length > 0 ? undefined : input.referenceImageUrl?.trim();
- const supportsReferenceImage = !!referenceImageUrl && supportsImageInput;
- const imageUrls =
- styleReferenceImageUrls.length > 0
- ? styleReferenceImageUrls
- : supportsReferenceImage
- ? [referenceImageUrl]
- : undefined;
- 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 } : {}),
- ...(imageUrls ? { imageUrls } : {}),
- ...(size ? { size } : {}),
- prompt: buildAgentArtworkPrompt({
- ...input,
- referenceImageUrl: supportsReferenceImage ? referenceImageUrl : undefined,
- styleReferenceImageUrls,
- }),
- };
- const result = await imageService.createImage({
- generationTopicId,
- imageNum: 1,
- model: model.id,
- params,
- provider: provider.id,
+ const url = await generateArtworkImage({
+ buildPrompt: (references) => buildAgentArtworkPrompt({ ...input, ...references }),
+ kind: input.kind,
+ onGenerationCreated: (generationId) => {
+ job.generationId = generationId;
+ },
+ referenceImageUrl: input.referenceImageUrl,
+ signal: job.controller.signal,
+ styleReferenceImageUrls: input.styleReferenceImageUrls,
+ topicTitle: input.kind === 'avatar' ? 'Agent avatar' : 'Agent background',
});
- 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 },
diff --git a/src/store/agent/slices/artwork/index.ts b/src/store/agent/slices/artwork/index.ts
index 3e0ed63d8ba..e540e2fb5b7 100644
--- a/src/store/agent/slices/artwork/index.ts
+++ b/src/store/agent/slices/artwork/index.ts
@@ -4,4 +4,3 @@ export {
type AgentArtworkSliceState,
initialAgentArtworkSliceState,
} from './initialState';
-export { selectAgentArtworkModel } from './utils';