🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(agent): add a transparent full-body artwork to the Agent artwork studio (#18446)
Arvin Xu334a10aec174
diff --git a/.agents/acceptance/PROJECT.md b/.agents/acceptance/PROJECT.mdindex 3a95d07d579..d050bdb53d2 100644--- a/.agents/acceptance/PROJECT.md+++ b/.agents/acceptance/PROJECT.md@@ -108,8 +108,11 @@ stale standalone install: a recently added workspace package fails to resolve`DATABASE_URL=postgresql://postgres:postgres@localhost:5433/postgres`,`DATABASE_DRIVER=node`, `AGENT_RUNTIME_MODE=queue`,`REDIS_URL=redis://localhost:6380`, `FEATURE_FLAGS=-agent_self_iteration`,- `KEY_VAULTS_SECRET`, `AUTH_SECRET`, auth verification off, plus local `s3rver`- and local QStash vars. Treat the dev-server terminal output as final when the+ `KEY_VAULTS_SECRET`, `AUTH_SECRET`, auth verification off, a generated+ `JWKS_KEY` (persisted at `.records/env/agent-testing-jwks.json`, required by every+ async-task dispatch such as image generation), `SSRF_ALLOW_PRIVATE_IP_ADDRESS=1`+ (the server fetches reference images from the local s3rver on 127.0.0.1), plus+ local `s3rver` and local QStash vars. Treat the dev-server terminal output as final when theport is non-standard, then `export SERVER_URL=http://localhost:<port>`.In the cloud repo (this repo as the `lobehub/` submodule), worktree names mapdiff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.mdindex 8dfafbea5a6..9087330a661 100644--- a/.agents/acceptance/common-mistakes.md+++ b/.agents/acceptance/common-mistakes.md@@ -718,3 +718,22 @@ your own file with `git checkout stash@{n} -- <your file>`; **never pop or dropwhole stash** — it belongs to the other session, and popping it is that session'sown action. When you find conflict markers in someone else's file, wait for them toresolve it rather than resolving it for them.++### L-S14 — Claiming an image property from the prompt that asked for it++**Wrong approach:** satisfy a requirement about a generated image (transparent+background, exact aspect ratio, no text) by adding that wording to the prompt, then+publish the prompt diff, a unit test asserting the wording, and a screenshot of the+result as proof.++**Why it fails:** the property lives in the returned bytes, not in the request. LobeHub's+preferred artwork model returns JPEG, so an alpha channel is impossible regardless of+wording — and asked for "a transparent background" the model _paints_ the grey-white+checkerboard that UIs use to depict transparency. Both failures look correct in a+screenshot and pass any prompt-level assertion.++**Correct approach:** verify the produced artifact — decode it and assert the property+numerically (alpha at the corners vs the subject, encoded format signature, dimensions),+and where the property is compositional, show the artifact over a contrasting surface.+When the model cannot deliver the property, produce it in code after generation rather+than re-wording the prompt.diff --git a/.agents/acceptance/references/probe-field-notes.md b/.agents/acceptance/references/probe-field-notes.mdindex 2450ee5e0ba..64185d8b8cc 100644--- a/.agents/acceptance/references/probe-field-notes.md+++ b/.agents/acceptance/references/probe-field-notes.md@@ -734,9 +734,27 @@ executionTarget: 'local'` in `agencyConfig`) + one message per case asking CC to### E22. Local dev env has no `JWKS_KEY` — every hetero agent run dies at `signOperationJwt`- **Situation**: a real Claude Code / Codex run in the local no-`.env` env fails immediately with `Failed to sign operation JWT for hetero agent` (`apps/server/src/services/aiAgent/index.ts`). Nothing in the UI explains it; the topic just fails.-- **Cause**: `signOperationJwt` → `getSigningKey()` → `getJwksKey()` needs the `JWKS_KEY` RSA JWK, and `init-dev-env.sh` does not export one.-- **Works**: the repo ships a generator — `JWKS_KEY="$(node scripts/generate-oidc-jwk.mjs)" ./.agents/acceptance/scripts/init-dev-env.sh dev`. Must be present at dev-server **start** (it is read from `process.env`), so a running server has to be restarted.+- **Cause**: `signOperationJwt` → `getSigningKey()` → `getJwksKey()` needs the `JWKS_KEY` RSA JWK.+- **Fixed in the bootstrap**: `init-dev-env.sh` now generates one on first use and persists it at `.records/env/agent-testing-jwks.json`, then exports `JWKS_KEY` from `apply_env`. A server started any other way still needs it explicitly — `JWKS_KEY="$(node scripts/generate-oidc-jwk.mjs)" …` — and it must be present at dev-server **start** (read from `process.env`), so a running server has to be restarted.- **Note the failure is downstream-honest**: with `JWKS_KEY` set, the run proceeds and then fails at the hetero _sandbox_ (`Hetero sandbox spawn failed / unauthorized`) unless the agent has a real Claude Code token. Those are two different walls — don't read the second as the first.+- **Same wall, other feature**: any async-task dispatch needs it too. Image generation (`lambda/image.createImage` → `createAsyncCaller`) records the task as `error` with `start async task error: JWKS_KEY environment variable is not set`, which surfaces in the UI only as a generic 「暂时无法生成图片,请重试」 — read `async_tasks.error` rather than the toast.++### E23b. Local image generation needs three env pieces, and each fails as the same generic toast++- **Situation**: driving a real image generation from the app (avatar / artwork studio, `lambda/image.createImage`) against the local no-`.env` backend. The UI only ever says 「暂时无法生成图片,请重试」.+- **Read the cause from `async_tasks.error`, not the toast**: `docker exec <pg> psql -U postgres -d postgres -c "select status, error from async_tasks order by created_at desc limit 3;"`.+- **Three separate walls, in the order you hit them**:+ 1. `start async task error: JWKS_KEY environment variable is not set` → see E22. The bootstrap now exports a persisted `JWKS_KEY`; you only hit this on a server started outside `init-dev-env.sh`.+ 2. `InvalidProviderAPIKey` → the seeded user's stored `ai_providers.key_vaults` may hold a key encrypted with a different `KEY_VAULTS_SECRET`. Clear it (`update ai_providers set key_vaults = null where id = '<provider>'`) so the server env key is used; provide `<PROVIDER>_API_KEY` plus, for a relay endpoint, `<PROVIDER>_PROXY_URL` (`apps/server/src/modules/ModelRuntime/index.ts` reads `process.env[`${UPPER}\_PROXY\_URL`]`).+ 3. `SSRF blocked: ... is not allowed. Because, It is private IP address.` → any reference image living in the local s3rver is fetched **server-side**. The bootstrap now exports `SSRF_ALLOW_PRIVATE_IP_ADDRESS=1`; set it yourself on a server started another way.+- **Then note which model the product actually picked** before attributing quality or format to a model: read the product's own selector rather than assuming (`selectAgentArtworkModel(enabledImageModelList(...))` over CDP). Disabling a provider row is enough to change the pick.+- **Style presets that attach reference images can still fail after all three**: local presigned URLs may return an S3 XML error body, which reaches the model as `Unsupported MIME type: application/xml`. Pick a preset with no reference images to test generation itself.++### E23c. A green desktop surface can be talking to another worktree's dev server++- **Situation**: verifying a schema-backed field from the Electron app. Writes landed, but reads came back without the new column, and the app looked healthy throughout.+- **Cause**: the desktop client proxies to whatever `dataSyncConfig.remoteServerUrl` says (E-note above). Any worktree can occupy that port — here the port was taken by a dev server started from the _main_ repo, whose branch has no such column. `init-dev-env.sh dev-next` then dies with `EADDRINUSE` in a log you are not watching, and the app keeps serving the other branch's code.+- **Works**: confirm the owner before trusting a read — `lsof -p "$(lsof -ti tcp:<port> -sTCP:LISTEN | head -1)" | grep cwd` must print the worktree under test. Do not kill a server you did not start; run yours on a free port (and repoint the app) or wait for the port. To separate a server-code problem from a client one, exercise the service directly with `bun` against the same `DATABASE_URL` — it uses the worktree's own schema.### E25. Electron `will-attach-webview` params carry NO custom attributes — identity via data-\* never arrivesdiff --git a/.agents/acceptance/scripts/init-dev-env.sh b/.agents/acceptance/scripts/init-dev-env.shindex 08018aa63af..3b8055222b0 100755--- a/.agents/acceptance/scripts/init-dev-env.sh+++ b/.agents/acceptance/scripts/init-dev-env.sh@@ -102,6 +102,7 @@ REDIS_CONTAINER="${REDIS_CONTAINER:-lobehub-agent-testing-redis}"REDIS_URL="${REDIS_URL:-redis://localhost:${REDIS_PORT}}"ENV_FILE_DEFAULT="$WORKSPACE_ROOT/.records/env/agent-testing-dev.env"CLI_ENV_FILE_DEFAULT="$WORKSPACE_ROOT/.records/env/agent-testing-cli.env"+JWKS_FILE_DEFAULT="$WORKSPACE_ROOT/.records/env/agent-testing-jwks.json"AGENT_TESTING_API_KEY="${AGENT_TESTING_API_KEY:-sk-lh-agenttesting0001}"QSTASH_DEV_PORT="${QSTASH_DEV_PORT:-8080}"QSTASH_LOCAL_TOKEN="${QSTASH_LOCAL_TOKEN:-eyJVc2VySUQiOiJkZWZhdWx0VXNlciIsIlBhc3N3b3JkIjoiZGVmYXVsdFBhc3N3b3JkIn0=}"@@ -110,6 +111,21 @@ QSTASH_LOCAL_NEXT_SIGNING_KEY="${QSTASH_LOCAL_NEXT_SIGNING_KEY:-sig_5ZB6DVzB1wjES3_DEV_PORT="${S3_DEV_PORT:-29000}"S3_DATA_DIR="${S3_DATA_DIR:-$WORKSPACE_ROOT/.records/data/agent-testing-s3}"+# Any async task the server dispatches (image generation, hetero agent runs) signs+# an internal JWT, so a missing JWKS_KEY kills the feature before it reaches its+# own code — and it surfaces as a generic UI error. Generate one once and reuse it.+_load_or_gen_jwks() {+ [[ -n "${JWKS_KEY:-}" ]] && return 0+ if [[ ! -s "$JWKS_FILE_DEFAULT" ]]; then+ mkdir -p "$(dirname "$JWKS_FILE_DEFAULT")"+ node "$REPO_ROOT/scripts/generate-oidc-jwk.mjs" 2> /dev/null > "$JWKS_FILE_DEFAULT" || {+ rm -f "$JWKS_FILE_DEFAULT"+ return 0+ }+ fi+ JWKS_KEY="$(cat "$JWKS_FILE_DEFAULT")"+}+ok() { printf ' \033[32m✔\033[0m %s\n' "$1"; }bad() { printf ' \033[31m✘\033[0m %s\n' "$1"; }note() { printf ' %s\n' "$1"; }@@ -181,6 +197,13 @@ apply_env() {export S3_SET_ACL="${S3_SET_ACL:-0}"export SPA_PORTexport VITE_DEV_PORT="${VITE_DEV_PORT:-$SPA_PORT}"+ _load_or_gen_jwks+ export JWKS_KEY+ # Reference images (style presets, uploaded artwork) live in the local s3rver on+ # 127.0.0.1, and the server fetches them itself before calling a model. Without+ # this the fetch is refused as a private-IP SSRF target. Local-only: the bootstrap+ # never runs against a deployed server (guard_no_root_env).+ export SSRF_ALLOW_PRIVATE_IP_ADDRESS="${SSRF_ALLOW_PRIVATE_IP_ADDRESS:-1}"# Bypass cloud chat-security UA/headless fingerprint checks for local e2e only.# Guarded by NODE_ENV !== 'production' inside detectSuspiciousRequest(), so it# can never weaken production. Lets headless agent-browser drive real chats.@@ -218,6 +241,8 @@ env_keys() {S3_SET_ACL \SPA_PORT \VITE_DEV_PORT \+ JWKS_KEY \+ SSRF_ALLOW_PRIVATE_IP_ADDRESS \AGENT_TESTING_DISABLE_CHAT_SECURITY}diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 7ea9a12584a..2f44f4af141 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -242,23 +242,32 @@"apps.mobile.title": "Mobile","apps.title": "Discover more ways to use LobeHub","artworkStudio.cancel": "Cancel generation",+ "artworkStudio.composition.avatar": "Avatar",+ "artworkStudio.composition.fullBody": "Full body",+ "artworkStudio.direction.placeholder": "Add a detail — \"a boy with glasses\", \"cyberpunk mechanic\" (optional)","artworkStudio.diyTitle": "Make your own","artworkStudio.enableModel": "Enable a model",- "artworkStudio.generate": "Generate avatar",+ "artworkStudio.framePreview": "Preview what home shows",+ "artworkStudio.generate.avatar": "Generate",+ "artworkStudio.generate.characterSet": "Generate both images",+ "artworkStudio.generate.fullBody": "Generate","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.preview.fullBody": "Full-body character preview",+ "artworkStudio.reference.remove": "Remove reference",+ "artworkStudio.reference.title": "Reference",+ "artworkStudio.remove": "Remove",+ "artworkStudio.style.anime": "Anime",+ "artworkStudio.style.lineArt": "Hand-drawn Lines",+ "artworkStudio.style.lobe": "Lobe Style",+ "artworkStudio.style.painterly": "Hand-painted","artworkStudio.style.pixel": "Pixel Art",- "artworkStudio.style.sticker": "Sticker",- "artworkStudio.style.watercolor": "Watercolor",- "artworkStudio.upload": "Upload image",+ "artworkStudio.style.title": "Style",+ "artworkStudio.upload": "Upload",+ "artworkStudio.uploadSpec.avatar": "1:1 · PNG / JPG ≤ 1 MB",+ "artworkStudio.uploadSpec.fullBody": "3:4 · transparent PNG ≤ 1 MB","checking": "Checking...","checkingPermissions": "Checking permissions...","creds.actions.delete": "Delete",@@ -754,7 +763,7 @@"settingAgent.agentTools.tabAgent": "Agent Tools","settingAgent.agentTools.tabUser": "User Tools","settingAgent.agentTools.tabWorkspace": "Workspace Tools",- "settingAgent.artwork.avatar.generating": "Creating an avatar that matches this Agent…",+ "settingAgent.artwork.avatar.generating": "Creating an image that matches this Agent…","settingAgent.artwork.avatar.image": "AI avatar","settingAgent.artwork.background.empty": "Add a background to give this Agent a visual identity","settingAgent.artwork.background.emptyHint": "Add a cover image",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex c651b317552..1ccaad3b7e0 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -242,23 +242,32 @@"apps.mobile.title": "移动端","apps.title": "探索 LobeHub 的更多使用方式","artworkStudio.cancel": "取消生成",+ "artworkStudio.composition.avatar": "头像",+ "artworkStudio.composition.fullBody": "全身形象",+ "artworkStudio.direction.placeholder": "补充形象描述,例如「戴眼镜的少年」「机械朋克」(选填)","artworkStudio.diyTitle": "自行制作","artworkStudio.enableModel": "去启用",- "artworkStudio.generate": "一键生成",+ "artworkStudio.framePreview": "预览首页取景",+ "artworkStudio.generate.avatar": "生成",+ "artworkStudio.generate.characterSet": "同时生成两个形象",+ "artworkStudio.generate.fullBody": "生成","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.preview.fullBody": "全身形象预览",+ "artworkStudio.reference.remove": "移除参考图",+ "artworkStudio.reference.title": "参考图",+ "artworkStudio.remove": "移除",+ "artworkStudio.style.anime": "二次元",+ "artworkStudio.style.lineArt": "线条手绘",+ "artworkStudio.style.lobe": "Lobe 风格",+ "artworkStudio.style.painterly": "手绘油画","artworkStudio.style.pixel": "像素风",- "artworkStudio.style.sticker": "贴纸插画",- "artworkStudio.style.watercolor": "水彩手绘",- "artworkStudio.upload": "上传图片",+ "artworkStudio.style.title": "选择风格",+ "artworkStudio.upload": "上传",+ "artworkStudio.uploadSpec.avatar": "1:1 · PNG / JPG ≤ 1 MB",+ "artworkStudio.uploadSpec.fullBody": "3:4 · 透明底 PNG ≤ 1 MB","checking": "检查中…","checkingPermissions": "检查权限中…","creds.actions.delete": "删除",@@ -754,7 +763,7 @@"settingAgent.agentTools.tabAgent": "Agent 工具","settingAgent.agentTools.tabUser": "用户工具","settingAgent.agentTools.tabWorkspace": "Workspace 工具",- "settingAgent.artwork.avatar.generating": "正在生成符合助理形象的头像…",+ "settingAgent.artwork.avatar.generating": "正在生成符合 Agent 设定的形象…","settingAgent.artwork.avatar.image": "AI 形象","settingAgent.artwork.background.empty": "添加背景,让助理拥有更鲜明的视觉形象","settingAgent.artwork.background.emptyHint": "添加封面图片",diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.tsindex 3f8b298088e..ab6d402e195 100644--- a/packages/database/src/models/__tests__/agent.test.ts+++ b/packages/database/src/models/__tests__/agent.test.ts@@ -1190,6 +1190,25 @@ describe('AgentModel', () => {});describe('updateConfig', () => {+ it('replaces the profile wholesale so a removed trait can be cleared', async () => {+ const agent = await serverDB+ .insert(agents)+ .values({+ profile: { artworkStyle: 'anime', fullBodyArtwork: 'https://cdn/full-body.png' },+ userId,+ })+ .returning()+ .then((res) => res[0]);++ await agentModel.updateConfig(agent.id, { profile: { artworkStyle: 'anime' } });++ const result = await serverDB.query.agents.findFirst({+ where: eq(agents.id, agent.id),+ });++ expect(result?.profile).toEqual({ artworkStyle: 'anime' });+ });+it('should update agent config and set updatedAt', async () => {const agent = await serverDB.insert(agents)diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.tsindex 74fe38aad00..a2590a2ff8c 100644--- a/packages/database/src/models/agent.ts+++ b/packages/database/src/models/agent.ts@@ -1388,6 +1388,14 @@ export class AgentModel {}}+ // A character sheet is authored as a whole: the studio reads the current+ // profile and writes the version it wants. Deep-merging it would make a+ // cleared trait or a removed artwork impossible to express, since a missing+ // key reads as "leave it alone". Same reasoning as the graph below.+ if (Object.hasOwn(data, 'profile')) {+ mergedValue.profile = data.profile as AgentItem['profile'];+ }+// A AgentGraph is a complete executable document, not a partial config// patch — replace it wholesale instead of deep-merging. The Graph Agent// (agencyConfig.graph) is the agent's behavior body; legacy clients maydiff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 001ba89e08e..26da869948d 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -72,24 +72,34 @@ export default {'accountDeletion.workspaceBlocked.title': 'Transfer your workspaces first','advancedSettings': 'Advanced Settings','artworkStudio.cancel': 'Cancel generation',+ 'artworkStudio.composition.avatar': 'Avatar',+ 'artworkStudio.composition.fullBody': 'Full body',+ 'artworkStudio.direction.placeholder':+ 'Add a detail — "a boy with glasses", "cyberpunk mechanic" (optional)','artworkStudio.diyTitle': 'Make your own','artworkStudio.enableModel': 'Enable a model',- 'artworkStudio.generate': 'Generate avatar',+ 'artworkStudio.generate.avatar': 'Generate',+ 'artworkStudio.generate.fullBody': 'Generate',+ 'artworkStudio.generate.characterSet': 'Generate both images',+ 'artworkStudio.framePreview': 'Preview what home shows','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.reference.remove': 'Remove reference',+ 'artworkStudio.reference.title': 'Reference',+ 'artworkStudio.remove': 'Remove',+ 'artworkStudio.style.anime': 'Anime',+ 'artworkStudio.style.lineArt': 'Hand-drawn Lines',+ 'artworkStudio.style.lobe': 'Lobe Style',+ 'artworkStudio.style.painterly': 'Hand-painted','artworkStudio.style.pixel': 'Pixel Art',- 'artworkStudio.style.sticker': 'Sticker',- 'artworkStudio.style.watercolor': 'Watercolor',- 'artworkStudio.upload': 'Upload image',+ 'artworkStudio.style.title': 'Style',+ 'artworkStudio.upload': 'Upload',+ 'artworkStudio.uploadSpec.avatar': '1:1 · PNG / JPG ≤ 1 MB',+ 'artworkStudio.uploadSpec.fullBody': '3:4 · transparent PNG ≤ 1 MB',+ 'artworkStudio.preview.fullBody': 'Full-body character preview','agentCronJobs.addJob': 'Add Scheduled Task','agentCronJobs.clearTopics': 'Clear Topics','agentCronJobs.clearTopicsFailed': 'Failed to clear topics',@@ -834,7 +844,7 @@ 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.generating': 'Creating an avatar that matches this Agent…',+ 'settingAgent.artwork.avatar.generating': 'Creating an image that matches this Agent…','settingAgent.artwork.avatar.image': 'AI avatar','settingAgent.artwork.background.empty': 'Add a background to give this Agent a visual identity','settingAgent.artwork.background.emptyHint': 'Add a cover image',diff --git a/packages/prompts/src/prompts/agentArtwork/index.test.ts b/packages/prompts/src/prompts/agentArtwork/index.test.tsindex 185e0b64794..98aead44d5c 100644--- a/packages/prompts/src/prompts/agentArtwork/index.test.ts+++ b/packages/prompts/src/prompts/agentArtwork/index.test.ts@@ -21,7 +21,7 @@ describe('buildAgentArtworkPrompt', () => {);expect(prompt).toContain('<description>Helps with TypeScript & React</description>');expect(prompt).toContain('full-bleed composition');- expect(prompt).toContain('square profile icon');+ expect(prompt).toContain('square character image');});it('includes the system role in a wide background prompt', () => {@@ -114,21 +114,148 @@ describe('buildAgentArtworkPrompt', () => {);expect(new Set(prompts).size).toBe(AGENT_ARTWORK_STYLES.length);- expect(prompts.find((p) => p.includes('watercolor'))).toBeTruthy();- expect(prompts.find((p) => p.includes('pixel art'))).toBeTruthy();- expect(prompts.find((p) => p.includes('die-cut sticker'))).toBeTruthy();+ expect(prompts.find((p) => p.includes('Japanese anime'))).toBeTruthy();+ expect(prompts.find((p) => p.includes('minimalist hand-drawn line art'))).toBeTruthy();+ expect(prompts.find((p) => p.includes('64 x 64 pixel grid'))).toBeTruthy();});it('applies the chosen style to both avatar and background prompts', () => {- const avatar = buildAgentArtworkPrompt({ id: 'agent-1', kind: 'avatar', style: 'clay' });+ const avatar = buildAgentArtworkPrompt({ id: 'agent-1', kind: 'avatar', style: 'painterly' });const background = buildAgentArtworkPrompt({id: 'agent-1',kind: 'background',- style: 'clay',+ style: 'painterly',});- expect(avatar).toContain('clay-style figure');- expect(background).toContain('clay-style figure');+ expect(avatar).toContain('hand-painted texture');+ expect(background).toContain('hand-painted texture');+ });++ it('supports a full-body character composition', () => {+ const prompt = buildAgentArtworkPrompt({+ composition: 'fullBody',+ id: 'agent-1',+ kind: 'avatar',+ style: 'anime',+ });++ expect(prompt).toContain('complete head-to-toe character image');+ expect(prompt).toContain('entire body clearly');+ expect(prompt).toContain('distinctive portrait character image');+ expect(prompt).toContain('entire portrait canvas');+ expect(prompt).not.toContain('distinctive square character image');+ expect(prompt).not.toContain('head fills most of the frame');+ });++ it('asks every full-body style for one flat keyable backdrop', () => {+ for (const style of AGENT_ARTWORK_STYLES) {+ const prompt = buildAgentArtworkPrompt({+ composition: 'fullBody',+ id: 'agent-1',+ kind: 'avatar',+ style,+ });++ expect(prompt).toContain('completely flat, uniform background color that contrasts');+ expect(prompt).toContain('keyed out cleanly');+ // The per-style backdrop clauses would compete with the contrast requirement.+ expect(prompt).not.toContain('matching solid-color background');+ expect(prompt).not.toContain('vivid contrasting solid background color');+ expect(prompt).not.toContain('pure white background');+ }+ });++ it('bans the painted checkerboard that "transparent background" wording produces', () => {+ const prompt = buildAgentArtworkPrompt({+ composition: 'fullBody',+ id: 'agent-1',+ kind: 'avatar',+ style: 'anime',+ });++ expect(prompt).toContain('Never draw a checkerboard');+ expect(prompt).not.toContain('transparent background');+ });++ it('keeps the avatar composition on its solid background', () => {+ const prompt = buildAgentArtworkPrompt({+ composition: 'avatar',+ id: 'agent-1',+ kind: 'avatar',+ });++ expect(prompt).toContain('one vivid contrasting solid background color');+ expect(prompt).not.toContain('keyed out cleanly');+ });++ it('keeps the mascot character wording when the lobe backdrop clause is dropped', () => {+ const prompt = buildAgentArtworkPrompt({+ composition: 'fullBody',+ id: 'agent-1',+ kind: 'avatar',+ style: 'lobe',+ });++ expect(prompt).toContain('mascot-style 3D emoji character');+ expect(prompt).toContain('soft studio lighting. Express the identity');+ });++ it('keeps style references compatible with a full-body composition', () => {+ const prompt = buildAgentArtworkPrompt({+ composition: 'fullBody',+ id: 'agent-1',+ kind: 'avatar',+ style: 'lineArt',+ styleReferenceImageUrls: ['https://example.com/line-art.webp'],+ });++ expect(prompt).toContain('character design, line quality');+ expect(prompt).not.toContain('mascot-like head-dominant look');+ });++ it('uses an existing avatar as the exact character reference for a full-body image', () => {+ const prompt = buildAgentArtworkPrompt({+ composition: 'fullBody',+ id: 'agent-1',+ kind: 'avatar',+ referenceImageUrl: 'https://example.com/avatar.webp',+ style: 'anime',+ });++ expect(prompt).toContain('existing avatar as the exact character source of truth');+ expect(prompt).toContain('same identity, face, hair, outfit');+ expect(prompt).toContain('Do not redesign or reinterpret the character');+ expect(prompt).toContain("ignore the avatar's background entirely");+ expect(prompt).not.toContain('existing profile background');+ });++ it('appends the user direction last so it outweighs the derived concept', () => {+ const prompt = buildAgentArtworkPrompt({+ direction: '戴眼镜的少年 & 机械风',+ id: 'agent-1',+ kind: 'avatar',+ });++ expect(prompt).toContain('The user asked for this specifically:');+ expect(prompt).toContain('戴眼镜的少年 & 机械风');+ expect(prompt).toContain('does not conflict with the canvas, composition, and no-text rules');+ expect(prompt.trimEnd().endsWith('rules above.')).toBe(true);+ });++ it('ignores a blank user direction', () => {+ const prompt = buildAgentArtworkPrompt({ direction: ' ', id: 'agent-1', kind: 'avatar' });++ expect(prompt).not.toContain('The user asked for this specifically');+ });++ it('carries the user direction into a cover prompt too', () => {+ const prompt = buildAgentArtworkPrompt({+ direction: 'deep sea',+ id: 'agent-1',+ kind: 'background',+ });++ expect(prompt).toContain('The user asked for this specifically: deep sea');});it('steers the motif away from generic technology clichés in every prompt', () => {@@ -144,10 +271,10 @@ describe('buildAgentArtworkPrompt', () => {id: 'designer',kind: 'background',referenceImageUrl: 'https://example.com/avatar.png',- style: 'watercolor',+ style: 'lineArt',});- expect(prompt).toContain('hand-painted watercolor');+ expect(prompt).toContain('minimalist hand-drawn line art');expect(prompt).not.toContain('illustration style');});});diff --git a/packages/prompts/src/prompts/agentArtwork/index.ts b/packages/prompts/src/prompts/agentArtwork/index.tsindex a19fe705d89..b35a2c198e9 100644--- a/packages/prompts/src/prompts/agentArtwork/index.ts+++ b/packages/prompts/src/prompts/agentArtwork/index.ts@@ -1,15 +1,9 @@import { escapeXmlAttr, escapeXmlContent } from '../search/xmlEscape';export type AgentArtworkKind = 'avatar' | 'background';+export type AgentArtworkComposition = 'avatar' | 'fullBody';-export const AGENT_ARTWORK_STYLES = [- 'lobe',- 'clay',- 'watercolor',- 'geometric',- 'pixel',- 'sticker',-] as const;+export const AGENT_ARTWORK_STYLES = ['lobe', 'anime', 'lineArt', 'pixel', 'painterly'] as const;export type AgentArtworkStyle = (typeof AGENT_ARTWORK_STYLES)[number];@@ -23,16 +17,36 @@ export const DEFAULT_AGENT_ARTWORK_STYLE: AgentArtworkStyle = 'lobe';* through outfit and accessories instead.*/const STYLE_DIRECTIONS: Record<AgentArtworkStyle, string> = {- clay: 'Render it as a soft 3D clay-style figure with rounded forms, matte materials, subtle hand-made charm, gentle studio lighting, and warm pastel colors.',- geometric:- 'Render it as flat geometric illustration built from bold simple shapes, crisp edges, and a confident limited palette in the spirit of mid-century poster design.',- lobe: "Render it as a bold mascot-style 3D emoji character: a single oversized head filling most of the frame, skin in one friendly likeable color that people love — warm yellow, orange, peach, coral, or soft brown (not realistic human skin, and never odd tones like green, teal, or gray), graphic simplified facial features with an expression that matches the agent's personality (a knowing wink, a curious smile, a warm grin — lively, never blank or babyish), glossy candy-like materials with soft studio lighting, and one vivid contrasting solid background color. Show at most a hint of shoulders. Express the identity through a hat and one or two small floating accessory props beside the head — do not draw scenes, maps, or diagrams on the character.",+ anime:+ 'Render it in an expressive FLCL-inspired Japanese anime style. Choose an age and character archetype that fits the agent, such as a young boy, a playful young woman, a mature onee-san, or a handsome older man. Use a matching solid-color background with no decorations.',+ lineArt:+ "Render it as minimalist hand-drawn line art. Use the pose and styling to communicate the agent's professional traits. Use a pure white background.",+ lobe: "Render it as a bold mascot-style 3D emoji character: skin in one friendly likeable color that people love — warm yellow, orange, peach, coral, or soft brown (not realistic human skin, and never odd tones like green, teal, or gray), graphic simplified facial features with an expression that matches the agent's personality (a knowing wink, a curious smile, a warm grin — lively, never blank or babyish), glossy candy-like materials with soft studio lighting, and one vivid contrasting solid background color. Express the identity through a hat and one or two small accessory props — do not draw scenes, maps, or diagrams on the character.",+ painterly:+ 'Render it with a cinematic 3D-to-2D hand-painted texture and dramatic stylization inspired by premium animated fantasy series, against a matching solid-color background.',pixel:- 'Render it as crisp retro pixel art with chunky readable pixels, a limited bright palette, and clean shading in the spirit of classic 16-bit games.',- sticker:- 'Render it as a glossy die-cut sticker illustration with bold clean outlines, flat vivid colors, a thick white sticker border, and a simple bright solid background.',- watercolor:- 'Render it as a hand-painted watercolor piece with visible paper texture, soft pigment washes, and loose organic edges.',+ 'Render it as crisp pixel art on a 64 x 64 pixel grid, against a matching solid-color background with no decorations.',+};++/**+ * Every style direction above signs off with its own background clause — a+ * matching color, or pure white. Both fight the cut-out: a matching color is by+ * definition close to the character's palette, and white collides with the+ * white that anime and line-art styles put on the character. These variants+ * drop that clause so the contrast requirement above is the only backdrop rule.+ */+const FULL_BODY_STYLE_OVERRIDES: Record<AgentArtworkStyle, string> = {+ anime: STYLE_DIRECTIONS.anime.replace(+ ' Use a matching solid-color background with no decorations.',+ '',+ ),+ lineArt: STYLE_DIRECTIONS.lineArt.replace(' Use a pure white background.', ''),+ lobe: STYLE_DIRECTIONS.lobe.replace(', and one vivid contrasting solid background color', ''),+ painterly: STYLE_DIRECTIONS.painterly.replace(', against a matching solid-color background', ''),+ pixel: STYLE_DIRECTIONS.pixel.replace(+ ', against a matching solid-color background with no decorations',+ '',+ ),};/**@@ -54,6 +68,18 @@ 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.`;+/**+ * The full-body artwork is composited onto product surfaces, so its backdrop has+ * to come off afterwards. Asking the model for "a transparent background" does+ * NOT work — the returned image has no alpha channel and the model paints a+ * checkerboard *depicting* transparency instead. So we ask for the one thing it+ * can actually deliver: a single flat keyable color, which the client then cuts+ * out (see `cutOutFlatBackground`).+ */+const FULL_BODY_CANVAS_DIRECTION = `Use the entire portrait canvas for a clean character presentation. Place the character against one completely flat, uniform background color that contrasts clearly with the character and appears nowhere on the character itself: exactly one solid color across the whole canvas, with no gradient, no shading, no texture, no scenery, no ground plane, and no cast or drop shadow, so the background can be keyed out cleanly. Never draw a checkerboard, grid, or any other pattern that depicts transparency. No frame, no border, no words, no letters, and no logo.`;++const AVATAR_COMPOSITION_DIRECTION = `Compose a close-up avatar: the head fills most of the frame, with at most a little of the upper body visible.`;+const FULL_BODY_COMPOSITION_DIRECTION = `Compose a complete head-to-toe character image: show the entire body clearly, centered in a natural standing or action pose, with comfortable breathing room around the silhouette. Keep the face expressive and readable.`;/*** `character` is for avatars, where the references define the TARGET subject@@ -64,24 +90,61 @@ const AVATAR_CANVAS_DIRECTION = `Fill the entire square canvas edge to edge with*/const buildStyleReferenceDirection = (count: number,- mode: 'character' | 'surface',+ mode: 'character' | 'fullBodyCharacter' | 'surface',subject: string,+ /**+ * A preset reference is one of ours: it stands for a look, so the prompt has+ * to fence off its literal subject. A reference the user attached is the+ * opposite — they are pointing at the character they want, and refusing to+ * follow it would ignore the only thing they said.+ */+ isUserSupplied = false,): 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.`;+ if (isUserSupplied)+ return `\n\nThe user attached the ${imageWord} as ${possessive} own reference for this character. Follow ${possessive} appearance closely — the same character design, features, palette, and rendering — and adapt it to the composition and canvas rules above rather than inventing a different character.`;++ if (mode === 'surface')+ return `\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 compositionQualities =+ mode === 'fullBodyCharacter'+ ? 'character design, line quality, materials, lighting, and color energy'+ : 'mascot-like head-dominant look, single-color skin, material, lighting, and color energy';++ return `\n\nUse the attached ${imageWord} as the target character style — the same ${compositionQualities}. Do not copy ${possessive} exact faces, hats, or subjects — invent a new character for the ${subject} described above.`;+};++/**+ * The user's own words are the most specific input we have, so they go last —+ * models weight the tail of a prompt heavily — while the canvas, composition+ * and no-text rules stay authoritative because product surfaces depend on them.+ */+const buildUserDirection = (direction?: string | null): string => {+ const trimmed = direction?.trim();+ if (!trimmed) return '';++ return `\n\nThe user asked for this specifically: ${escapeXmlContent(trimmed.slice(0, 600))}. Follow it wherever it does not conflict with the canvas, composition, and no-text rules above.`;};const countStyleReferences = (urls?: string[] | null): number =>urls?.filter((url) => url.trim()).length ?? 0;export interface AgentArtworkPromptInput {+ composition?: AgentArtworkComposition;description?: string | null;+ /**+ * Free-text direction the user typed in the studio ("a boy with glasses",+ * "cyberpunk mechanic"). It is the most specific thing we know about what+ * they want, so it lands last and is allowed to override the derived+ * concept — but not the canvas or composition rules, which the product+ * depends on.+ */+ direction?: string | null;id: string;kind: AgentArtworkKind;name?: string | null;@@ -94,6 +157,12 @@ export interface AgentArtworkPromptInput {* blend the two references unpredictably.*/styleReferenceImageUrls?: string[] | null;+ /**+ * Where `styleReferenceImageUrls` came from. `custom` means the user attached+ * them, which flips the wording from "borrow this look" to "follow this+ * character" — see {@link buildStyleReferenceDirection}.+ */+ styleReferenceSource?: 'preset' | 'custom' | null;systemRole?: string | null;title?: string | null;}@@ -127,32 +196,50 @@ export const buildAgentArtworkPrompt = (input: AgentArtworkPromptInput): stringtitle: input.title,});const style = input.style ?? DEFAULT_AGENT_ARTWORK_STYLE;+ const composition = input.composition ?? 'avatar';const styleDirection =input.kind === 'background'? (BACKGROUND_STYLE_OVERRIDES[style] ?? STYLE_DIRECTIONS[style])- : STYLE_DIRECTIONS[style];+ : composition === 'fullBody'+ ? FULL_BODY_STYLE_OVERRIDES[style]+ : STYLE_DIRECTIONS[style];const styleReferenceCount = countStyleReferences(input.styleReferenceImageUrls);const styleReferenceDirection = buildStyleReferenceDirection(styleReferenceCount,- input.kind === 'avatar' ? 'character' : 'surface',+ input.kind === 'background'+ ? 'surface'+ : composition === 'fullBody'+ ? 'fullBodyCharacter'+ : 'character','agent',+ input.styleReferenceSource === 'custom',);const counterpartReferenceUrl = styleReferenceCount > 0 ? undefined : input.referenceImageUrl;+ const userDirection = buildUserDirection(input.direction);if (input.kind === 'avatar') {// The reference paragraph preserves palette / materials / motifs but not the// rendering style itself — the user may regenerate with a different preset,// and the style direction above must stay authoritative.const referenceDirection = counterpartReferenceUrl?.trim()- ? `\n\nUse the attached existing profile background as the visual source of truth. Preserve its dominant color palette, 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.`+ ? composition === 'fullBody'+ ? `\n\nUse the attached existing avatar as the exact character source of truth. Preserve the same identity, face, hair, outfit, accessories, color palette, materials, and rendering style while extending that character into a complete head-to-toe pose. Do not redesign or reinterpret the character. Take nothing but the character from it — ignore the avatar's background entirely and use the flat keyable backdrop described above instead.`+ : `\n\nUse the attached existing profile background as the visual source of truth. Preserve its dominant color palette, 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.+ const compositionDirection =+ composition === 'fullBody' ? FULL_BODY_COMPOSITION_DIRECTION : AVATAR_COMPOSITION_DIRECTION;+ const canvasDirection =+ composition === 'fullBody' ? FULL_BODY_CANVAS_DIRECTION : AVATAR_CANVAS_DIRECTION;++ const canvasShape = composition === 'fullBody' ? 'portrait' : 'square';++ return `Create a distinctive ${canvasShape} character image 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 with a simple silhouette. ${styleDirection} ${MOTIF_DIRECTION} ${AVATAR_CANVAS_DIRECTION}${styleReferenceDirection}${referenceDirection}`;+Translate the agent's identity, purpose, and personality into one coherent visual concept. Use a single centered subject with a simple silhouette. ${compositionDirection} ${styleDirection} ${MOTIF_DIRECTION} ${canvasDirection}${styleReferenceDirection}${referenceDirection}${userDirection}`;}const referenceDirection = counterpartReferenceUrl?.trim()@@ -163,7 +250,7 @@ Translate the agent's identity, purpose, and personality into one coherent visua${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}`;+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}${userDirection}`;};/**diff --git a/packages/types/src/agent/item.ts b/packages/types/src/agent/item.tsindex 0a8f1002b62..d93f04b4a1d 100644--- a/packages/types/src/agent/item.ts+++ b/packages/types/src/agent/item.ts@@ -40,20 +40,20 @@ export interface LobeAgentConfig {* Used to save the complete state of the rich text editor, including special nodes like mention*/editorData?: any;+fewShots?: FewShots;files?: FileItem[];id?: string;-/*** knowledge bases*/knowledgeBases?: KnowledgeBaseItem[];+/*** Language model used by the agent* @default gpt-4o-mini*/model: string;-/*** The agent's personal name (e.g. "Alice", "小艾") — the identity it is* addressed by. Distinct from {@link LobeAgentConfig.title}, which describes@@ -66,15 +66,16 @@ export interface LobeAgentConfig {* Opening message*/openingMessage?: string;+/*** Opening questions*/openingQuestions?: string[];-/*** Language model parameters*/params: LLMParams;+/*** Enabled plugins. Each entry is either a legacy bare identifier string* (implicit pinned) or a tri-state `{ identifier, mode }` object — see@@ -83,6 +84,8 @@ export interface LobeAgentConfig {* `getPluginMode`) over reading this field directly.*/plugins?: AgentPluginEntry[];+ /** Character sheet — traits and artwork; see {@link AgentProfile}. */+ profile?: AgentProfile | null;/*** Model providerdiff --git a/packages/types/src/agent/profile.ts b/packages/types/src/agent/profile.tsindex ce3a1adc6f3..61f5662a239 100644--- a/packages/types/src/agent/profile.ts+++ b/packages/types/src/agent/profile.ts@@ -64,6 +64,12 @@ export interface AgentProfile {* dropping what they asked for.*/artworkDirection?: string;+ /**+ * A reference image the user attached themselves. Unlike a style preset — which+ * says "look like this kind of art" — this says "look like THIS character", so+ * a generation using it follows the reference instead of inventing a subject.+ */+ artworkReferenceImage?: string;/*** Id of the artwork style preset the current images were generated with, so* reopening the studio resumes where the user left off. Values are thediff --git a/public/app-images/agent-artwork-styles/line-art-reference.webp b/public/app-images/agent-artwork-styles/line-art-reference.webpnew file mode 100644index 00000000000..5bd56a26cbeBinary files /dev/null and b/public/app-images/agent-artwork-styles/line-art-reference.webp differdiff --git a/public/app-images/agent-artwork-styles/style-anime.webp b/public/app-images/agent-artwork-styles/style-anime.webpnew file mode 100644index 00000000000..97c304e8c9bBinary files /dev/null and b/public/app-images/agent-artwork-styles/style-anime.webp differdiff --git a/public/app-images/agent-artwork-styles/style-lineArt.webp b/public/app-images/agent-artwork-styles/style-lineArt.webpnew file mode 100644index 00000000000..bedd6480b4dBinary files /dev/null and b/public/app-images/agent-artwork-styles/style-lineArt.webp differdiff --git a/public/app-images/agent-artwork-styles/style-painterly.webp b/public/app-images/agent-artwork-styles/style-painterly.webpnew file mode 100644index 00000000000..8d5c0769fb4Binary files /dev/null and b/public/app-images/agent-artwork-styles/style-painterly.webp differdiff --git a/public/app-images/agent-artwork-styles/style-pixel.webp b/public/app-images/agent-artwork-styles/style-pixel.webpnew file mode 100644index 00000000000..29a581fcfd6Binary files /dev/null and b/public/app-images/agent-artwork-styles/style-pixel.webp differdiff --git a/src/features/AgentArtworkStudio/Content.tsx b/src/features/AgentArtworkStudio/Content.tsxindex 84a021c8aeb..0756534c185 100644--- a/src/features/AgentArtworkStudio/Content.tsx+++ b/src/features/AgentArtworkStudio/Content.tsx@@ -1,25 +1,62 @@'use client';-import type { AgentArtworkStyle } from '@lobechat/prompts';+import type { AgentArtworkComposition, AgentArtworkStyle } from '@lobechat/prompts';+import type { AgentProfile } from '@lobechat/types';import { toast } from '@lobehub/ui/base-ui';import { memo, useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';import { resolveAgentBackground } from '@/features/AgentProfileArtwork/utils';import { ArtworkStudioContent, styleReferencesForArtworkStyle } from '@/features/ArtworkStudio';+import { useAppOrigin } from '@/hooks/useAppOrigin';+import { cutOutFullBodyArtwork } from '@/services/artworkGeneration';import { useAgentStore } from '@/store/agent';import { agentArtworkSelectors, agentSelectors } from '@/store/agent/selectors';import { useFileStore } from '@/store/file';+import { generateCharacterSet } from './generateCharacterSet';+const MAX_AVATAR_SIZE = 1024 * 1024;interface AgentArtworkStudioContentProps {agentId: string;}+/**+ * Image models return an opaque JPEG, so the generated full-body artwork is cut+ * out and re-uploaded as a transparent PNG before it is stored — the home+ * surface composites it over its own background. A failed cut-out keeps the+ * original artwork rather than blocking the result.+ */+const useTransparentFullBody = () => {+ const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);++ return useCallback(+ async (url: string) => {+ const file = await cutOutFullBodyArtwork(url);+ if (!file) return url;++ try {+ const result = await uploadWithProgress({ file });++ return result?.url || url;+ } catch (error) {+ console.error('Failed to upload the transparent full-body artwork:', error);++ return url;+ }+ },+ [uploadWithProgress],+ );+};+const AgentArtworkStudioContent = memo<AgentArtworkStudioContentProps>(({ agentId }) => {const { t } = useTranslation('setting');+ const appOrigin = useAppOrigin();const meta = useAgentStore(agentSelectors.getAgentMetaById(agentId));+ const fullBody = useAgentStore(agentSelectors.getAgentFullBodyArtworkById(agentId));+ const profile = useAgentStore(agentSelectors.getAgentProfileById(agentId));+ const storedAvatar = useAgentStore(agentSelectors.getAgentStoredAvatarById(agentId));const systemRole = useAgentStore((s) => agentSelectors.getAgentConfigById(agentId)(s)?.systemRole,);@@ -28,41 +65,137 @@ const AgentArtworkStudioContent = memo<AgentArtworkStudioContentProps>(({ agentIconst cancelAgentArtworkGeneration = useAgentStore((s) => s.cancelAgentArtworkGeneration);const updateAgentMetaById = useAgentStore((s) => s.updateAgentMetaById);const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);+ const toTransparentFullBody = useTransparentFullBody();const [uploading, setUploading] = useState(false);+ const [generatingTarget, setGeneratingTarget] = useState<AgentArtworkComposition | 'both'>();const generating = generation?.status === 'generating' && generation.kind === 'avatar';const generationFailed = generation?.status === 'error' && generation.kind === 'avatar';+ // `profile` is one jsonb bag, so a partial write has to merge rather than replace.+ const saveProfile = useCallback(+ (patch: Partial<AgentProfile>) =>+ updateAgentMetaById(agentId, { profile: { ...profile, ...patch } }),+ [agentId, profile, updateAgentMetaById],+ );+const generate = useCallback(- (nextStyle: AgentArtworkStyle) => {- generateAgentArtwork({+ async (+ nextStyle: AgentArtworkStyle,+ composition?: AgentArtworkComposition,+ direction?: string,+ useReference?: boolean,+ ) => {+ // The user's own reference replaces the preset's images rather than joining+ // them: the two carry opposite instructions ("follow this character" vs+ // "borrow this look, invent a character"), and a model given both blends+ // them into neither.+ const customReference = useReference ? profile?.artworkReferenceImage : undefined;+ const commonInput = {description: meta.description,id: agentId,kind: 'avatar',name: meta.name,+ direction,referenceImageUrl: resolveAgentBackground(meta.backgroundColor),style: nextStyle,- styleReferenceImageUrls: styleReferencesForArtworkStyle(nextStyle),+ styleReferenceImageUrls: customReference+ ? [customReference]+ : styleReferencesForArtworkStyle(nextStyle, appOrigin),+ styleReferenceSource: customReference ? 'custom' : 'preset',systemRole,title: meta.title,- }).catch(() => {+ } as const;++ setGeneratingTarget(composition ?? 'both');+ try {+ const result = await generateCharacterSet({+ composition,+ currentAvatarUrl: meta.avatar,+ generate: generateAgentArtwork,+ input: commonInput,+ });+ if (result.fullBodyUrl) {+ await saveProfile({+ artworkDirection: direction?.trim() || undefined,+ artworkStyle: nextStyle,+ fullBodyArtwork: await toTransparentFullBody(result.fullBodyUrl),+ });+ }+ } catch {// The Agent store owns the persistent error state rendered below.- });+ } finally {+ setGeneratingTarget(undefined);+ }},[agentId,+ appOrigin,generateAgentArtwork,meta.backgroundColor,meta.description,+ meta.avatar,meta.name,meta.title,+ profile?.artworkReferenceImage,+ saveProfile,systemRole,+ toTransparentFullBody,],);+ /** Attaches the user's own generation reference, or clears it when called bare. */+ const changeReference = useCallback(+ async (file?: File) => {+ if (!file) {+ const { artworkReferenceImage: _cleared, ...rest } = profile ?? {};+ await updateAgentMetaById(agentId, { profile: rest });+ return;+ }++ if (file.size > MAX_AVATAR_SIZE) {+ toast.error(t('settingAgent.artwork.sizeExceeded'));+ return;+ }++ setUploading(true);+ try {+ const result = await uploadWithProgress({ file });+ if (!result?.url) throw new Error('Upload returned no URL');+ await saveProfile({ artworkReferenceImage: result.url });+ } catch (error) {+ console.error('Failed to upload artwork reference:', error);+ toast.error(t('settingAgent.artwork.uploadFailed'));+ } finally {+ setUploading(false);+ }+ },+ [agentId, profile, saveProfile, t, updateAgentMetaById, uploadWithProgress],+ );++ const remove = useCallback(+ async (composition: AgentArtworkComposition) => {+ try {+ if (composition === 'avatar') {+ await updateAgentMetaById(agentId, { avatar: null });+ return;+ }++ // Drop the key rather than storing an empty value, so the bag keeps+ // only what the agent actually has.+ const { fullBodyArtwork: _removed, ...rest } = profile ?? {};+ await updateAgentMetaById(agentId, { profile: rest });+ } catch (error) {+ console.error('Failed to remove agent artwork:', error);+ toast.error(t('settingAgent.artwork.uploadFailed'));+ }+ },+ [agentId, profile, t, updateAgentMetaById],+ );+const upload = useCallback(- async (file: File) => {+ async (file: File, composition: AgentArtworkComposition) => {if (file.size > MAX_AVATAR_SIZE) {toast.error(t('settingAgent.artwork.sizeExceeded'));return;@@ -72,7 +205,9 @@ const AgentArtworkStudioContent = memo<AgentArtworkStudioContentProps>(({ agentItry {const result = await uploadWithProgress({ file });if (!result?.url) throw new Error('Upload returned no URL');- await updateAgentMetaById(agentId, { avatar: result.url });+ await cancelAgentArtworkGeneration(agentId);+ if (composition === 'avatar') await updateAgentMetaById(agentId, { avatar: result.url });+ else await saveProfile({ fullBodyArtwork: result.url });} catch (error) {console.error('Failed to upload agent avatar:', error);toast.error(t('settingAgent.artwork.uploadFailed'));@@ -80,21 +215,34 @@ const AgentArtworkStudioContent = memo<AgentArtworkStudioContentProps>(({ agentIsetUploading(false);}},- [agentId, t, updateAgentMetaById, uploadWithProgress],+ [+ agentId,+ cancelAgentArtworkGeneration,+ saveProfile,+ t,+ updateAgentMetaById,+ uploadWithProgress,+ ],);return (<ArtworkStudioContentavatar={meta.avatar}- diyHint={t('settingAgent.artwork.studio.diyHint')}- generateHint={t('settingAgent.artwork.studio.generateHint')}+ fullBody={fullBody}generating={generating}+ generatingTarget={generatingTarget}generatingTitle={t('settingAgent.artwork.avatar.generating')}generationFailed={generationFailed}+ hasStoredAvatar={!!storedAvatar}+ initialDirection={profile?.artworkDirection}+ initialStyle={profile?.artworkStyle}+ referenceImage={profile?.artworkReferenceImage}uploading={uploading}onCancel={() => void cancelAgentArtworkGeneration(agentId)}onGenerate={generate}- onUpload={(file) => void upload(file)}+ onReferenceChange={(file) => void changeReference(file)}+ onRemove={(composition) => void remove(composition)}+ onUpload={(file, composition) => void upload(file, composition)}/>);});diff --git a/src/features/AgentArtworkStudio/generateCharacterSet.test.ts b/src/features/AgentArtworkStudio/generateCharacterSet.test.tsnew file mode 100644index 00000000000..7a8dc51fe99--- /dev/null+++ b/src/features/AgentArtworkStudio/generateCharacterSet.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it, vi } from 'vitest';++import { generateCharacterSet } from './generateCharacterSet';++const input = {+ id: 'agent-1',+ kind: 'avatar' as const,+ style: 'anime' as const,+ styleReferenceImageUrls: ['https://example.com/anime-style.webp'],+};++describe('generateCharacterSet', () => {+ it('generates the avatar first and uses it as the full-body character reference', async () => {+ const generate = vi+ .fn()+ .mockResolvedValueOnce('https://example.com/generated-avatar.webp')+ .mockResolvedValueOnce('https://example.com/generated-full-body.webp');++ const result = await generateCharacterSet({ generate, input });++ expect(generate).toHaveBeenNthCalledWith(1, { ...input, composition: 'avatar' });+ expect(generate).toHaveBeenNthCalledWith(2, {+ ...input,+ composition: 'fullBody',+ persist: false,+ referenceImageUrl: 'https://example.com/generated-avatar.webp',+ styleReferenceImageUrls: undefined,+ });+ expect(result.fullBodyUrl).toBe('https://example.com/generated-full-body.webp');+ });++ it('uses the current avatar when only the full-body image is generated', async () => {+ const generate = vi.fn().mockResolvedValue('https://example.com/generated-full-body.webp');++ await generateCharacterSet({+ composition: 'fullBody',+ currentAvatarUrl: 'https://example.com/current-avatar.webp',+ generate,+ input,+ });++ expect(generate).toHaveBeenCalledOnce();+ expect(generate).toHaveBeenCalledWith(+ expect.objectContaining({+ composition: 'fullBody',+ referenceImageUrl: 'https://example.com/current-avatar.webp',+ styleReferenceImageUrls: undefined,+ }),+ );+ });+});diff --git a/src/features/AgentArtworkStudio/generateCharacterSet.ts b/src/features/AgentArtworkStudio/generateCharacterSet.tsnew file mode 100644index 00000000000..ce790bd2f7c--- /dev/null+++ b/src/features/AgentArtworkStudio/generateCharacterSet.ts@@ -0,0 +1,40 @@+import type { AgentArtworkComposition, AgentArtworkPromptInput } from '@lobechat/prompts';++interface GenerateCharacterArtworkInput extends AgentArtworkPromptInput {+ persist?: boolean;+}++interface GenerateCharacterSetOptions {+ composition?: AgentArtworkComposition;+ currentAvatarUrl?: string | null;+ generate: (input: GenerateCharacterArtworkInput) => Promise<string | undefined>;+ input: AgentArtworkPromptInput;+}++export const generateCharacterSet = async ({+ composition,+ currentAvatarUrl,+ generate,+ input,+}: GenerateCharacterSetOptions) => {+ let avatarUrl = currentAvatarUrl || undefined;++ if (!composition || composition === 'avatar') {+ const generatedAvatarUrl = await generate({ ...input, composition: 'avatar' });+ if (generatedAvatarUrl) avatarUrl = generatedAvatarUrl;+ }++ if (!composition || composition === 'fullBody') {+ const fullBodyUrl = await generate({+ ...input,+ composition: 'fullBody',+ persist: false,+ referenceImageUrl: avatarUrl || input.referenceImageUrl,+ styleReferenceImageUrls: avatarUrl ? undefined : input.styleReferenceImageUrls,+ });++ return { avatarUrl, fullBodyUrl };+ }++ return { avatarUrl, fullBodyUrl: undefined };+};diff --git a/src/features/AgentArtworkStudio/index.tsx b/src/features/AgentArtworkStudio/index.tsxindex b7a32021e4e..f46775a4713 100644--- a/src/features/AgentArtworkStudio/index.tsx+++ b/src/features/AgentArtworkStudio/index.tsx@@ -8,8 +8,8 @@ import AgentArtworkStudioContent from './Content';export { styleReferencesForArtworkStyle } from '@/features/ArtworkStudio';/**- * Large avatar workshop for one agent: make your own (upload) or one-click- * generate in the official style. Reads everything from the agent store, so+ * Character workshop for one agent: upload an image or generate either an+ * avatar or full-body composition. Reads everything from the agent store, so* any surface that knows an agent id can open it.*/export const openAgentArtworkStudio = (agentId: string): ModalInstance =>@@ -17,6 +17,7 @@ export const openAgentArtworkStudio = (agentId: string): ModalInstance =>content: <AgentArtworkStudioContent agentId={agentId} />,footer: null,maskClosable: true,+ styles: { content: { paddingBlockStart: 0 } },title: t('settingAgent.artwork.studio.title', { ns: 'setting' }),- width: 'min(92vw, 820px)',+ width: 'min(94vw, 920px)',});diff --git a/src/features/AgentProfileArtwork/index.tsx b/src/features/AgentProfileArtwork/index.tsxindex 57e9068bc85..6b609d7ce64 100644--- a/src/features/AgentProfileArtwork/index.tsx+++ b/src/features/AgentProfileArtwork/index.tsx@@ -18,6 +18,7 @@ import {openAgentArtworkStudio,styleReferencesForArtworkStyle,} from '@/features/AgentArtworkStudio';+import { useAppOrigin } from '@/hooks/useAppOrigin';import { useAgentStore } from '@/store/agent';import { agentArtworkSelectors } from '@/store/agent/selectors';import { useAiInfraStore } from '@/store/aiInfra';@@ -211,6 +212,7 @@ export const AgentProfileArtwork = memo<AgentProfileArtworkProps>(onBackgroundChange,}) => {const { t } = useTranslation('setting');+ const appOrigin = useAppOrigin();const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);const canGenerate = useAiInfraStore((state) => aiProviderSelectors.enabledImageModelList(state).length > 0,@@ -273,7 +275,7 @@ export const AgentProfileArtwork = memo<AgentProfileArtworkProps>(name,referenceImageUrl: kind === 'background' ? avatar : backgroundUrl,style,- styleReferenceImageUrls: styleReferencesForArtworkStyle(style),+ styleReferenceImageUrls: styleReferencesForArtworkStyle(style, appOrigin),systemRole,title,});@@ -283,6 +285,7 @@ export const AgentProfileArtwork = memo<AgentProfileArtworkProps>(},[agentId,+ appOrigin,avatar,backgroundUrl,canEdit,diff --git a/src/features/ArtworkStudio/Content.tsx b/src/features/ArtworkStudio/Content.tsxindex a63b1c2fab4..c44361f4fad 100644--- a/src/features/ArtworkStudio/Content.tsx+++ b/src/features/ArtworkStudio/Content.tsx@@ -1,66 +1,105 @@'use client';import { imageUrl } from '@lobechat/const';+import type { AgentArtworkComposition, AgentArtworkStyle } from '@lobechat/prompts';+import { AGENT_ARTWORK_STYLES } from '@lobechat/prompts';import {- AGENT_ARTWORK_STYLES,- type AgentArtworkStyle,- DEFAULT_AGENT_ARTWORK_STYLE,-} from '@lobechat/prompts';-import { Avatar, Center, Flexbox, Icon, Tag, Text } from '@lobehub/ui';+ Accordion,+ AccordionItem,+ ActionIcon,+ Avatar,+ Center,+ Flexbox,+ Icon,+ Input,+ Text,+} from '@lobehub/ui';import { Alert, 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 {+ CircleUserRound,+ Frame,+ ImagePlus,+ PersonStanding,+ SettingsIcon,+ Trash2,+ UploadIcon,+ WandSparkles,+} from 'lucide-react';+import { memo, type MouseEvent, useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';import { avatarRemountKey, openFilePicker } from '@/features/AgentProfileArtwork/utils';+import { CHIEF_AGENT_ARTWORKS, DEFAULT_CHIEF_AGENT_ARTWORK } from '@/features/ChiefAgent/artwork';+import { HOME_PORTRAIT_VISIBLE_RATIO } from '@/features/Home/portraitFraming';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;+const LOBE_STYLE_PREVIEW =+ CHIEF_AGENT_ARTWORKS.find((item) => item.id === 'sienna')?.avatar ??+ DEFAULT_CHIEF_AGENT_ARTWORK.avatar;-const GALLERY_STYLES = AGENT_ARTWORK_STYLES.filter((item) => item !== 'lobe');+/**+ * The avatar fills its own grid column and the full-body slot stretches to the+ * same row height, so the pair sizes with the modal instead of a fixed number.+ * This is the breathing room left around the avatar inside its frame.+ */+const AVATAR_INSET = 40;+/** Default slot size; the pair shrinks below it on a narrower modal. */+const PREVIEW_MAX_SIZE = 240;+/**+ * The style gallery is a picker, not content. At full-bleed thumbnail size its+ * five saturated images outweighed the artwork the modal is actually about, so+ * it is sized as a control strip.+ */+const STYLE_THUMB_SIZE = 64;+const GENERATE_SECTION_KEY = 'generate';+/**+ * Vertical breathing room inside the full-body slot. The avatar gets a much+ * larger inset because a head reads fine small; a full body needs the height,+ * so this only keeps the character off the frame's edge.+ */+const FULL_BODY_INSET = 12;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;+ display: flex;+ flex-wrap: wrap;+ gap: 12px;+ align-items: start;`,galleryItem: css`cursor: pointer;++ width: ${STYLE_THUMB_SIZE + 8}px;+ padding: 4px;+ border: 1px solid transparent;border-radius: ${cssVar.borderRadiusLG};+ transition:+ border-color ${cssVar.motionDurationFast},+ background ${cssVar.motionDurationFast};+&:hover img {filter: brightness(1.06);}`,+ galleryItemActive: css`+ border-color: ${cssVar.colorPrimary};+ background: ${cssVar.colorFillTertiary};+ `,galleryLabel: css`font-size: 12px;+ line-height: 16px;color: ${cssVar.colorTextSecondary};text-align: center;`,galleryThumb: css`aspect-ratio: 1;- width: 100%;+ width: ${STYLE_THUMB_SIZE}px;border-radius: ${cssVar.borderRadiusLG};object-fit: cover;@@ -70,55 +109,215 @@ const styles = createStaticStyles(({ css }) => ({galleryThumbWrap: css`position: relative;`,+ /** Empty state of the custom-reference tile: same footprint as a thumbnail. */+ referenceEmpty: css`+ aspect-ratio: 1;+ width: ${STYLE_THUMB_SIZE}px;+ border: 1px dashed ${cssVar.colorBorder};+ border-radius: ${cssVar.borderRadiusLG};++ color: ${cssVar.colorTextTertiary};+ `,+ referenceRemove: css`+ position: absolute;+ z-index: 1;+ inset-block-start: 2px;+ inset-inline-end: 2px;++ opacity: 0;+ background: color-mix(in srgb, ${cssVar.colorBgContainer} 72%, transparent);+ backdrop-filter: blur(8px);++ transition: opacity ${cssVar.motionDurationFast};++ *:hover > & {+ opacity: 1;+ }+ `,generationOverlay: css`position: absolute;z-index: 2;inset: 0;+ padding: 12px;border-radius: calc(${cssVar.borderRadiusLG} - 1px);background: color-mix(in srgb, ${cssVar.colorBgContainer} 88%, transparent);backdrop-filter: blur(12px);`,+ generationOverlayTitle: css`+ overflow: hidden;+ display: -webkit-box;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 2;++ font-size: 13px;+ font-weight: 500;+ line-height: 18px;+ text-align: center;+ `,hint: css`font-size: 13px;color: ${cssVar.colorTextSecondary};`,- lobeCard: css`- cursor: pointer;+ noModelBlock: css`border-radius: ${cssVar.borderRadiusLG};background: ${cssVar.colorFillQuaternary};- transition: background ${cssVar.motionDurationFast};-- &:hover {- background: ${cssVar.colorFillTertiary};- }`,- lobeCardActive: css`- background: ${cssVar.colorFillSecondary};+ outputCard: css`+ cursor: pointer;+ padding-block: 0;+ padding-inline: 8px;+ `,+ /**+ * Upload / generate / remove live on the artwork and only appear on hover or+ * keyboard focus, so a settled slot is just the character.+ *+ * Filled buttons are translucent by design, so the row carries its own scrim:+ * a bottom-up fade that darkens whatever the character puts behind the labels+ * without boxing the buttons in a panel.+ */+ outputActions: css`+ position: absolute;+ z-index: 2;+ inset-block-end: 0;+ inset-inline: 0;- &:hover {- background: ${cssVar.colorFillSecondary};- }+ padding-block: 40px 10px;+ padding-inline: 10px;++ opacity: 0;+ background: linear-gradient(+ to top,+ ${cssVar.colorBgContainer} 0%,+ color-mix(in srgb, ${cssVar.colorBgContainer} 76%, transparent) 46%,+ transparent 100%+ );++ transition: opacity ${cssVar.motionDurationMid};`,- noModelBlock: css`- border-radius: ${cssVar.borderRadiusLG};- background: ${cssVar.colorFillQuaternary};+ outputColumn: css`+ width: 100%;+ height: 100%;`,- preview: css`+ outputGrid: css`+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 24px;+ align-items: stretch;+ `,+ outputPreview: css`position: relative;overflow: hidden;- flex: none;border: 1px solid ${cssVar.colorBorderSecondary};border-radius: ${cssVar.borderRadiusLG};- background: ${cssVar.colorFillQuaternary};+ background: ${cssVar.colorBgContainer};++ &:hover [data-slot-actions],+ &:focus-within [data-slot-actions] {+ opacity: 1;+ }+ `,+ /**+ * Square, and as wide as the column allows up to its default size — this sets+ * the row height, and shrinks with the modal rather than pinning a number.+ */+ outputPreviewAvatar: css`+ aspect-ratio: 1;+ width: 100%;+ max-width: ${PREVIEW_MAX_SIZE}px;+ `,+ /** Matches the avatar's height; its own ratio then decides the width. */+ /**+ * Matches the avatar's height — same cap, so the pair stays level — and its+ * own ratio then decides the width.+ */+ outputPreviewFullBody: css`+ aspect-ratio: 3 / 4;+ max-width: 100%;+ height: 100%;+ max-height: ${PREVIEW_MAX_SIZE}px;+ `,+ /**+ * Breathing room so the head is not pinned to the slot's top edge. Far less+ * than the avatar's inset — a full body wants the height — but enough that the+ * slot reads as a frame around the character rather than a crop of it.+ */+ previewBodyImage: css`+ box-sizing: border-box;+ width: 100%;+ height: 100%;+ padding-block: ${FULL_BODY_INSET}px;++ object-fit: contain;+ `,+ /**+ * Dashed marker for the share of the character the home surface actually+ * shows, so framing can be judged here instead of by walking to home.+ */+ framePreview: css`+ pointer-events: none;++ position: absolute;+ z-index: 3;+ inset-block-start: ${FULL_BODY_INSET}px;+ inset-inline: ${FULL_BODY_INSET}px;++ height: calc((100% - ${FULL_BODY_INSET * 2}px) * ${HOME_PORTRAIT_VISIBLE_RATIO});+ border: 1px dashed ${cssVar.colorTextSecondary};+ border-radius: ${cssVar.borderRadiusSM};+ `,+ framePreviewLabel: css`+ position: absolute;+ inset-block-end: 4px;+ inset-inline-end: 6px;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 11px;+ line-height: 14px;+ color: ${cssVar.colorTextSecondary};+ `,+ frameToggle: css`+ position: absolute;+ z-index: 4;+ inset-block-start: 8px;+ inset-inline-start: 8px;++ opacity: 0;+ background: color-mix(in srgb, ${cssVar.colorBgContainer} 72%, transparent);+ backdrop-filter: blur(8px);++ transition: opacity ${cssVar.motionDurationMid};+ `,+ controlLabel: css`+ font-size: 12px;+ line-height: 16px;+ color: ${cssVar.colorTextTertiary};+ `,+ removeButton: css`+ position: absolute;+ z-index: 2;+ inset-block-start: 8px;+ inset-inline-end: 8px;++ opacity: 0;+ background: color-mix(in srgb, ${cssVar.colorBgContainer} 72%, transparent);+ backdrop-filter: blur(8px);++ transition: opacity ${cssVar.motionDurationMid};`,sectionTitle: css`font-weight: 500;`,+ uploadSpec: css`+ font-size: 12px;+ line-height: 16px;+ color: ${cssVar.colorTextQuaternary};+ text-align: center;+ `,visuallyHiddenInput: css`pointer-events: none;@@ -136,38 +335,103 @@ const styles = createStaticStyles(({ css }) => ({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;+ /** Current or freshly generated full-body artwork. */+ fullBody?: string | null;generating?: boolean;+ generatingTarget?: AgentArtworkComposition | 'both';/** Headline shown over the preview while a generation runs. */generatingTitle: string;/** True when the last generation attempt failed and can be retried. */generationFailed?: boolean;+ /**+ * True when the subject has an avatar of its own. Separate from `avatar`,+ * which falls back to a default so the slot is never blank — there is+ * nothing to remove when only the fallback is showing.+ */+ hasStoredAvatar?: boolean;+ /** Free-text direction the subject was last generated with. */+ initialDirection?: string;+ /** Style preset the subject was last generated with. */+ initialStyle?: string;onCancel: () => void;- onGenerate: (style: AgentArtworkStyle) => void;- onUpload: (file: File) => void;+ onGenerate: (+ style: AgentArtworkStyle,+ composition?: AgentArtworkComposition,+ direction?: string,+ /** True when the user's own reference should drive the character. */+ useReference?: boolean,+ ) => void;+ /** Attaches (or clears, with `undefined`) the user's own generation reference. */+ onReferenceChange: (file?: File) => void;+ /** Clears the artwork in one slot. */+ onRemove: (composition: AgentArtworkComposition) => void;+ onUpload: (file: File, composition: AgentArtworkComposition) => void;+ /**+ * The user's own reference image, if they attached one. Selecting it makes a+ * generation follow that character instead of a style preset.+ */+ referenceImage?: string | null;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.+ * Artwork workshop shared by every subject that can own one (Agents, workspaces).+ * The same underlying image is shown in its two product crops so users can+ * choose the intended generation composition without hiding either result.*/+/**+ * The avatar sizes itself off the slot rather than a fixed pixel value, so the+ * pair keeps its proportions as the modal grows.+ */+const AvatarSlotImage = memo<{ avatar?: string | null }>(({ avatar }) => {+ const ref = useRef<HTMLDivElement>(null);+ const [size, setSize] = useState(0);++ useEffect(() => {+ const node = ref.current;+ if (!node) return;++ const observer = new ResizeObserver(([entry]) => {+ setSize(Math.max(0, Math.round(entry.contentRect.width) - AVATAR_INSET));+ });+ observer.observe(node);++ return () => observer.disconnect();+ }, []);++ return (+ <Center height={'100%'} ref={ref} width={'100%'}>+ {size > 0 ? (+ <Avatar+ avatar={avatar || undefined}+ key={avatarRemountKey(avatar)}+ shape={'square'}+ size={size}+ />+ ) : null}+ </Center>+ );+});++AvatarSlotImage.displayName = 'AvatarSlotImage';+const ArtworkStudioContent = memo<ArtworkStudioContentProps>(({avatar,- diyHint,- generateHint,+ fullBody,generatingTitle,generating,+ generatingTarget,generationFailed,+ hasStoredAvatar,+ initialDirection,+ initialStyle,onCancel,onGenerate,+ onRemove,+ onReferenceChange,onUpload,+ referenceImage,uploading,}) => {const { t } = useTranslation('setting');@@ -177,10 +441,29 @@ const ArtworkStudioContent = memo<ArtworkStudioContentProps>((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 avatarInputRef = useRef<HTMLInputElement>(null);+ const fullBodyInputRef = useRef<HTMLInputElement>(null);+ const referenceInputRef = useRef<HTMLInputElement>(null);+ // Off by default: the frame is a measuring tool, and leaving it drawn over+ // every artwork would make the slot read as cropped.+ const [showFramePreview, setShowFramePreview] = useState(false);+ // Resume the subject's own last choice; a preset that no longer exists+ // falls back rather than leaving the gallery with nothing selected.+ const [style, setStyle] = useState<AgentArtworkStyle>(() =>+ GALLERY_STYLES.includes(initialStyle as AgentArtworkStyle)+ ? (initialStyle as AgentArtworkStyle)+ : 'anime',+ );+ const [direction, setDirection] = useState(initialDirection ?? '');+ const [generateExpanded, setGenerateExpanded] = useState(true);+ // The gallery picks one source for the character: a preset, or the user's own+ // reference. Keeping the preset selected underneath means clearing the+ // reference lands back where they were instead of on nothing.+ const [useReference, setUseReference] = useState(false);+ const selectStyle = useCallback((next: AgentArtworkStyle) => {+ setStyle(next);+ setUseReference(false);+ }, []);const keySelect = useCallback((next: AgentArtworkStyle) => (event: { key: string; preventDefault: () => void }) => {@@ -192,183 +475,345 @@ const ArtworkStudioContent = memo<ArtworkStudioContentProps>([],);+ const isGenerating = (composition: AgentArtworkComposition) =>+ !!generating && (generatingTarget === composition || generatingTarget === 'both');++ // The slot is only ~200px wide, so the overlay carries the headline and the+ // cancel affordance; the duration hint sits under the row where it has space.+ // Sits on the preview rather than in the button row: removal is rare next to+ // upload and generate, and a third button crowded the ~200px column.+ const renderRemove = (composition: AgentArtworkComposition, hasImage: boolean) =>+ hasImage && !isGenerating(composition) ? (+ <ActionIcon+ data-slot-actions+ className={styles.removeButton}+ icon={Trash2}+ size={'small'}+ title={t('artworkStudio.remove')}+ onClick={(event: MouseEvent<HTMLDivElement>) => {+ event.stopPropagation();+ onRemove(composition);+ }}+ />+ ) : null;++ const renderGenerationOverlay = (composition: AgentArtworkComposition) =>+ isGenerating(composition) ? (+ <Center className={styles.generationOverlay} gap={8}>+ <NeuralNetworkLoading size={28} />+ <Text className={styles.generationOverlayTitle}>{generatingTitle}</Text>+ <Button size={'small'} type={'fill'} onClick={onCancel}>+ {t('artworkStudio.cancel')}+ </Button>+ </Center>+ ) : null;+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 gap={24} padding={24}>+ <div className={styles.outputGrid}>+ <Flexbox+ align={'center'}+ className={styles.outputCard}+ gap={10}+ role={'button'}+ tabIndex={0}+ onClick={() => avatarInputRef.current && openFilePicker(avatarInputRef.current)}+ onKeyDown={(event) => {+ if (event.key === 'Enter' || event.key === ' ') {+ event.preventDefault();+ if (avatarInputRef.current) openFilePicker(avatarInputRef.current);+ }+ }}+ >+ <Flexbox horizontal align={'center'} gap={6}>+ <Icon icon={CircleUserRound} size={16} />+ <Text className={styles.sectionTitle}>{t('artworkStudio.composition.avatar')}</Text>+ </Flexbox>+ <Flexbox align={'center'} className={styles.outputColumn} gap={10}>+ <Center className={`${styles.outputPreview} ${styles.outputPreviewAvatar}`}>+ <AvatarSlotImage avatar={avatar} />+ {renderRemove('avatar', !!hasStoredAvatar)}+ <Flexbox data-slot-actions horizontal className={styles.outputActions} gap={8}>+ <Button icon={UploadIcon} loading={uploading} style={{ flex: 1 }} type={'fill'}>+ {t('artworkStudio.upload')}+ </Button>+ <Button+ icon={WandSparkles}+ style={{ flex: 1 }}+ type={'fill'}+ onClick={(event) => {+ event.stopPropagation();+ onGenerate(style, 'avatar', direction, useReference);+ }}+ >+ {t('artworkStudio.generate.avatar')}+ </Button></Flexbox>+ {renderGenerationOverlay('avatar')}</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>+ <Text className={styles.uploadSpec}>{t('artworkStudio.uploadSpec.avatar')}</Text>+ </Flexbox></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' }}+ <Flexbox+ align={'center'}+ className={styles.outputCard}+ gap={10}+ role={'button'}+ tabIndex={0}+ onClick={() => fullBodyInputRef.current && openFilePicker(fullBodyInputRef.current)}+ onKeyDown={(event) => {+ if (event.key === 'Enter' || event.key === ' ') {+ event.preventDefault();+ if (fullBodyInputRef.current) openFilePicker(fullBodyInputRef.current);+ }+ }}+ >+ <Flexbox horizontal align={'center'} gap={6}>+ <Icon icon={PersonStanding} size={16} />+ <Text className={styles.sectionTitle}>{t('artworkStudio.composition.fullBody')}</Text>+ </Flexbox>+ <Flexbox align={'center'} className={styles.outputColumn} gap={10}>+ <Center className={`${styles.outputPreview} ${styles.outputPreviewFullBody}`}>+ {fullBody ? (+ <img+ alt={t('artworkStudio.preview.fullBody')}+ className={styles.previewBodyImage}+ src={fullBody}/>+ ) : (+ <Icon icon={PersonStanding} size={64} />+ )}+ {showFramePreview && fullBody ? (+ <div className={styles.framePreview}>+ <span className={styles.framePreviewLabel}>+ {Math.round(HOME_PORTRAIT_VISIBLE_RATIO * 100)}%+ </span>+ </div>) : null}- </Flexbox>-- <Flexbox gap={8}>- <Text className={styles.hint}>{t('artworkStudio.moreStyles')}</Text>- <div className={styles.galleryGrid}>- {GALLERY_STYLES.map((item) => (+ {fullBody && !isGenerating('fullBody') ? (+ <ActionIcon+ data-slot-actions+ active={showFramePreview}+ className={styles.frameToggle}+ icon={Frame}+ size={'small'}+ title={t('artworkStudio.framePreview')}+ onClick={(event: MouseEvent<HTMLDivElement>) => {+ event.stopPropagation();+ setShowFramePreview((open) => !open);+ }}+ />+ ) : null}+ {renderRemove('fullBody', !!fullBody)}+ <Flexbox data-slot-actions horizontal className={styles.outputActions} gap={8}>+ <Button icon={UploadIcon} loading={uploading} style={{ flex: 1 }} type={'fill'}>+ {t('artworkStudio.upload')}+ </Button>+ <Button+ icon={WandSparkles}+ style={{ flex: 1 }}+ type={'fill'}+ onClick={(event) => {+ event.stopPropagation();+ onGenerate(style, 'fullBody', direction, useReference);+ }}+ >+ {t('artworkStudio.generate.fullBody')}+ </Button>+ </Flexbox>+ {renderGenerationOverlay('fullBody')}+ </Center>+ <Text className={styles.uploadSpec}>{t('artworkStudio.uploadSpec.fullBody')}</Text>+ </Flexbox>+ </Flexbox>+ </div>++ {generating ? (+ <Text className={styles.hint} style={{ textAlign: 'center' }}>+ {t('artworkStudio.generatingHint')}+ </Text>+ ) : null}++ {canGenerate ? (+ <>+ <Accordion+ expandedKeys={generateExpanded ? [GENERATE_SECTION_KEY] : []}+ gap={4}+ onExpandedChange={(keys) => setGenerateExpanded(keys.length > 0)}+ >+ <AccordionItem+ itemKey={GENERATE_SECTION_KEY}+ paddingBlock={2}+ paddingInline={0}+ title={+ <Text className={styles.controlLabel}>{t('artworkStudio.generateTitle')}</Text>+ }+ >+ <Flexbox gap={12} paddingBlock={'4px 0'}>+ <div className={styles.galleryGrid}>+ {GALLERY_STYLES.map((item) => (+ <Flexbox+ className={`${styles.galleryItem} ${style === item && !useReference ? styles.galleryItemActive : ''}`}+ 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={+ item === 'lobe'+ ? LOBE_STYLE_PREVIEW+ : imageUrl(`agent-artwork-styles/style-${item}.webp`)+ }+ />+ </div>+ <Text ellipsis className={styles.galleryLabel}>+ {t(`artworkStudio.style.${item}`)}+ </Text>+ </Flexbox>+ ))}+ {/*+ A preset says "look like this kind of art"; this says "look+ like THIS character". It sits in the same row because it is+ the same choice — what the generation follows — and only one+ of them can be in effect.+ */}<Flexbox- className={styles.galleryItem}+ className={`${styles.galleryItem} ${useReference ? styles.galleryItemActive : ''}`}gap={6}- key={item}role={'button'}tabIndex={0}- onClick={() => selectStyle(item)}- onKeyDown={keySelect(item)}+ onClick={() =>+ referenceImage+ ? setUseReference(true)+ : referenceInputRef.current && openFilePicker(referenceInputRef.current)+ }+ onKeyDown={(event) => {+ if (event.key !== 'Enter' && event.key !== ' ') return;+ event.preventDefault();+ if (referenceImage) setUseReference(true);+ else if (referenceInputRef.current)+ openFilePicker(referenceInputRef.current);+ }}><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} />+ {referenceImage ? (+ <>+ <img+ alt={t('artworkStudio.reference.title')}+ className={styles.galleryThumb}+ src={referenceImage}+ />+ <ActionIcon+ className={styles.referenceRemove}+ icon={Trash2}+ size={'small'}+ title={t('artworkStudio.reference.remove')}+ onClick={(event: MouseEvent<HTMLDivElement>) => {+ event.stopPropagation();+ setUseReference(false);+ onReferenceChange();+ }}+ />+ </>+ ) : (+ <Center className={styles.referenceEmpty}>+ <Icon icon={ImagePlus} size={18} /></Center>- ) : null}+ )}</div><Text ellipsis className={styles.galleryLabel}>- {t(`artworkStudio.style.${item}`)}+ {t('artworkStudio.reference.title')}</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>+ </div>+ <Input+ disabled={generating}+ placeholder={t('artworkStudio.direction.placeholder')}+ value={direction}+ onChange={(event) => setDirection(event.target.value)}+ />+ <Flexbox horizontal>+ <Button+ disabled={generating}+ icon={WandSparkles}+ type={'fill'}+ onClick={() => onGenerate(style, undefined, direction, useReference)}+ >+ {t('artworkStudio.generate.characterSet')}+ </Button>+ </Flexbox>+ {generationFailed ? (+ <Alert showIcon title={t('artworkStudio.generateFailed')} type={'error'} />+ ) : null}+ </Flexbox>+ </AccordionItem>+ </Accordion>+ </>+ ) : (+ <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={'fill'}+ onClick={() => {+ close();+ navigate('/settings/provider/all');+ }}+ >+ {t('artworkStudio.enableModel')}+ </Button>+ </Center>+ )}<inputaccept="image/*"aria-label={t('artworkStudio.upload')}className={styles.visuallyHiddenInput}- ref={uploadInputRef}+ ref={avatarInputRef}+ tabIndex={-1}+ type="file"+ onChange={(event) => {+ const file = event.target.files?.[0];+ event.target.value = '';+ if (file) onUpload(file, 'avatar');+ }}+ />+ <input+ accept="image/*"+ aria-label={t('artworkStudio.upload')}+ className={styles.visuallyHiddenInput}+ ref={fullBodyInputRef}+ tabIndex={-1}+ type="file"+ onChange={(event) => {+ const file = event.target.files?.[0];+ event.target.value = '';+ if (file) onUpload(file, 'fullBody');+ }}+ />+ <input+ accept="image/*"+ aria-label={t('artworkStudio.reference.title')}+ className={styles.visuallyHiddenInput}+ ref={referenceInputRef}tabIndex={-1}type="file"onChange={(event) => {const file = event.target.files?.[0];event.target.value = '';- if (file) onUpload(file);+ if (!file) return;+ // Attaching one is also choosing it — nobody uploads a reference+ // they did not want the next generation to follow.+ setUseReference(true);+ onReferenceChange(file);}}/></Flexbox>diff --git a/src/features/ArtworkStudio/styleReferences.test.ts b/src/features/ArtworkStudio/styleReferences.test.tsnew file mode 100644index 00000000000..0e8645188f6--- /dev/null+++ b/src/features/ArtworkStudio/styleReferences.test.ts@@ -0,0 +1,18 @@+import { describe, expect, it } from 'vitest';++import { styleReferencesForArtworkStyle } from './styleReferences';++describe('styleReferencesForArtworkStyle', () => {+ it('uses the provided app origin for the line-art reference', () => {+ const appOrigin = 'https://self-hosted.example.com:8443';+ const references = styleReferencesForArtworkStyle('lineArt', appOrigin);+ const reference = references?.[0];++ expect(reference).toBe(`${appOrigin}/app-images/agent-artwork-styles/line-art-reference.webp`);+ expect(new URL(reference!).origin).toBe(appOrigin);+ });++ it('omits the line-art reference until an app origin is available', () => {+ expect(styleReferencesForArtworkStyle('lineArt')).toBeUndefined();+ });+});diff --git a/src/features/ArtworkStudio/styleReferences.ts b/src/features/ArtworkStudio/styleReferences.tsindex c2825925212..12b07105342 100644--- a/src/features/ArtworkStudio/styleReferences.ts+++ b/src/features/ArtworkStudio/styleReferences.ts@@ -1,3 +1,4 @@+import { imageUrl } from '@lobechat/const';import type { AgentArtworkStyle } from '@lobechat/prompts';import { CHIEF_AGENT_ARTWORKS } from '@/features/ChiefAgent/artwork';@@ -13,5 +14,15 @@ export const LOBE_STYLE_REFERENCE_IMAGE_URLS = CHIEF_AGENT_ARTWORKS.filter((itemREFERENCE_IDS.has(item.id),).map((item) => item.avatar);-export const styleReferencesForArtworkStyle = (style: AgentArtworkStyle): string[] | undefined =>- style === 'lobe' ? LOBE_STYLE_REFERENCE_IMAGE_URLS : undefined;+const lineArtReferenceImageUrl = (appOrigin: string) =>+ new URL(imageUrl('agent-artwork-styles/line-art-reference.webp'), appOrigin).toString();++export const styleReferencesForArtworkStyle = (+ style: AgentArtworkStyle,+ appOrigin?: string,+): string[] | undefined =>+ style === 'lobe'+ ? LOBE_STYLE_REFERENCE_IMAGE_URLS+ : style === 'lineArt' && appOrigin+ ? [lineArtReferenceImageUrl(appOrigin)]+ : undefined;diff --git a/src/features/Home/HomePortrait.tsx b/src/features/Home/HomePortrait.tsxindex 0363838a9aa..3453e80bff2 100644--- a/src/features/Home/HomePortrait.tsx+++ b/src/features/Home/HomePortrait.tsx@@ -4,22 +4,35 @@ import { memo } from 'react';import { resolveChiefAgentArtwork } from '@/features/ChiefAgent/artwork';import { useAgentStore } from '@/store/agent';-import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';+import { agentSelectors } from '@/store/agent/selectors';++import { useResolvedHomeAgentId } from './AgentSelect/useResolvedHomeAgentId';const styles = createStaticStyles(({ css }) => ({- // Anchored below the greeting row rather than above the rail, so the agent- // stands the same distance into the first card however the greeting wraps.+ /**+ * One frame for every character. Generated artwork arrives cropped to the+ * subject, and the built-in catalog draws its character across the frame with+ * a few percent of margin, so sizing by height lands both at the same stature.+ * Anchored deep enough that the lower body passes behind the first card — the+ * character leans on the surface instead of standing on it. The offset is what+ * sets how much shows: 94px leaves `HOME_PORTRAIT_VISIBLE_RATIO` of the+ * character above the card (see ./portraitFraming), which clears the catalog+ * mascot's head — it is half its own height — and reaches the hem on a+ * standing figure, where 57% cut both at the collar and the waist. Change one+ * and the studio's preview frame stops matching what home shows.+ */image: css`pointer-events: none;position: absolute;- inset-block-end: -64px;+ inset-block-end: -94px;inset-inline-end: 12px;- width: 152px;- height: 152px;+ width: 176px;+ height: 200px;object-fit: contain;+ object-position: bottom;`,root: css`position: relative;@@ -28,13 +41,24 @@ const styles = createStaticStyles(({ css }) => ({}));const HomePortrait = memo(() => {- const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);- const inboxMeta = useAgentStore(agentSelectors.getAgentMetaById(inboxAgentId ?? ''));- const artwork = resolveChiefAgentArtwork(inboxMeta.avatar || DEFAULT_INBOX_AVATAR);+ // The portrait depicts whoever home is addressing, so it follows the same+ // selection the composer sends to — not the Inbox Agent it defaults to.+ const { agentId } = useResolvedHomeAgentId();+ const useFetchAgentConfig = useAgentStore((s) => s.useFetchAgentConfig);+ // A freshly picked agent may not be in the store yet; without this the+ // portrait would silently stay on the previous one's artwork.+ useFetchAgentConfig(true, agentId ?? '');++ const meta = useAgentStore(agentSelectors.getAgentMetaById(agentId ?? ''));+ // An agent that has been through the artwork studio shows its own character;+ // the built-in catalog covers everyone else.+ const fullBodyArtwork = useAgentStore(agentSelectors.getAgentFullBodyArtworkById(agentId ?? ''));+ const artwork = resolveChiefAgentArtwork(meta.avatar || DEFAULT_INBOX_AVATAR);+ const hero = fullBodyArtwork || artwork.hero;return (<div className={styles.root}>- <img aria-hidden alt="" className={styles.image} src={artwork.hero} />+ <img aria-hidden alt="" className={styles.image} key={hero} src={hero} /></div>);});diff --git a/src/features/Home/portraitFraming.ts b/src/features/Home/portraitFraming.tsnew file mode 100644index 00000000000..9657af5a84d--- /dev/null+++ b/src/features/Home/portraitFraming.ts@@ -0,0 +1,13 @@+/**+ * How much of the character the home surface actually shows.+ *+ * The home portrait hangs below its container so the lower body passes behind+ * the first card; what survives that overlap is this fraction of the character's+ * height, measured against the real layout (image box 200px tall, card top+ * 130px below the image's top edge).+ *+ * It lives here rather than inside the stylesheet because the artwork studio+ * draws the same fraction as a preview frame — if the two ever disagree, the+ * preview is lying about where home will cut.+ */+export const HOME_PORTRAIT_VISIBLE_RATIO = 0.65;diff --git a/src/services/artworkGeneration/cutOutFlatBackground.test.ts b/src/services/artworkGeneration/cutOutFlatBackground.test.tsnew file mode 100644index 00000000000..25a03e350fc--- /dev/null+++ b/src/services/artworkGeneration/cutOutFlatBackground.test.ts@@ -0,0 +1,135 @@+import { describe, expect, it } from 'vitest';++import { cutOutFlatBackground, type RgbaImage, subjectBounds } from './cutOutFlatBackground';++interface Rgb {+ b: number;+ g: number;+ r: number;+}++const ORANGE: Rgb = { b: 40, g: 100, r: 230 };+const SKIN: Rgb = { b: 150, g: 190, r: 240 };+const WHITE: Rgb = { b: 255, g: 255, r: 255 };++/** Paints a flat backdrop with a centered opaque block standing in for the character. */+const makeImage = (+ size: number,+ backdrop: Rgb,+ subject: Rgb,+ subjectInset = Math.floor(size / 4),+): RgbaImage => {+ const data = new Uint8ClampedArray(size * size * 4);++ for (let y = 0; y < size; y += 1) {+ for (let x = 0; x < size; x += 1) {+ const inside =+ x >= subjectInset &&+ x < size - subjectInset &&+ y >= subjectInset &&+ y < size - subjectInset;+ const color = inside ? subject : backdrop;+ const offset = (y * size + x) * 4;+ data[offset] = color.r;+ data[offset + 1] = color.g;+ data[offset + 2] = color.b;+ data[offset + 3] = 255;+ }+ }++ return { data, height: size, width: size };+};++const alphaAt = ({ data, width }: RgbaImage, x: number, y: number) => data[(y * width + x) * 4 + 3];++describe('cutOutFlatBackground', () => {+ it('clears the flat backdrop and keeps the character opaque', () => {+ const image = makeImage(40, ORANGE, SKIN);++ const result = cutOutFlatBackground(image);++ expect(result.applied).toBe(true);+ expect(alphaAt(image, 0, 0)).toBe(0);+ expect(alphaAt(image, 39, 39)).toBe(0);+ expect(alphaAt(image, 20, 20)).toBe(255);+ });++ it('keeps backdrop-colored pixels that are enclosed by the character', () => {+ const image = makeImage(40, WHITE, SKIN);+ // A white highlight inside the subject — same color as the backdrop.+ const offset = (20 * 40 + 20) * 4;+ image.data[offset] = WHITE.r;+ image.data[offset + 1] = WHITE.g;+ image.data[offset + 2] = WHITE.b;++ cutOutFlatBackground(image);++ expect(alphaAt(image, 20, 20)).toBe(255);+ expect(alphaAt(image, 0, 0)).toBe(0);+ });++ it('softens the silhouette instead of leaving a hard key edge', () => {+ const image = makeImage(40, ORANGE, SKIN);+ // An anti-aliased pixel halfway between backdrop and character.+ const offset = (10 * 40 + 20) * 4;+ image.data[offset] = Math.round((ORANGE.r + SKIN.r) / 2);+ image.data[offset + 1] = Math.round((ORANGE.g + SKIN.g) / 2);+ image.data[offset + 2] = Math.round((ORANGE.b + SKIN.b) / 2);++ cutOutFlatBackground(image);++ const alpha = alphaAt(image, 20, 10);+ expect(alpha).toBeGreaterThan(0);+ expect(alpha).toBeLessThan(255);+ });++ it('reports the character box so callers can crop the margin away', () => {+ const image = makeImage(40, ORANGE, SKIN, 10);++ const { bounds } = cutOutFlatBackground(image);++ expect(bounds).toEqual({ height: 20, left: 10, top: 10, width: 20 });+ });++ it('has no character box when the cut-out was rejected', () => {+ const image = makeImage(40, ORANGE, ORANGE);++ const { applied, bounds } = cutOutFlatBackground(image);++ expect(applied).toBe(false);+ expect(bounds).toBeUndefined();+ });++ it('ignores all-transparent input when measuring the character box', () => {+ const size = 8;+ const data = new Uint8ClampedArray(size * size * 4);++ expect(subjectBounds({ data, height: size, width: size })).toBeUndefined();+ });++ it('reports the cut-out as not applied when the backdrop is not flat', () => {+ const size = 40;+ const data = new Uint8ClampedArray(size * size * 4);+ for (let index = 0; index < size * size; index += 1) {+ const offset = index * 4;+ data[offset] = index % 256;+ data[offset + 1] = (index * 3) % 256;+ data[offset + 2] = (index * 7) % 256;+ data[offset + 3] = 255;+ }++ const result = cutOutFlatBackground({ data, height: size, width: size });++ expect(result.applied).toBe(false);+ expect(data[3]).toBe(255);+ });++ it('reports the cut-out as not applied when it would erase the whole frame', () => {+ const image = makeImage(40, ORANGE, ORANGE);++ const result = cutOutFlatBackground(image);++ expect(result.applied).toBe(false);+ expect(result.removedRatio).toBeGreaterThan(0.97);+ });+});diff --git a/src/services/artworkGeneration/cutOutFlatBackground.ts b/src/services/artworkGeneration/cutOutFlatBackground.tsnew file mode 100644index 00000000000..137303461a2--- /dev/null+++ b/src/services/artworkGeneration/cutOutFlatBackground.ts@@ -0,0 +1,190 @@+/**+ * Image models cannot hand back a real alpha channel here — Nano Banana returns+ * JPEG, and asking it for "a transparent background" makes it *paint* a+ * checkerboard instead. So the full-body prompt asks for one flat, uniform+ * backdrop color and this module keys that backdrop out afterwards, which is+ * what actually produces the transparent PNG the home surface needs.+ */++export interface RgbaImage {+ data: Uint8ClampedArray;+ height: number;+ width: number;+}++export interface CutOutOptions {+ /** Max squared RGB distance from the sampled backdrop that still counts as backdrop. */+ tolerance?: number;+}++export interface CutOutResult {+ /** False when the result was rejected as untrustworthy and `data` was left untouched. */+ applied: boolean;+ /**+ * Bounding box of what survived, or `undefined` when nothing did. Callers crop+ * to it so the stored artwork's edges are the character's edges — see+ * {@link subjectBounds}.+ */+ bounds?: SubjectBounds;+ /** Share of pixels turned fully transparent, 0–1. */+ removedRatio: number;+}++export interface SubjectBounds {+ height: number;+ left: number;+ top: number;+ width: number;+}++/**+ * Box around every pixel the cut-out kept.+ *+ * A model frames a standing character with whatever margin it likes — measured+ * against the built-in artwork, a generated full body filled only 35% of its+ * canvas width where the catalog's fills 75%. Cropping to this box makes the+ * file's edges mean the same thing every time, so one display rule can size any+ * character instead of guessing per source.+ */+export const subjectBounds = ({ data, height, width }: RgbaImage): SubjectBounds | undefined => {+ let minX = width;+ let maxX = -1;+ let minY = height;+ let maxY = -1;++ for (let y = 0; y < height; y += 1) {+ for (let x = 0; x < width; x += 1) {+ if (data[(y * width + x) * 4 + 3] <= ALPHA_FLOOR) continue;+ if (x < minX) minX = x;+ if (x > maxX) maxX = x;+ if (y < minY) minY = y;+ if (y > maxY) maxY = y;+ }+ }++ if (maxX < minX || maxY < minY) return;++ return { height: maxY - minY + 1, left: minX, top: minY, width: maxX - minX + 1 };+};++/** Squared distance keeps the hot loop free of `Math.sqrt`. */+const TOLERANCE = 26 * 26 * 3;+/** Alpha at or below this is background as far as the subject box is concerned. */+const ALPHA_FLOOR = 16;+/** Below this the backdrop clearly was not flat; above it the character was eaten. */+const MIN_REMOVED_RATIO = 0.05;+const MAX_REMOVED_RATIO = 0.97;++const distanceSquared = (+ data: Uint8ClampedArray,+ offset: number,+ r: number,+ g: number,+ b: number,+): number => {+ const dr = data[offset] - r;+ const dg = data[offset + 1] - g;+ const db = data[offset + 2] - b;++ return dr * dr + dg * dg + db * db;+};++/**+ * The backdrop color is read from the frame rather than assumed, so the prompt+ * stays free to pick whatever color contrasts with the character. The median of+ * each channel ignores the few border pixels a pose may legitimately touch.+ */+const sampleBackdrop = ({ data, height, width }: RgbaImage): [number, number, number] => {+ const reds: number[] = [];+ const greens: number[] = [];+ const blues: number[] = [];++ const push = (x: number, y: number) => {+ const offset = (y * width + x) * 4;+ reds.push(data[offset]);+ greens.push(data[offset + 1]);+ blues.push(data[offset + 2]);+ };++ for (let x = 0; x < width; x += 1) {+ push(x, 0);+ push(x, height - 1);+ }+ for (let y = 0; y < height; y += 1) {+ push(0, y);+ push(width - 1, y);+ }++ const median = (values: number[]) => {+ values.sort((a, b) => a - b);++ return values[Math.floor(values.length / 2)];+ };++ return [median(reds), median(greens), median(blues)];+};++/**+ * Clears the backdrop of an already-decoded image in place.+ *+ * Only backdrop-colored pixels *connected to the frame* are cleared, so the same+ * color inside the character (an eye highlight, a white collar) survives. Pixels+ * that merely sit near the backdrop color get a partial alpha, which keeps the+ * anti-aliased silhouette from turning into a hard jagged edge.+ */+export const cutOutFlatBackground = (image: RgbaImage, options?: CutOutOptions): CutOutResult => {+ const { data, height, width } = image;+ const tolerance = options?.tolerance ?? TOLERANCE;+ const [r, g, b] = sampleBackdrop(image);++ const pixelCount = width * height;+ const visited = new Uint8Array(pixelCount);+ const stack: number[] = [];++ const push = (pixel: number) => {+ if (visited[pixel]) return;+ visited[pixel] = 1;+ if (distanceSquared(data, pixel * 4, r, g, b) > tolerance * 4) return;+ stack.push(pixel);+ };++ for (let x = 0; x < width; x += 1) {+ push(x);+ push((height - 1) * width + x);+ }+ for (let y = 0; y < height; y += 1) {+ push(y * width);+ push(y * width + width - 1);+ }++ let removed = 0;++ while (stack.length > 0) {+ const pixel = stack.pop() as number;+ const offset = pixel * 4;+ const distance = distanceSquared(data, offset, r, g, b);++ if (distance <= tolerance) {+ data[offset + 3] = 0;+ removed += 1;+ } else {+ // Feather zone: the closer to the backdrop, the more transparent.+ const ratio = (distance - tolerance) / (tolerance * 3);+ data[offset + 3] = Math.round(data[offset + 3] * Math.min(1, ratio));+ continue;+ }++ const x = pixel % width;+ const y = (pixel - x) / width;++ if (x > 0) push(pixel - 1);+ if (x < width - 1) push(pixel + 1);+ if (y > 0) push(pixel - width);+ if (y < height - 1) push(pixel + width);+ }++ const removedRatio = removed / pixelCount;+ const applied = removedRatio >= MIN_REMOVED_RATIO && removedRatio <= MAX_REMOVED_RATIO;++ return { applied, bounds: applied ? subjectBounds(image) : undefined, removedRatio };+};diff --git a/src/services/artworkGeneration/generateArtworkImage.ts b/src/services/artworkGeneration/generateArtworkImage.tsindex 910566b1c58..80c5e184208 100644--- a/src/services/artworkGeneration/generateArtworkImage.ts+++ b/src/services/artworkGeneration/generateArtworkImage.ts@@ -1,4 +1,4 @@-import type { AgentArtworkKind } from '@lobechat/prompts';+import type { AgentArtworkComposition, AgentArtworkKind } from '@lobechat/prompts';import { generationService } from '@/services/generation';import { generationTopicService } from '@/services/generationTopic';@@ -66,6 +66,7 @@ export interface AttachedArtworkReferences {export interface GenerateArtworkImageOptions {buildPrompt: (references: AttachedArtworkReferences) => string;+ composition?: AgentArtworkComposition;kind: AgentArtworkKind;/*** Fires as soon as the remote generation exists, so a caller that owns the@@ -89,6 +90,7 @@ export interface GenerateArtworkImageOptions {*/export const generateArtworkImage = async ({buildPrompt,+ composition,kind,onGenerationCreated,referenceImageUrl,@@ -123,14 +125,18 @@ export const generateArtworkImage = async ({const supportedSizes =model.parameters && 'size' in model.parameters ? model.parameters.size?.enum : undefined;const preferredSizes =- kind === 'avatar' ? ['1024x1024', '2048x2048'] : ['2048x1152', '1536x1024', '3840x2160'];+ kind === 'background'+ ? ['2048x1152', '1536x1024', '3840x2160']+ : composition === 'fullBody'+ ? ['1024x1536', '2048x3072', '1440x2560', '2160x3840']+ : ['1024x1024', '2048x2048'];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 aspectRatio = kind === 'background' ? '16:9' : composition === 'fullBody' ? '3:4' : '1:1';const params = {...(model.parameters && 'aspectRatio' in model.parameters ? { aspectRatio } : {}),...(imageUrls ? { imageUrls } : {}),diff --git a/src/services/artworkGeneration/index.ts b/src/services/artworkGeneration/index.tsindex 3c130106e33..4929d2c8a16 100644--- a/src/services/artworkGeneration/index.ts+++ b/src/services/artworkGeneration/index.ts@@ -1,9 +1,11 @@+export { cutOutFlatBackground, type CutOutResult, type RgbaImage } from './cutOutFlatBackground';export {type AttachedArtworkReferences,generateArtworkImage,type GenerateArtworkImageOptions,} from './generateArtworkImage';export { selectAgentArtworkModel } from './selectModel';+export { cutOutFullBodyArtwork } from './transparentFullBody';export {generateWorkspaceAvatarImage,type GenerateWorkspaceAvatarImageOptions,diff --git a/src/services/artworkGeneration/transparentFullBody.ts b/src/services/artworkGeneration/transparentFullBody.tsnew file mode 100644index 00000000000..88f6e4fb1a9--- /dev/null+++ b/src/services/artworkGeneration/transparentFullBody.ts@@ -0,0 +1,63 @@+import { cutOutFlatBackground } from './cutOutFlatBackground';++/**+ * Turns a freshly generated full-body image into a transparent PNG.+ *+ * Returns `undefined` whenever the source cannot be read or the cut-out looks+ * untrustworthy, so callers fall back to the original artwork instead of+ * showing a half-erased character.+ */+export const cutOutFullBodyArtwork = async (url: string): Promise<File | undefined> => {+ try {+ const response = await fetch(url);+ if (!response.ok) return;++ const bitmap = await createImageBitmap(await response.blob());+ const canvas = document.createElement('canvas');+ canvas.width = bitmap.width;+ canvas.height = bitmap.height;++ const context = canvas.getContext('2d');+ if (!context) return;++ context.drawImage(bitmap, 0, 0);+ bitmap.close();++ const imageData = context.getImageData(0, 0, canvas.width, canvas.height);+ const { applied, bounds } = cutOutFlatBackground(imageData);+ if (!applied || !bounds) return;++ context.clearRect(0, 0, canvas.width, canvas.height);+ context.putImageData(imageData, 0, 0);++ // Crop to the character so the file's edges are its edges: the model frames+ // a standing figure with whatever margin it likes, and a surface cannot size+ // artwork it has to guess the padding of.+ const cropped = document.createElement('canvas');+ cropped.width = bounds.width;+ cropped.height = bounds.height;+ const croppedContext = cropped.getContext('2d');+ if (!croppedContext) return;++ croppedContext.drawImage(+ canvas,+ bounds.left,+ bounds.top,+ bounds.width,+ bounds.height,+ 0,+ 0,+ bounds.width,+ bounds.height,+ );++ const blob = await new Promise<Blob | null>((resolve) => cropped.toBlob(resolve, 'image/png'));+ if (!blob) return;++ return new File([blob], 'full-body.png', { type: 'image/png' });+ } catch (error) {+ console.error('Failed to cut out the full-body background:', error);++ return;+ }+};diff --git a/src/store/agent/selectors/selectors.ts b/src/store/agent/selectors/selectors.tsindex 922bcc00a6e..2f991f35cc4 100644--- a/src/store/agent/selectors/selectors.ts+++ b/src/store/agent/selectors/selectors.ts@@ -11,6 +11,7 @@ import {import {agentDisplayName,type AgentMode,+ type AgentProfile,type KnowledgeItem,type LobeAgentConfig,type LobeAgentTTSConfig,@@ -106,6 +107,31 @@ const getAgentMetaById =};};+/**+ * Full-body artwork of the agent's character, or `undefined` when it has none.+ * Kept out of {@link getAgentMetaById} because `MetaData` is shared with+ * sessions and groups, which have no character sheet.+ */+/**+ * The avatar actually stored on the agent — unlike {@link getAgentMetaById},+ * which substitutes a default so every surface has something to render. Use+ * this to decide whether there is anything to remove.+ */+const getAgentStoredAvatarById =+ (agentId: string) =>+ (s: AgentStoreState): string | undefined =>+ s.agentMap[agentId]?.avatar || undefined;++const getAgentProfileById =+ (agentId: string) =>+ (s: AgentStoreState): AgentProfile | undefined =>+ s.agentMap[agentId]?.profile ?? undefined;++const getAgentFullBodyArtworkById =+ (agentId: string) =>+ (s: AgentStoreState): string | undefined =>+ s.agentMap[agentId]?.profile?.fullBodyArtwork || undefined;+// ========== Config ============== //const inboxAgentConfig = (s: AgentStoreState) => {@@ -380,7 +406,10 @@ export const agentSelectors = {displayableAgentPlugins,getAgentConfigById,getAgentDocumentsById,+ getAgentFullBodyArtworkById,getAgentMetaById,+ getAgentProfileById,+ getAgentStoredAvatarById,getAgentSlugById,hasEnabledKnowledge,hasEnabledKnowledgeBases,diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.tsindex 46b941103a5..740d30c434d 100644--- a/src/store/agent/slices/agent/action.ts+++ b/src/store/agent/slices/agent/action.ts@@ -614,6 +614,10 @@ export class AgentSliceActionImpl {draft[id] = config;} else {draft[id] = merge(draft[id], config);+ // The character sheet is authored as one document — `AgentModel`+ // replaces it rather than merging — so mirror that here, or a trait the+ // user just cleared reappears until the next full fetch.+ if (Object.hasOwn(config, 'profile')) draft[id].profile = config.profile;// merge() can't drop keys; honor `undefined` as a per-device delete so// clearing a working directory takes effect optimistically.pruneWorkingDirByDeviceDeletes(draft[id].agencyConfig, config.agencyConfig);diff --git a/src/store/agent/slices/artwork/action.test.ts b/src/store/agent/slices/artwork/action.test.tsindex 9f9db6dcd93..54969660203 100644--- a/src/store/agent/slices/artwork/action.test.ts+++ b/src/store/agent/slices/artwork/action.test.ts@@ -87,6 +87,56 @@ describe('AgentArtworkAction', () => {expect(useAgentStore.getState().agentArtworkGenerationMap?.['agent-a']).toBeUndefined();});+ it('returns companion artwork without replacing persisted agent metadata', async () => {+ vi.mocked(getAiInfraStoreState).mockReturnValue({+ enabledImageModelList: [+ {+ children: [+ {+ abilities: {},+ id: 'gemini-3.1-flash-lite-image:image',+ parameters: {+ aspectRatio: { default: 'auto', enum: ['auto', '1:1', '3:4'] },+ prompt: { default: '' },+ },+ },+ ],+ id: 'google',+ name: 'Google',+ 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/full-body.webp' } },+ status: AsyncTaskStatus.Success,+ } as never);+ const updateAgentMetaById = vi.fn().mockResolvedValue(undefined);+ useAgentStore.setState({ updateAgentMetaById });++ const url = await useAgentStore.getState().generateAgentArtwork({+ ...input,+ composition: 'fullBody',+ persist: false,+ });++ expect(url).toBe('https://example.com/full-body.webp');+ expect(imageService.createImage).toHaveBeenCalledWith(+ expect.objectContaining({+ params: expect.objectContaining({+ aspectRatio: '3:4',+ prompt: expect.stringContaining('distinctive portrait character image'),+ }),+ }),+ );+ expect(updateAgentMetaById).not.toHaveBeenCalled();+ });+it('passes the existing avatar as a reference image when generating a background', async () => {vi.mocked(getAiInfraStoreState).mockReturnValue({enabledImageModelList: [diff --git a/src/store/agent/slices/artwork/action.ts b/src/store/agent/slices/artwork/action.tsindex 66050859ee2..1e99c50d127 100644--- a/src/store/agent/slices/artwork/action.ts+++ b/src/store/agent/slices/artwork/action.ts@@ -13,6 +13,11 @@ interface AgentArtworkGenerationJob {generationId?: string;}+interface GenerateAgentArtworkInput extends AgentArtworkPromptInput {+ /** False for companion artwork that is previewed without replacing the avatar or cover. */+ persist?: boolean;+}+type Setter = StoreSetter<AgentStore>;export const createAgentArtworkSlice = (set: Setter, get: () => AgentStore, _api?: unknown) =>@@ -56,7 +61,7 @@ export class AgentArtworkActionImpl {);};- generateAgentArtwork = async (input: AgentArtworkPromptInput): Promise<void> => {+ generateAgentArtwork = async (input: GenerateAgentArtworkInput): Promise<string | undefined> => {if (this.#get().agentArtworkGenerationMap[input.id]?.status === 'generating') return;const job: AgentArtworkGenerationJob = { controller: new AbortController() };@@ -66,6 +71,7 @@ export class AgentArtworkActionImpl {try {const url = await generateArtworkImage({buildPrompt: (references) => buildAgentArtworkPrompt({ ...input, ...references }),+ composition: input.composition,kind: input.kind,onGenerationCreated: (generationId) => {job.generationId = generationId;@@ -76,11 +82,14 @@ export class AgentArtworkActionImpl {topicTitle: input.kind === 'avatar' ? 'Agent avatar' : 'Agent background',});- await this.#get().updateAgentMetaById(- input.id,- input.kind === 'avatar' ? { avatar: url } : { backgroundColor: url },- );+ if (input.persist !== false) {+ await this.#get().updateAgentMetaById(+ input.id,+ input.kind === 'avatar' ? { avatar: url } : { backgroundColor: url },+ );+ }this.#setGenerationState(input.id, undefined);+ return url;} catch (error) {if (job.controller.signal.aborted) return;