🤯 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): give new agents a personal name (#17853)
Arvin Xu353f00006284
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.mdindex 438b218651e..c5466e49e73 100644--- a/.agents/acceptance/probe-mock-patterns.md+++ b/.agents/acceptance/probe-mock-patterns.md@@ -563,6 +563,56 @@ Prove the working-tree bundle is actually live first — read back a string thatexists only in the working tree (e.g. a changed placeholder), never assume HMRapplied.+### Counting section instances across the Home rail collapse needs real visibility, not a rect++**Situation:** asserting that a Home section moved between the rail and the main+column rather than being duplicated or lost.++**Doesn't work:** two independent traps, each of which inverts the verdict.++- Filtering candidates by `getBoundingClientRect()` alone. The collapsed rail is+ hidden with `visibility: hidden` after a transition, and a `visibility: hidden`+ subtree **keeps its layout boxes** — so the rail's copy still measures non-zero+ and every folded-in section reads as duplicated. This is the inverse of the+ generic D12 phantom (zero-size decoy); here the stale node is full-size.+- Collecting only leaf elements. The main column's `GroupBlock` renders its+ subtitle as a `<span>` inside the title, so the title element has children,+ while the rail's `RailCard` takes no subtitle and its title _is_ a leaf. A+ leaf-only walk therefore finds a section in the rail and "loses" it in the main+ column — reading exactly like the fold-in never happened.++**Works:** match on the element's own direct text nodes and gate on+`el.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true })`, then sort+by viewport `y`:++```js+const own = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent.trim()).join('');+if (!label.test(own)) continue;+if (!el.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true })) continue;+```++Assert both columns in the same pass — a claim about _moving_ is only settled by+observing the source column go empty and the destination fill in one snapshot.++### A worktree Electron run leaves a second `@types/react` that fails the worktree type-check++**Situation:** running the Electron surface from a git worktree, which requires+the `apps/desktop` standalone install (adapter §1), then running `bun run check --type`.++**Doesn't work:** treating the resulting type errors as the branch's own. The+desktop install brings its own `@types/react` (e.g. `19.2.18`) alongside the+root's (`19.2.13`), and the two identities collide on every `lucide-react` icon+`ref`, producing a cluster of "Two different types with this name exist, but they+are unrelated" errors in files the branch never touched.++**Works:** intersect the erroring files with the branch's changed-file list before+drawing any conclusion, and confirm causality by A/B — moving+`apps/desktop/node_modules` aside makes the cluster vanish. At teardown, remove+`apps/desktop/node_modules` and re-run the root `pnpm install` to restore a clean+`✓ types clean` baseline. **Do not run the A/B while the instance is live** — the+Electron binary runs out of that directory, so parking it kills the instance;+capture all UI evidence first.+### Managed command runners can reap `electron-dev.sh start` children after the helper returns**Situation:** `electron-dev.sh start` (legacy and pool forms) reports that CDP@@ -787,6 +837,47 @@ cache, so the renderer still shows the pre-write value (generic M18). Clear`lobechat-swr-cache*` + `lobehub-local-data` through`Page.addScriptToEvaluateOnNewDocument` and reload (see "Cold SWR cache" above),then assert `agentMap[id].agencyConfig` before drawing any conclusion.+### An unconverged lockfile puts two copies of a dep in the graph — every route using it dies at the ErrorBoundary++**Situation:** after rebasing onto a canary that bumped a shared UI dependency and+running `pnpm install`, every route rendering the rich-text editor (agent profile,+Home composer) fails with+`LexicalComposerContext.useLexicalComposerContext: cannot find a LexicalComposerContext`+and the SPA shows 页面暂时不可用.++**Doesn't work:** reading it as a defect in the change under test, or as a stale+Vite dep cache. Clearing `node_modules/.vite` (both root and `src/`) and a plain+`pnpm install` both leave it broken, because the duplicate is in the resolution,+not the cache.++**Works:** attribute first, then measure the resolution.++1. Attribution is cheap and decisive: load a route the branch definitely does not+ touch that uses the same dependency. If it fails too, the change under test is+ ruled out without checking out the base ref.++2. The mechanism is two physical copies with different peer sets. The root+ declares an exact-ish range while workspace packages declare a loose one, so a+ dependency bump moves only the root:++ ```bash+ readlink node_modules/@lobehub/editor # -> …[email protected]_…[email protected]+ readlink packages/*/node_modules/@lobehub/editor # -> …[email protected]_…[email protected]+ ```++ A React context is module-scoped, so two copies means the provider and the+ consumer read different context objects — the symptom is always "cannot find+ the context", never a version error.++3. `pnpm dedupe` converges them; clear the Vite dep caches and restart afterwards.++**`pnpm-lock.yaml` is gitignored in this repo (`.gitignore`), so this divergence is+always LOCAL install state — never something canary committed and never something to+open a PR about.** A loose workspace range (`^4`) stays satisfied by the old version+across incremental installs, so the drift accumulates silently in a long-lived+checkout and appears right after a rebase that bumps the root range. Do not report it+as a defect of the branch or of the base ref; note it as an environment finding and+move on. Back up the lockfile before `dedupe` anyway — it is the only copy.## Detailed referencesdiff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.tsindex a15e1540634..728fc83aa1b 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts@@ -452,6 +452,7 @@ export const buildServerCallLlmContext = async ({avatar: editingConfig.avatar ?? undefined,backgroundColor: editingConfig.backgroundColor ?? undefined,description: editingConfig.description ?? undefined,+ name: editingConfig.name ?? undefined,tags: editingConfig.tags ?? undefined,title: editingConfig.title ?? undefined,},diff --git a/apps/server/src/routers/lambda/__tests__/share.test.ts b/apps/server/src/routers/lambda/__tests__/share.test.tsindex 3d5734cdec2..d81edbe0e94 100644--- a/apps/server/src/routers/lambda/__tests__/share.test.ts+++ b/apps/server/src/routers/lambda/__tests__/share.test.ts@@ -23,6 +23,7 @@ describe('shareRouter', () => {agentId: 'agent-1',agentMarketIdentifier: 'market-id',agentSlug: 'agent-slug',+ agentName: null,agentTitle: 'Test Agent',groupAvatar: null,groupBackgroundColor: null,@@ -75,6 +76,7 @@ describe('shareRouter', () => {agentId: 'agent-1',agentMarketIdentifier: 'market-agent',agentSlug: 'test-agent',+ agentName: null,agentTitle: 'Test Agent Title',groupAvatar: null,groupBackgroundColor: null,@@ -119,6 +121,7 @@ describe('shareRouter', () => {agentId: null,agentMarketIdentifier: null,agentSlug: null,+ agentName: null,agentTitle: null,groupAvatar: 'group-avatar.png',groupBackgroundColor: '#000000',@@ -205,6 +208,7 @@ describe('shareRouter', () => {agentId: null,agentMarketIdentifier: null,agentSlug: null,+ agentName: null,agentTitle: null,groupAvatar: null,groupBackgroundColor: null,diff --git a/apps/server/src/routers/lambda/_helpers/resourceConfigGuard.test.ts b/apps/server/src/routers/lambda/_helpers/resourceConfigGuard.test.tsindex a6c9f3502d7..fa5e28a9e6d 100644--- a/apps/server/src/routers/lambda/_helpers/resourceConfigGuard.test.ts+++ b/apps/server/src/routers/lambda/_helpers/resourceConfigGuard.test.ts@@ -155,6 +155,7 @@ describe('config redaction', () => {files: [{ id: 'file-1' }],id: 'agent-1',model: 'shared-model',+ name: 'Alice',openingMessage: 'Hello',params: { temperature: 0.8 },plugins: ['private-tool'],@@ -175,6 +176,7 @@ describe('config redaction', () => {description: 'Public description',id: 'agent-1',model: 'shared-model',+ name: 'Alice',openingMessage: 'Hello',provider: 'shared-provider',title: 'Public title',diff --git a/apps/server/src/routers/lambda/_helpers/resourceConfigGuard.ts b/apps/server/src/routers/lambda/_helpers/resourceConfigGuard.tsindex bed99bb07f2..c24fd1479a8 100644--- a/apps/server/src/routers/lambda/_helpers/resourceConfigGuard.ts+++ b/apps/server/src/routers/lambda/_helpers/resourceConfigGuard.ts@@ -135,6 +135,7 @@ const AGENT_PROFILE_KEYS = ['isSupervisor','marketIdentifier','model',+ 'name','openingMessage','openingQuestions','provider',diff --git a/apps/server/src/routers/lambda/agent.ts b/apps/server/src/routers/lambda/agent.tsindex fb925869d10..9b5d96c6e18 100644--- a/apps/server/src/routers/lambda/agent.ts+++ b/apps/server/src/routers/lambda/agent.ts@@ -1064,6 +1064,38 @@ export const agentRouter = router({return ctx.agentService.updateAgentConfig(input.agentId, input.value);}),+ /**+ * Resolve a slug to its agent id so `/agent/:slug` can open the agent.+ *+ * Read-only and ownership-scoped: an unknown slug and someone else's slug both+ * return `null`, so this cannot be used to probe which slugs exist.+ */+ resolveAgentIdBySlug: agentProcedure+ .input(z.object({ slug: z.string() }))+ .query(async ({ input, ctx }) => {+ const agentId = await ctx.agentModel.resolveIdBySlug(input.slug);+ return { agentId };+ }),++ /**+ * Rename an agent's url slug. Separate from `updateAgentConfig` because `slug`+ * is immutable there by design — see `IMMUTABLE_AGENT_FIELDS`.+ */+ updateAgentSlug: agentProcedure+ .use(withScopedPermission('agent:update'))+ .input(z.object({ agentId: z.string(), slug: z.string() }))+ .mutation(async ({ input, ctx }) => {+ await assertCanEditResource({+ db: ctx.serverDB,+ resourceId: input.agentId,+ resourceType: 'agent',+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ });++ return ctx.agentModel.updateSlug(input.agentId, input.slug);+ }),+/*** Pin or unpin an agent*/diff --git a/apps/server/src/routers/lambda/connector.ts b/apps/server/src/routers/lambda/connector.tsindex 5986cac8519..0b3ca7fbf43 100644--- a/apps/server/src/routers/lambda/connector.ts+++ b/apps/server/src/routers/lambda/connector.ts@@ -235,6 +235,7 @@ export const connectorRouter = router({return {...rest,agentAvatar: meta?.avatar ?? null,+ agentName: meta?.name ?? null,agentTitle: meta?.title ?? null,oidcConfig: safeOidcConfig,tools,diff --git a/apps/server/src/routers/lambda/share.ts b/apps/server/src/routers/lambda/share.tsindex f92c9b31b34..45ee0d5dc4f 100644--- a/apps/server/src/routers/lambda/share.ts+++ b/apps/server/src/routers/lambda/share.ts@@ -31,6 +31,7 @@ export const shareRouter = router({avatar: share.agentAvatar,backgroundColor: share.agentBackgroundColor,marketIdentifier: share.agentMarketIdentifier,+ name: share.agentName,slug: share.agentSlug,title: share.agentTitle,}diff --git a/apps/server/src/services/brief/index.ts b/apps/server/src/services/brief/index.tsindex 4124eefd131..9d6198d8007 100644--- a/apps/server/src/services/brief/index.ts+++ b/apps/server/src/services/brief/index.ts@@ -166,6 +166,7 @@ export class BriefService {agentRowId,agentAvatar,agentBackgroundColor,+ agentName,agentTitle,taskIdentifier,taskName,@@ -177,6 +178,7 @@ export class BriefService {avatar: agentAvatar,backgroundColor: agentBackgroundColor,id: agentRowId,+ name: agentName,title: agentTitle,}: null,diff --git a/apps/server/src/services/messenger/MessengerRouter.ts b/apps/server/src/services/messenger/MessengerRouter.tsindex a2aa85be92c..99c7dbbae8e 100644--- a/apps/server/src/services/messenger/MessengerRouter.ts+++ b/apps/server/src/services/messenger/MessengerRouter.ts@@ -1,4 +1,5 @@import { createIoRedisState } from '@chat-adapter/state-ioredis';+import { agentDisplayName } from '@lobechat/types';import {Chat,ConsoleLogger,@@ -1590,18 +1591,19 @@ export class MessengerRouter {): Promise<AgentSummary[]> {// The filter, ordering, pinning, and title fallback all live in the model.// This text-only channel has no client-side i18n default, so it asks the- // model to fill blank titles with a generic "Custom Agent" label.+ // model to fill blank titles with a generic "Custom Agent" label, then+ // resolves name-over-title itself — there is no renderer downstream to do it.const rows = await new AgentModel(serverDB,userId,workspaceId ?? undefined,).listMessengerBindableAgents({ fallbackTitle: 'Custom Agent' });- // `fallbackTitle` guarantees a non-null title for every row.+ // `fallbackTitle` guarantees a non-null label for every row.const summaries = rows.map((row) => ({id: row.id,isPrivate: row.isPrivate,- title: row.title!,+ title: agentDisplayName(row, 'Custom Agent'),}));// Workspace scope: stable-partition shared workspace agents ahead of thediff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex d8080203a89..924d49757dc 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -697,21 +697,41 @@"settingAgent.export.tags": "Tags","settingAgent.export.untitled": "Untitled Agent","settingAgent.export.untitledFileName": "agent-profile",+ "settingAgent.identity.done": "Done",+ "settingAgent.identity.edit": "Edit identity",+ "settingAgent.identity.saveFailed": "Could not save the identity, please try again",+ "settingAgent.identity.untitled": "Unnamed agent","settingAgent.modelPolicy.fixedTip": "The model is fixed in Agent Profile and cannot be switched while chatting.","settingAgent.modelPolicy.title": "Model","settingAgent.name.placeholder": "Enter agent name","settingAgent.name.title": "Name",+ "settingAgent.personalName.label": "Name",+ "settingAgent.personalName.pickFailed": "Could not save the name, please try again",+ "settingAgent.personalName.pickForMe": "Name it for me",+ "settingAgent.personalName.placeholder": "Give it a name, e.g. Alice",+ "settingAgent.personalName.unnamed": "This agent has no name yet","settingAgent.prompt.desc": "Defines who this agent is, what it is responsible for, and how it works and responds. It serves as a core instruction in every conversation.","settingAgent.prompt.editorPlaceholder": "Enter core instructions, press / to open the Slash Menu","settingAgent.prompt.mode.source": "Markdown source","settingAgent.prompt.mode.visual": "Visual editor","settingAgent.prompt.placeholder": "Enter agent instructions","settingAgent.prompt.title": "Core Instructions",+ "settingAgent.role.label": "Role",+ "settingAgent.role.placeholder": "What it is responsible for, e.g. Health Assistant",+ "settingAgent.role.unset": "No role set yet","settingAgent.runtimeConfig.title": "Model & Tools","settingAgent.selectionPolicy.membersCanSwitch": "Can switch","settingAgent.selectionPolicy.membersCanSwitchWhenShared": "Can switch when shared","settingAgent.selectionPolicy.membersCannotSwitch": "Locked","settingAgent.selectionPolicy.membersCannotSwitchWhenShared": "Locked when shared",+ "settingAgent.slug.error.builtin": "A builtin agent’s identifier can’t be changed",+ "settingAgent.slug.error.invalid": "Use lowercase letters, numbers and hyphens only",+ "settingAgent.slug.error.reserved": "This identifier is reserved",+ "settingAgent.slug.error.taken": "This identifier is already in use",+ "settingAgent.slug.label": "Identifier",+ "settingAgent.slug.openWith": "Open it directly with /agent/{{slug}}",+ "settingAgent.slug.placeholder": "url-identifier",+ "settingAgent.slug.tooltip": "The agent’s url identifier — open it with /agent/<slug>","settingAgent.submit": "Update Agent","settingAgent.tag.desc": "Agent tags will be displayed in the Agent Community","settingAgent.tag.placeholder": "Enter tag",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 1d8bbc92cad..4d51371e853 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -697,21 +697,41 @@"settingAgent.export.tags": "标签","settingAgent.export.untitled": "未命名助理","settingAgent.export.untitledFileName": "助理档案",+ "settingAgent.identity.done": "完成",+ "settingAgent.identity.edit": "编辑身份信息",+ "settingAgent.identity.saveFailed": "身份信息保存失败,请重试",+ "settingAgent.identity.untitled": "未命名助理","settingAgent.modelPolicy.fixedTip": "模型已在助理档案中固定,聊天时不可切换。","settingAgent.modelPolicy.title": "模型","settingAgent.name.placeholder": "请输入助理名称","settingAgent.name.title": "名称",+ "settingAgent.personalName.label": "名字",+ "settingAgent.personalName.pickFailed": "名字保存失败,请重试",+ "settingAgent.personalName.pickForMe": "一键起名",+ "settingAgent.personalName.placeholder": "给它起个名字,比如小艾",+ "settingAgent.personalName.unnamed": "该助理还没有名字","settingAgent.prompt.desc": "定义这个助理的身份、职责、工作方式和回应风格。这里的设定会在每次对话中生效。","settingAgent.prompt.editorPlaceholder": "输入核心指令,按 / 打开斜杠菜单","settingAgent.prompt.mode.source": "Markdown 源码","settingAgent.prompt.mode.visual": "所见即所得","settingAgent.prompt.placeholder": "请输入助理指令","settingAgent.prompt.title": "核心指令",+ "settingAgent.role.label": "角色",+ "settingAgent.role.placeholder": "负责领域,例如:健康助手",+ "settingAgent.role.unset": "暂未设定角色","settingAgent.runtimeConfig.title": "模型与工具","settingAgent.selectionPolicy.membersCanSwitch": "可切换","settingAgent.selectionPolicy.membersCanSwitchWhenShared": "公开后可切换","settingAgent.selectionPolicy.membersCannotSwitch": "锁定","settingAgent.selectionPolicy.membersCannotSwitchWhenShared": "公开后锁定",+ "settingAgent.slug.error.builtin": "内置助理的标识不可修改",+ "settingAgent.slug.error.invalid": "只能使用小写字母、数字和连字符",+ "settingAgent.slug.error.reserved": "该标识为系统保留",+ "settingAgent.slug.error.taken": "该标识已被占用",+ "settingAgent.slug.label": "标识",+ "settingAgent.slug.openWith": "可用 /agent/{{slug}} 直接打开",+ "settingAgent.slug.placeholder": "url-标识",+ "settingAgent.slug.tooltip": "该助理的 url 标识 —— 可用 /agent/<slug> 直接打开","settingAgent.submit": "更新助理信息","settingAgent.tag.desc": "助理标签将在助理社区中展示","settingAgent.tag.placeholder": "请输入标签",diff --git a/packages/builtin-agents/src/agents/agent-builder/systemRole.ts b/packages/builtin-agents/src/agents/agent-builder/systemRole.tsindex cf783adcae0..ca0b8d04d5a 100644--- a/packages/builtin-agents/src/agents/agent-builder/systemRole.ts+++ b/packages/builtin-agents/src/agents/agent-builder/systemRole.ts@@ -2,109 +2,46 @@* Agent Builder System Role Template** This agent helps users configure and optimize their AI agents through natural conversation.+ *+ * Keep this prompt about *who the builder is*. The operational detail — the exact+ * tool surface, field-by-field configuration knowledge, naming rules, display+ * conventions — lives in the Agent Builder tool's own system prompt+ * (`@lobechat/builtin-tool-agent-builder`), which is injected alongside this one+ * whenever the tool is enabled. Duplicating it here is how the two drift apart.*/-export const systemRoleTemplate = `You are Lobe, an Agent Builder integrated into LobeHub. Your role is to help users configure and optimize their AI agents through natural conversation.--<capabilities>-You have access to tools that can read and modify agent configurations:+export const systemRoleTemplate = `You are Lobe, an Agent Builder integrated into LobeHub. You help users create, configure and optimize their AI agents through natural conversation.-**Read Operations:**-- **getConfig**: Get the complete configuration of the current agent (model, plugins, chat settings, opening message, etc.)-- **getMeta**: Get agent metadata (title, description, avatar, tags)-- **getAvailableModels**: Get all available AI models and providers that can be used. Optionally filter by provider ID.-- **getAvailableTools**: Get all available tools (built-in tools and installed plugins) that can be enabled for the agent.+<role>+You configure agents; you never become one. When a user's message could be read either as a request for domain help or as a description of an agent to build, always read it as the latter — "健康助手,咨询健康问题" means "build me a health assistant", not "answer my health question".+</role>-**Write Operations:**-- **updateConfig**: Update multiple configuration fields at once-- **updateMeta**: Update agent metadata (title, description, avatar, tags)-- **updateChatConfig**: Update chat-specific settings+<tools>+The Agent Builder tool is your only authority for changing the agent being edited:+- **updateConfig**: update configuration (model, provider, plugins, opening message/questions, chat settings, model parameters) and/or metadata (name, title, description, avatar, tags, backgroundColor) in one call+- **updatePrompt**: rewrite the agent's system prompt+- **installPlugin**: install and enable a plugin (marketplace MCP, builtin, Composio, LobeHub Skill)+- **getAvailableModels** / **searchMarketTools**: discover models and marketplace tools-**Specific Field Operations:**-- **togglePlugin**: Enable or disable a specific plugin-- **setModel**: Change the AI model and provider-- **setOpeningMessage**: Set the agent's opening message-- **setOpeningQuestions**: Set suggested opening questions-</capabilities>+The agent's current configuration, metadata and available official tools are injected into the conversation as \`<current_agent_context>\` — read them from there instead of asking the user or guessing.+</tools><workflow>-1. **Understand the request**: Listen carefully to what the user wants to configure-2. **Read current state**: Use getConfig/getMeta to understand current configuration before making changes-3. **Make targeted changes**: Use the most specific API for the task (e.g., setModel for model changes, togglePlugin for plugins)-4. **Confirm changes**: Report what was changed and the new values+1. **Understand the request** — what does the user actually want the agent to do?+2. **Read the injected context** — know the current state before changing it.+3. **Establish identity first** — name, title, description, avatar. Then model and tools. Then the system prompt, which can now reference both.+4. **Report what changed** — state the before → after for each field you touched.</workflow><guidelines>-1. **Always read before write**: Before making changes, use getConfig to understand the current state, unless the user explicitly tells you the current value.-2. **Explain your changes**: When modifying configurations, explain what you're changing and why it might benefit the user.-3. **One change at a time**: Prefer making focused changes rather than bulk updates, unless the user explicitly requests multiple changes at once.-4. **Validate user intent**: For significant changes (like changing the model or disabling important plugins), confirm with the user before proceeding.-5. **Provide recommendations**: When users ask for advice, explain the trade-offs of different options based on their use case.-6. **Use user's language**: Always respond in the same language the user is using.+1. **Batch related edits**: merge multiple field changes into a single updateConfig call rather than firing several in sequence.+2. **Confirm significant changes**: switching the model or disabling a plugin the agent relies on deserves a check with the user first.+3. **Explain trade-offs**: when recommending a model or tool, say what the user gains and gives up.+4. **Keep it simple**: cover the settings that matter for the user's goal; surface advanced parameters only when asked.+5. **Use the user's language**: always reply in the language the user writes in.</guidelines>-<configuration_knowledge>-**Model & Provider:**-- model: The AI model identifier (e.g., "gpt-4o", "gpt-4o-mini", "claude-3-5-sonnet-20241022", "gemini-1.5-pro")-- provider: The AI provider (e.g., "openai", "anthropic", "google", "azure")-- Different models have different capabilities, costs, and speed trade-offs--**Chat Configuration (chatConfig):**-- historyCount: Number of previous messages to include in context (default: 20). Higher values provide more context but increase token usage.-- enableHistoryCount: Whether to limit history (default: true)-- enableCompressHistory: Compress long conversation history to save tokens (default: true)-- enableStreaming: Stream responses in real-time (default: true)-- enableReasoning: Enable reasoning/thinking mode for supported models (default: false)-- displayMode: "chat" for conversational view, "docs" for document-style view--**Model Parameters (params):**-- temperature: Controls randomness (0-2, default: 1). Lower = more focused, higher = more creative-- top_p: Nucleus sampling parameter (0-1, default: 1)-- frequency_penalty: Reduces repetition (0-2, default: 0)-- presence_penalty: Encourages new topics (0-2, default: 0)--**Plugins:**-- Array of enabled plugin identifiers-- Common plugins: "lobe-web-browsing", "lobe-image-generation", "lobe-artifacts"-- Plugins extend agent capabilities with external tools--**Opening Experience:**-- openingMessage: First message shown when starting a new conversation. Good for introducing the agent's purpose.-- openingQuestions: Suggested questions to help users get started. Should be relevant to the agent's specialty.--**Metadata:**-- title: Display name for the agent-- description: Brief description of what the agent does-- avatar: Emoji or image URL for the agent's avatar-- tags: Categories for organization-- backgroundColor: Theme color for the agent card-</configuration_knowledge>--<examples>-User: "帮我把模型改成 Claude"-Action: First check current model with getConfig, then use setModel to change to claude-3-5-sonnet-20241022 with provider "anthropic"--User: "Enable web browsing for this agent"-Action: Use togglePlugin with pluginId "lobe-web-browsing" and enabled: true--User: "What's my current configuration?"-Action: Use getConfig and getMeta to retrieve and display the current settings in a readable format--User: "Set up some opening questions about coding"-Action: Use setOpeningQuestions with relevant programming questions like ["How can I help you with your code today?", "What programming language are you working with?", "Do you need help debugging or writing new code?"]--User: "What models are available?"-Action: Use getAvailableModels to retrieve and display all available AI models grouped by provider, showing their capabilities (vision, function calling, reasoning)--User: "Show me what tools I can enable"-Action: Use getAvailableTools to list all available built-in tools and installed plugins that can be enabled for the agent--User: "I want to use a model with vision capabilities"-Action: Use getAvailableModels to find models with vision capability, then recommend suitable options and use setModel to change if user confirms-</examples>-<response_format>-- When showing configuration, format it in a clear, readable way using markdown-- When making changes, clearly state what was changed (before → after)-- Use bullet points for listing multiple items-- Keep responses concise but informative+- Format configuration in readable markdown, using the user-facing field names, not raw keys+- State changes as before → after+- Keep responses concise but concrete</response_format>`;diff --git a/packages/builtin-tool-agent-builder/src/manifest.ts b/packages/builtin-tool-agent-builder/src/manifest.tsindex 9b8cd9b17dc..47f209a1ecc 100644--- a/packages/builtin-tool-agent-builder/src/manifest.ts+++ b/packages/builtin-tool-agent-builder/src/manifest.ts@@ -77,7 +77,7 @@ export const AgentBuilderManifest: BuiltinToolManifest = {},{description:- 'Update agent configuration and/or metadata. Use this to change model, provider, plugins, opening message, opening questions, chat settings, model parameters, title, description, avatar, tags, and toggle plugins. Only include fields you want to update. Use togglePlugin to enable/disable a specific plugin.',+ 'Update agent configuration and/or metadata. Use this to change model, provider, plugins, opening message, opening questions, chat settings, model parameters, name, title, description, avatar, tags, and toggle plugins. Only include fields you want to update. Use togglePlugin to enable/disable a specific plugin.',name: AgentBuilderApiName.updateAgentConfig,parameters: {properties: {@@ -140,13 +140,19 @@ export const AgentBuilderManifest: BuiltinToolManifest = {description: 'Agent description',type: 'string',},+ name: {+ description:+ 'The agent\'s personal name — what a user calls it, like a person\'s given name ("Alice", "小艾"). Must be a real, common given name in the user\'s language, NOT a role or a description: "Alice" ✅, "小艾" ✅, "Health Assistant" ❌, "健康助手" ❌ (those are the `title`). A newly created agent already has a randomly assigned name; only change it when the user asks, or once you know the agent\'s purpose and the seeded name clashes with it.',+ type: 'string',+ },tags: {description: 'Array of tags for categorization',items: { type: 'string' },type: 'array',},title: {- description: 'Agent display name',+ description:+ 'The role the agent plays, used as its label across the app ("Health Assistant", "健康助手"). This is the job, not the person — the person is `name`.',type: 'string',},},diff --git a/packages/builtin-tool-agent-builder/src/systemRole.ts b/packages/builtin-tool-agent-builder/src/systemRole.tsindex 36f9414e7ce..de0001a64f5 100644--- a/packages/builtin-tool-agent-builder/src/systemRole.ts+++ b/packages/builtin-tool-agent-builder/src/systemRole.ts@@ -10,7 +10,7 @@ export const systemPrompt = `You are an Agent Configuration Assistant integrated**Important**: The current agent's configuration, metadata, and available official tools are automatically injected into the conversation context as \`<current_agent_context>\`. You can reference this information directly without calling any read APIs.The injected context includes:-- **agent_meta**: title, description, avatar, backgroundColor, tags+- **agent_meta**: name, title, description, avatar, backgroundColor, tags- **agent_config**: model, provider, plugins, systemRole (truncated only when over 10000 characters), and other advanced settings- **official_tools**: List of available official tools including built-in tools, Composio MCP servers, and LobehubSkill providers (Linear, Outlook Calendar, Twitter, etc.) with their enabled/installed status@@ -67,7 +67,7 @@ Note: Official tools (built-in tools, Composio MCP servers, and LobehubSkill proWhen creating or modifying an agent, follow this order:**Step 1: Metadata & Identity**-Set avatar, title, description, tags, and backgroundColor first - establish who the agent is+Set avatar, name, title, description, tags, and backgroundColor first - establish who the agent is**Step 2: Model & Tools**Configure the AI model, provider, and enable necessary plugins/tools - define what capabilities the agent has@@ -78,11 +78,37 @@ Write or refine the system prompt last - this step benefits from knowing the ageThis sequence ensures the system prompt can reference the agent's established identity and capabilities.</modification_sequence>+<naming>+An agent has two separate identity fields. Never conflate them:++| Field | What it is | Examples |+|-------|-----------|----------|+| **name** | The agent's personal name — how the user addresses it, like a person | Alice, Leo, 小艾, 知微 |+| **title** | The role the agent plays — its job | Health Assistant, Code Reviewer, 健康助手, 代码审查员 |++**Rules:**+1. **Match the user's language.** A user speaking Chinese gets a Chinese name (小艾, 知微); a user speaking English gets an English name (Alice, Leo). Never give a Chinese-speaking user an English name, or vice versa.+2. **A name must be a real, common given name** — not a description, not a pun on the role, not a product-sounding coinage. "小艾" ✅, "健康小助手" ❌, "HealthBot" ❌.+3. **Never reuse an assistant brand** (Siri, Alexa, Claude, Gemini, ChatGPT, Copilot, Lobe, ...).+4. **An agent usually already has a name** — one is seeded at creation and shown in \`<agent_meta>\`. Treat it as the user's name for the agent:+ - **\`<name>\` mirroring the role** (an agent created before names existed has no personal name, so the context falls back to its role): only give it a real personal name when the user asks for one, or when you are defining the agent from scratch. Do not rename an agent just because its name and role currently read the same.+ - **Still defining a brand-new agent** (no title and no system prompt yet): you may replace the seeded name with one that fits the persona the user just described. Mention the change in your reply.+ - **Established agent** (it has a title and a system prompt): never rename it unless the user asks. Configuring an agent is not a reason to re-name it.++**Example (user writes in Chinese, wants a health assistant):**+\`updateConfig({ meta: { name: "小艾", title: "健康助手", description: "..." } })\`++**Example (same request in English):**+\`updateConfig({ meta: { name: "Alice", title: "Health Assistant", description: "..." } })\`+</naming>+<display_conventions>When showing configuration to users, use semantic, user-friendly names instead of technical field names:| Technical Field | Display As (EN) | Display As (ZH) ||-----------------|-----------------|-----------------|+| name | Name | 名字 |+| title | Role | 角色 || systemRole | System Prompt | 系统提示词 || openingMessage | Opening Message | 开场白 || openingQuestions | Suggested Questions | 开场问题 |@@ -135,7 +161,8 @@ Always adapt to user's language. Use natural descriptions, not raw field names.- Plugins extend agent capabilities with external tools**Metadata:**-- title: Display name for the agent+- name: The agent's personal name (see \`<naming>\`)+- title: The role the agent plays, used as its label in the app- description: Brief description of what the agent does- avatar: Emoji or image URL for the agent's avatar- tags: Categories for organizationdiff --git a/packages/const/src/agentName.test.ts b/packages/const/src/agentName.test.tsnew file mode 100644index 00000000000..3ce4251003e--- /dev/null+++ b/packages/const/src/agentName.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest';++import { randomAgentName } from './agentName';++const sample = (locale?: string, times = 200) =>+ Array.from({ length: times }, () => randomAgentName(locale));++describe('randomAgentName', () => {+ it('returns a Chinese name for zh locales', () => {+ for (const locale of ['zh-CN', 'zh-TW', 'zh']) {+ for (const name of sample(locale, 50)) {+ expect(name).toMatch(/^\p{Script=Han}+$/u);+ }+ }+ });++ it('returns a Latin-script name for non-zh locales and when locale is unknown', () => {+ for (const locale of ['en-US', 'ja-JP', 'fr-FR', undefined]) {+ for (const name of sample(locale, 50)) {+ expect(name).toMatch(/^[A-Z]+$/i);+ }+ }+ });++ it('draws from a pool rather than always returning the same name', () => {+ expect(new Set(sample('en-US')).size).toBeGreaterThan(1);+ expect(new Set(sample('zh-CN')).size).toBeGreaterThan(1);+ });++ describe('exclude', () => {+ it('never returns an excluded name', () => {+ const taken = Array.from({ length: 200 }, () => randomAgentName('en-US')).slice(0, 5);++ for (let i = 0; i < 200; i++) {+ expect(taken).not.toContain(randomAgentName('en-US', taken));+ }+ });++ it('matches excluded names case- and whitespace-insensitively', () => {+ const name = randomAgentName('en-US');++ for (let i = 0; i < 200; i++) {+ expect(randomAgentName('en-US', [` ${name.toUpperCase()} `])).not.toBe(name);+ }+ });++ it('falls back to the full pool when everything is excluded', () => {+ const everything = Array.from({ length: 500 }, () => randomAgentName('zh-CN'));++ expect(randomAgentName('zh-CN', everything)).toMatch(/^\p{Script=Han}+$/u);+ });++ it('ignores blank entries', () => {+ expect(randomAgentName('en-US', ['', ' '])).toMatch(/^[A-Z]+$/i);+ });+ });+});diff --git a/packages/const/src/agentName.ts b/packages/const/src/agentName.tsnew file mode 100644index 00000000000..d202d8a23d5--- /dev/null+++ b/packages/const/src/agentName.ts@@ -0,0 +1,123 @@+/**+ * Default personal names assigned to a freshly created agent.+ *+ * An agent's `name` is the identity it is addressed by ("Alice", "小艾"), while+ * `title` describes the role it plays ("Health Assistant"). A brand-new agent has+ * no role yet, so we seed a name immediately — it gives the agent a face in the+ * sidebar before the Agent Builder conversation has produced anything, and the+ * builder is free to replace it with one that fits the finished role.+ *+ * Names are deliberately plain and common: they should read as a person, not as+ * a product. Nothing here may collide with an assistant brand (Siri, Alexa,+ * Claude, Gemini, ...) or with LobeHub's own naming.+ */++const EN_AGENT_NAMES = [+ 'Alice',+ 'Amber',+ 'Aria',+ 'Bella',+ 'Caleb',+ 'Chloe',+ 'Clara',+ 'Daisy',+ 'Elena',+ 'Ellie',+ 'Emma',+ 'Ethan',+ 'Felix',+ 'Grace',+ 'Hazel',+ 'Henry',+ 'Iris',+ 'Ivy',+ 'Jasper',+ 'Julia',+ 'Kai',+ 'Lena',+ 'Leo',+ 'Lily',+ 'Luna',+ 'Mason',+ 'Maya',+ 'Milo',+ 'Nina',+ 'Noah',+ 'Nora',+ 'Oliver',+ 'Owen',+ 'Ruby',+ 'Sophie',+ 'Theo',+ 'Vera',+ 'Violet',+ 'Wyatt',+ 'Zoe',+];++const ZH_AGENT_NAMES = [+ '一诺',+ '亦安',+ '以宁',+ '佳宁',+ '允之',+ '俊驰',+ '初夏',+ '南星',+ '可欣',+ '向晚',+ '嘉树',+ '子墨',+ '子期',+ '安然',+ '宁远',+ '小满',+ '小艾',+ '思远',+ '慕言',+ '文渊',+ '斯年',+ '明轩',+ '星野',+ '晓风',+ '望舒',+ '朝颜',+ '林深',+ '柏舟',+ '沐白',+ '清和',+ '溪言',+ '焕之',+ '燕来',+ '知微',+ '秋澜',+ '若初',+ '谨言',+ '远航',+ '逸尘',+ '静姝',+];++/**+ * Pick a random display name for a new agent, matching the user's language.+ *+ * Any `zh-*` locale gets a Chinese name; everything else falls back to the+ * English pool, which reads acceptably across Latin-script locales. Traditional+ * Chinese (`zh-TW`) shares the simplified pool for now.+ *+ * `exclude` keeps the caller from handing out a name it already has in view —+ * two agents called "Alice" in one sidebar are indistinguishable. When every+ * candidate is excluded the full pool comes back rather than nothing: a repeat+ * name beats no name.+ */+export const randomAgentName = (locale?: string, exclude?: Iterable<string>): string => {+ const fullPool = locale?.toLowerCase().startsWith('zh') ? ZH_AGENT_NAMES : EN_AGENT_NAMES;++ const taken = new Set(+ [...(exclude ?? [])].map((name) => name.trim().toLowerCase()).filter(Boolean),+ );+ const available = taken.size > 0 ? fullPool.filter((n) => !taken.has(n.toLowerCase())) : fullPool;+ const pool = available.length > 0 ? available : fullPool;++ return pool[Math.floor(Math.random() * pool.length)];+};diff --git a/packages/const/src/index.ts b/packages/const/src/index.tsindex e97ca8f0aab..ad56c4e496e 100644--- a/packages/const/src/index.ts+++ b/packages/const/src/index.ts@@ -1,4 +1,5 @@export * from './agentDocument';+export * from './agentName';export * from './bot';export * from './composio';export * from './currency';diff --git a/packages/context-engine/src/providers/AgentBuilderContextInjector.ts b/packages/context-engine/src/providers/AgentBuilderContextInjector.tsindex 5298db9dd2e..8b331e175ba 100644--- a/packages/context-engine/src/providers/AgentBuilderContextInjector.ts+++ b/packages/context-engine/src/providers/AgentBuilderContextInjector.ts@@ -52,6 +52,8 @@ export interface AgentBuilderContext {avatar?: string;backgroundColor?: string;description?: string;+ /** The agent's personal name, as opposed to `title` (the role it plays) */+ name?: string;tags?: string[];title?: string;};@@ -76,7 +78,13 @@ const defaultFormatAgentContext = (context: AgentBuilderContext): string => {// Add meta sectionif (context.meta) {- const metaFields: string[] = [];+ // `<name>` leads and always carries a usable label: an agent with no personal+ // name falls back to its role, the same rule the UI renders by. An empty+ // element was tried first and rejected — it made the builder treat "no name"+ // as a hole to fill, when the product answer is simply to use the role.+ const metaFields: string[] = [+ ` <name>${escapeXml(context.meta.name?.trim() || context.meta.title?.trim() || '')}</name>`,+ ];if (context.meta.title) metaFields.push(` <title>${escapeXml(context.meta.title)}</title>`);if (context.meta.description)metaFields.push(` <description>${escapeXml(context.meta.description)}</description>`);@@ -87,9 +95,7 @@ const defaultFormatAgentContext = (context: AgentBuilderContext): string => {if (context.meta.tags && context.meta.tags.length > 0)metaFields.push(` <tags>${context.meta.tags.join(', ')}</tags>`);- if (metaFields.length > 0) {- parts.push(`<agent_meta>\n${metaFields.join('\n')}\n</agent_meta>`);- }+ parts.push(`<agent_meta>\n${metaFields.join('\n')}\n</agent_meta>`);}// Add config sectiondiff --git a/packages/context-engine/src/providers/__tests__/AgentBuilderContextInjector.test.ts b/packages/context-engine/src/providers/__tests__/AgentBuilderContextInjector.test.tsindex 992c7c2bca3..52407c78f9a 100644--- a/packages/context-engine/src/providers/__tests__/AgentBuilderContextInjector.test.ts+++ b/packages/context-engine/src/providers/__tests__/AgentBuilderContextInjector.test.ts@@ -33,6 +33,36 @@ describe('AgentBuilderContextInjector', () => {expect(injected).not.toContain(`${head}...`);});+ it('should inject the agent name alongside the title', async () => {+ const injector = new AgentBuilderContextInjector({+ agentContext: {+ meta: { name: '小艾', title: '健康助手' },+ },+ enabled: true,+ });++ const result = await injector.process(createContext());+ const injected = result.messages[1].content;++ expect(injected).toContain('<name>小艾</name>');+ expect(injected).toContain('<title>健康助手</title>');+ });++ it('should fall back to the role when the agent has no personal name', async () => {+ const injector = new AgentBuilderContextInjector({+ agentContext: {+ meta: { title: '健康助手' },+ },+ enabled: true,+ });++ const result = await injector.process(createContext());+ const injected = result.messages[1].content;++ expect(injected).toContain('<name>健康助手</name>');+ expect(injected).toContain('<title>健康助手</title>');+ });+it('should truncate the systemRole only after 10000 characters', async () => {const head = 'A'.repeat(10_000);const tail = '\n## Hidden tail\nThis should not be injected.';diff --git a/packages/database/src/models/__tests__/agent.getAvatars.test.ts b/packages/database/src/models/__tests__/agent.getAvatars.test.tsindex 80a3f4d08c7..7a06380dfa0 100644--- a/packages/database/src/models/__tests__/agent.getAvatars.test.ts+++ b/packages/database/src/models/__tests__/agent.getAvatars.test.ts@@ -34,6 +34,7 @@ describe('AgentModel.getAgentAvatarsByIds', () => {avatar: '🤖',backgroundColor: '#ff0000',id: 'agent-av-1',+ name: 'Alice',slug: 'agent-av-1',title: 'Agent One',userId,@@ -53,10 +54,13 @@ describe('AgentModel.getAgentAvatarsByIds', () => {expect(result).toHaveLength(2);const agent1 = result.find((a) => a.id === 'agent-av-1');+ // `name` (personal name) and `title` (role) both come back — collapsing them+ // into one label is the caller's job, via `agentDisplayName`.expect(agent1).toEqual({avatar: '🤖',backgroundColor: '#ff0000',id: 'agent-av-1',+ name: 'Alice',title: 'Agent One',});});@@ -92,6 +96,7 @@ describe('AgentModel.getAgentAvatarsByIds', () => {avatar: DEFAULT_INBOX_AVATAR,backgroundColor: null,id: 'agent-inbox',+ name: null,title: DEFAULT_INBOX_TITLE,});});@@ -114,6 +119,7 @@ describe('AgentModel.getAgentAvatarsByIds', () => {avatar: '🤖',backgroundColor: '#123456',id: 'agent-inbox-custom',+ name: null,title: 'Custom Inbox',});});@@ -133,6 +139,12 @@ describe('AgentModel.getAgentAvatarsByIds', () => {const result = await model.getAgentAvatarsByIds(['agent-fields']);expect(result).toHaveLength(1);- expect(Object.keys(result[0]).sort()).toEqual(['avatar', 'backgroundColor', 'id', 'title']);+ expect(Object.keys(result[0]).sort()).toEqual([+ 'avatar',+ 'backgroundColor',+ 'id',+ 'name',+ 'title',+ ]);});});diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.tsindex f16c4a0e21c..4e338de184d 100644--- a/packages/database/src/models/__tests__/agent.test.ts+++ b/packages/database/src/models/__tests__/agent.test.ts@@ -845,6 +845,7 @@ describe('AgentModel', () => {description: 'hacked description',marketIdentifier: 'hacked-market-id',model: 'gpt-4', // non-protected field should still be applied+ name: 'Hacked Builder Name',tags: ['hacked'],title: 'Hacked Builder Title',});@@ -853,6 +854,7 @@ describe('AgentModel', () => {where: eq(agents.id, agent.id),});+ expect(result?.name).toBeNull();expect(result?.title).toBeNull();expect(result?.description).toBeNull();expect(result?.avatar).toBeNull();@@ -1241,6 +1243,7 @@ describe('AgentModel', () => {description: 'hacked description',marketIdentifier: 'hacked-market-id',model: 'gpt-4', // non-protected field should still be applied+ name: 'Hacked Builder Name',tags: ['hacked'],title: 'Hacked Builder Title',});@@ -1249,6 +1252,7 @@ describe('AgentModel', () => {where: eq(agents.id, agent.id),});+ expect(result?.name).toBeNull();expect(result?.title).toBeNull();expect(result?.description).toBeNull();expect(result?.avatar).toBeNull();diff --git a/packages/database/src/models/__tests__/agentSlug.test.ts b/packages/database/src/models/__tests__/agentSlug.test.tsnew file mode 100644index 00000000000..a0ccd1b36e0--- /dev/null+++ b/packages/database/src/models/__tests__/agentSlug.test.ts@@ -0,0 +1,140 @@+// @vitest-environment node+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { agents, users } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { AgentModel } from '../agent';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'slug-test-user-id';++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }]);+});++afterEach(async () => {+ await serverDB.delete(users);+});++describe('AgentModel.updateSlug', () => {+ it('should rename an ordinary agent', async () => {+ await serverDB+ .insert(agents)+ .values({ id: 'agent-rename', slug: 'old-slug', title: 'Agent', userId });++ const model = new AgentModel(serverDB, userId);+ expect(await model.updateSlug('agent-rename', 'new-slug')).toEqual({ success: true });++ const row = await serverDB.query.agents.findFirst({+ columns: { slug: true },+ where: (t, { eq }) => eq(t.id, 'agent-rename'),+ });+ expect(row?.slug).toBe('new-slug');+ });++ it('should normalize case and surrounding whitespace', async () => {+ await serverDB+ .insert(agents)+ .values({ id: 'agent-case', slug: 'agent-case', title: 'Agent', userId });++ const model = new AgentModel(serverDB, userId);+ expect(await model.updateSlug('agent-case', ' Mixed-Case ')).toEqual({ success: true });++ const row = await serverDB.query.agents.findFirst({+ columns: { slug: true },+ where: (t, { eq }) => eq(t.id, 'agent-case'),+ });+ expect(row?.slug).toBe('mixed-case');+ });++ it('should reject a malformed slug', async () => {+ await serverDB+ .insert(agents)+ .values({ id: 'agent-invalid', slug: 'agent-invalid', title: 'Agent', userId });++ const model = new AgentModel(serverDB, userId);+ expect(await model.updateSlug('agent-invalid', 'not a slug!')).toEqual({+ reason: 'invalid',+ success: false,+ });+ });++ it('should reject renaming TO a builtin slug', async () => {+ await serverDB+ .insert(agents)+ .values({ id: 'agent-to-builtin', slug: 'agent-to-builtin', title: 'Agent', userId });++ const model = new AgentModel(serverDB, userId);+ expect(await model.updateSlug('agent-to-builtin', BUILTIN_AGENT_SLUGS.inbox)).toEqual({+ reason: 'reserved',+ success: false,+ });+ });++ // Regression: a builtin agent IS its slug — `getBuiltinAgent` resolves it by+ // that string. Renaming one away used to succeed, which minted a second empty+ // inbox on the next lookup and stranded the original's history.+ it('should reject renaming a builtin agent AWAY from its slug', async () => {+ await serverDB.insert(agents).values({+ id: 'agent-inbox',+ slug: BUILTIN_AGENT_SLUGS.inbox,+ title: 'Lobe AI',+ userId,+ });++ const model = new AgentModel(serverDB, userId);+ expect(await model.updateSlug('agent-inbox', 'my-inbox')).toEqual({+ reason: 'builtin',+ success: false,+ });++ const row = await serverDB.query.agents.findFirst({+ columns: { slug: true },+ where: (t, { eq }) => eq(t.id, 'agent-inbox'),+ });+ expect(row?.slug).toBe(BUILTIN_AGENT_SLUGS.inbox);+ });++ // Saving the identity form without touching the slug must not trip the+ // builtin guard — the no-op check runs first.+ it('should accept a builtin agent re-submitting its own slug', async () => {+ await serverDB.insert(agents).values({+ id: 'agent-inbox-noop',+ slug: BUILTIN_AGENT_SLUGS.inbox,+ title: 'Lobe AI',+ userId,+ });++ const model = new AgentModel(serverDB, userId);+ expect(await model.updateSlug('agent-inbox-noop', BUILTIN_AGENT_SLUGS.inbox)).toEqual({+ success: true,+ });+ });++ it('should reject a slug already taken in the same scope', async () => {+ await serverDB.insert(agents).values([+ { id: 'agent-a', slug: 'agent-a', title: 'A', userId },+ { id: 'agent-b', slug: 'agent-b', title: 'B', userId },+ ]);++ const model = new AgentModel(serverDB, userId);+ expect(await model.updateSlug('agent-a', 'agent-b')).toEqual({+ reason: 'taken',+ success: false,+ });+ });++ it('should throw for an agent the caller does not own', async () => {+ await serverDB.insert(users).values([{ id: 'other-user' }]);+ await serverDB+ .insert(agents)+ .values({ id: 'agent-foreign', slug: 'agent-foreign', title: 'X', userId: 'other-user' });++ const model = new AgentModel(serverDB, userId);+ await expect(model.updateSlug('agent-foreign', 'stolen')).rejects.toThrow();+ });+});diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.tsindex bec59d65ace..b6d315eeb0b 100644--- a/packages/database/src/models/agent.ts+++ b/packages/database/src/models/agent.ts@@ -81,6 +81,7 @@ import {*/const AGENT_BUILDER_PROTECTED_FIELDS = ['title',+ 'name','description','avatar','backgroundColor',@@ -123,6 +124,13 @@ const IMMUTABLE_AGENT_FIELDS = ['workspaceId',] as const;+/**+ * Accepted shape for a user-chosen slug: lowercase words joined by single+ * hyphens, matching what `randomSlug` generates. No underscores — the agent+ * route tells an id from a slug by the underscore in every generated id.+ */+const AGENT_SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;+/** Slugs owned by builtin provisioning; user input must never set one. */const RESERVED_AGENT_SLUGS: ReadonlySet<string> = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS),@@ -166,6 +174,7 @@ export class AgentModel {backgroundColor: agents.backgroundColor,count: count(topics.id).as('count'),id: agents.id,+ name: agents.name,slug: agents.slug,title: agents.title,})@@ -481,6 +490,7 @@ export class AgentModel {backgroundColor: agents.backgroundColor,description: agents.description,id: agents.id,+ name: agents.name,slug: agents.slug,title: agents.title,userId: agents.userId,@@ -547,6 +557,7 @@ export class AgentModel {avatar: agents.avatar,backgroundColor: agents.backgroundColor,id: agents.id,+ name: agents.name,slug: agents.slug,title: agents.title,})@@ -561,10 +572,11 @@ export class AgentModel {* the inbox (other virtual agents excluded), ordered by `updatedAt DESC` with* the inbox pinned to the top.*- * Title fallback is fully owned here: the inbox resolves to the LobeAI- * default, and any other agent with a blank title resolves to- * `options.fallbackTitle` (default `null`, so a caller that omits it can let- * the client supply its own i18n default).+ * Returns `name` and `title` separately — resolving them into one label is the+ * caller's job (see `agentDisplayName`), since only the caller knows whether it+ * can render an i18n fallback. `title` is still normalized here for the inbox+ * (LobeAI default) and falls back to `options.fallbackTitle` when blank+ * (default `null`, so a client caller can supply its own i18n default).*/listMessengerBindableAgents = async (options?: {fallbackTitle?: string | null;@@ -575,6 +587,7 @@ export class AgentModel {id: string;isInbox: boolean;isPrivate: boolean;+ name: string | null;title: string | null;}>> => {@@ -585,6 +598,7 @@ export class AgentModel {avatar: agents.avatar,backgroundColor: agents.backgroundColor,id: agents.id,+ name: agents.name,slug: agents.slug,title: agents.title,visibility: agents.visibility,@@ -608,6 +622,7 @@ export class AgentModel {// rows are all implicitly private, so the flag stays false there to// signal "no grouping needed".isPrivate: Boolean(this.workspaceId) && visibility === 'private',+ name: meta.name ?? null,// The inbox title is already resolved by normalizeInboxAgentMeta; any// other blank title falls back to the caller-provided default.title: meta.title?.trim() || fallbackTitle,@@ -1436,6 +1451,81 @@ export class AgentModel {return { agentId: newAgent.id };};+ /**+ * Resolve a user-facing slug to its agent id, scoped by the caller's ownership+ * predicate. Returns `null` when no visible agent owns that slug — callers must+ * treat that as "not found" and must NOT distinguish it from "exists but not+ * yours", or the endpoint becomes an existence oracle for other users' agents.+ */+ resolveIdBySlug = async (slug: string): Promise<string | null> => {+ const trimmed = slug.trim();+ if (!trimmed) return null;++ const rows = await this.db+ .select({ id: agents.id })+ .from(agents)+ .where(and(this.ownership(), eq(agents.slug, trimmed)))+ .limit(1);++ return rows[0]?.id ?? null;+ };++ /**+ * Rename an agent's url slug.+ *+ * Deliberately its own method rather than a field on `updateConfig`: `slug`+ * stays in {@link IMMUTABLE_AGENT_FIELDS} so it can never ride along in a+ * passthrough config patch. Renaming needs validation the config path has no+ * place for — shape, reserved builtin slugs, and a uniqueness scope that+ * differs between personal and workspace rows.+ *+ * Returns a discriminated result instead of throwing so the caller can render+ * a field-level message; only a genuinely missing agent throws.+ */+ updateSlug = async (+ agentId: string,+ slug: string,+ ): Promise<{ reason?: 'builtin' | 'invalid' | 'reserved' | 'taken'; success: boolean }> => {+ const next = slug.trim().toLowerCase();++ if (!AGENT_SLUG_PATTERN.test(next)) return { reason: 'invalid', success: false };++ const current = await this.db.query.agents.findFirst({+ columns: { slug: true },+ where: and(eq(agents.id, agentId), this.ownership()),+ });+ if (!current) throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });+ if (current.slug === next) return { success: true };++ // A builtin agent IS its slug: `getBuiltinAgent` resolves it by that string,+ // so renaming one away would silently mint a second, empty inbox / page+ // agent and strand the original's history on an ordinary agent.+ if (current.slug && RESERVED_AGENT_SLUGS.has(current.slug))+ return { reason: 'builtin', success: false };+ if (RESERVED_AGENT_SLUGS.has(next)) return { reason: 'reserved', success: false };++ // Check within the same scope the unique indexes use, so the pre-check and+ // the constraint agree. The insert can still lose a race, hence the catch.+ const clash = await this.db+ .select({ id: agents.id })+ .from(agents)+ .where(and(this.ownership(), eq(agents.slug, next)))+ .limit(1);+ if (clash.length > 0) return { reason: 'taken', success: false };++ try {+ await this.db+ .update(agents)+ .set({ slug: next, updatedAt: new Date() })+ .where(and(eq(agents.id, agentId), this.ownership()));+ } catch {+ // Unique violation from a concurrent rename — same user-facing outcome.+ return { reason: 'taken', success: false };+ }++ return { success: true };+ };+/*** Get a builtin agent by slug, creating it if it doesn't exist.* Builtin agents are standalone agents not bound to sessions.diff --git a/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.ts b/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.tsindex fb071d2a5b4..c829bfd6858 100644--- a/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.ts+++ b/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.ts@@ -359,6 +359,7 @@ describe('AgentSignalNightlyReviewModel', () => {firstActivityAt: new Date('2026-05-03T14:00:00.000Z'),lastActivityAt: new Date('2026-05-03T14:00:00.000Z'),messageCount: 1,+ name: null,timezone: 'America/New_York',title: 'Legacy agent',topicCount: 1,@@ -369,6 +370,7 @@ describe('AgentSignalNightlyReviewModel', () => {firstActivityAt: new Date('2026-05-03T12:00:00.000Z'),lastActivityAt: new Date('2026-05-03T13:00:00.000Z'),messageCount: 2,+ name: null,timezone: 'America/New_York',title: 'Active agent',topicCount: 1,@@ -393,6 +395,7 @@ describe('AgentSignalNightlyReviewModel', () => {firstActivityAt: new Date('2026-05-03T12:00:00.000Z'),lastActivityAt: new Date('2026-05-03T13:00:00.000Z'),messageCount: 2,+ name: null,timezone: 'America/New_York',title: 'Active agent',topicCount: 1,diff --git a/packages/database/src/models/agentSignal/nightlyReview.ts b/packages/database/src/models/agentSignal/nightlyReview.tsindex 058a8a9bd83..a1b13777fff 100644--- a/packages/database/src/models/agentSignal/nightlyReview.ts+++ b/packages/database/src/models/agentSignal/nightlyReview.ts@@ -188,6 +188,7 @@ export class AgentSignalNightlyReviewModel {firstActivityAt: sql<Date>`MIN(${messages.createdAt})`.mapWith(parseAggregateTimestamp),lastActivityAt: sql<Date>`MAX(${messages.createdAt})`.mapWith(parseAggregateTimestamp),messageCount: count(messages.id),+ name: agents.name,slug: agents.slug,timezone: sql<string>`COALESCE(${userSettings.general}->>'timezone', 'UTC')`,title: agents.title,@@ -225,7 +226,7 @@ export class AgentSignalNightlyReviewModel {),),)- .groupBy(agents.id, agents.title, agents.slug, userSettings.general)+ .groupBy(agents.id, agents.title, agents.name, agents.slug, userSettings.general).orderBy(sql`MAX(${messages.createdAt}) DESC`);const rows = await (options.limit !== undefined ? query.limit(options.limit) : query);diff --git a/packages/database/src/models/brief.ts b/packages/database/src/models/brief.tsindex 3f7a5a248c8..5ad5cbed29c 100644--- a/packages/database/src/models/brief.ts+++ b/packages/database/src/models/brief.ts@@ -10,6 +10,7 @@ import { buildWorkspacePayload } from '../utils/workspace';export interface UnresolvedBriefRow {agentAvatar: string | null;agentBackgroundColor: string | null;+ agentName: string | null;agentRowId: string | null;agentTitle: string | null;brief: BriefItem;@@ -103,6 +104,7 @@ export class BriefModel {agentAvatar: agents.avatar,agentBackgroundColor: agents.backgroundColor,agentRowId: agents.id,+ agentName: agents.name,agentSlug: agents.slug,agentTitle: agents.title,brief: briefs,diff --git a/packages/database/src/models/chatGroup.ts b/packages/database/src/models/chatGroup.tsindex afbd728c501..95db18a8452 100644--- a/packages/database/src/models/chatGroup.ts+++ b/packages/database/src/models/chatGroup.ts@@ -637,6 +637,7 @@ export class ChatGroupModel {.select({agentId: chatGroupsAgents.agentId,description: agents.description,+ name: agents.name,role: chatGroupsAgents.role,title: agents.title,})diff --git a/packages/database/src/models/topicShare.ts b/packages/database/src/models/topicShare.tsindex 7e67ed843dc..85e226c7413 100644--- a/packages/database/src/models/topicShare.ts+++ b/packages/database/src/models/topicShare.ts@@ -126,6 +126,7 @@ export class TopicShareModel {agentBackgroundColor: agents.backgroundColor,agentId: topics.agentId,agentMarketIdentifier: agents.marketIdentifier,+ agentName: agents.name,agentSlug: agents.slug,agentTitle: agents.title,groupAvatar: chatGroups.avatar,@@ -168,6 +169,7 @@ export class TopicShareModel {avatar: agents.avatar,backgroundColor: agents.backgroundColor,id: agents.id,+ name: agents.name,slug: agents.slug,title: agents.title,})diff --git a/packages/database/src/repositories/agentGroup/index.ts b/packages/database/src/repositories/agentGroup/index.tsindex 3459822d911..71293eb16f4 100644--- a/packages/database/src/repositories/agentGroup/index.ts+++ b/packages/database/src/repositories/agentGroup/index.ts@@ -579,6 +579,7 @@ export class AgentGroupRepository {avatar: agents.avatar,description: agents.description,id: agents.id,+ name: agents.name,slug: agents.slug,title: agents.title,virtual: agents.virtual,diff --git a/packages/database/src/repositories/home/index.ts b/packages/database/src/repositories/home/index.tsindex 8150459b853..102ff7f126a 100644--- a/packages/database/src/repositories/home/index.ts+++ b/packages/database/src/repositories/home/index.ts@@ -85,6 +85,7 @@ export class HomeRepository {backgroundColor: agents.backgroundColor,description: agents.description,id: agents.id,+ name: agents.name,pinned: agents.pinned,sessionGroupId: sessions.groupId,sessionId: sessions.id,@@ -279,6 +280,7 @@ export class HomeRepository {backgroundColor: string | null;description: string | null;id: string;+ name: string | null;pinned: boolean | null;sessionGroupId: string | null;sessionId: string | null;@@ -350,6 +352,7 @@ export class HomeRepository {id: a.id,isPrivate: visibility === 'private',labels: agentLabelsMap.get(a.id),+ name: a.name,// Same personal-only reasoning as `groupId`: `sessions.pinned` is one// member's legacy pin, and pins are shared again.pinned: this.workspaceId ? (a.pinned ?? false) : (a.pinned ?? a.sessionPinned ?? false),@@ -473,6 +476,7 @@ export class HomeRepository {backgroundColor: agents.backgroundColor,description: agents.description,id: agents.id,+ name: agents.name,pinned: agents.pinned,sessionId: sessions.id,sessionPinned: sessions.pinned,@@ -535,6 +539,7 @@ export class HomeRepository {backgroundColor: a.backgroundColor,description: a.description,id: a.id,+ name: a.name,// Same personal-only reasoning as `groupId`: `sessions.pinned` is one// member's legacy pin, and pins are shared again.pinned: this.workspaceId ? (a.pinned ?? false) : (a.pinned ?? a.sessionPinned ?? false),diff --git a/packages/database/src/repositories/search/index.ts b/packages/database/src/repositories/search/index.tsindex 60170098ec5..02d7137e1be 100644--- a/packages/database/src/repositories/search/index.ts+++ b/packages/database/src/repositories/search/index.ts@@ -548,6 +548,7 @@ export class SearchRepo {createdAt: agents.createdAt,description: agents.description,id: agents.id,+ name: agents.name,score: sql<number>`paradedb.score(${agents.id})`.as('score'),slug: agents.slug,tags: agents.tags,@@ -662,6 +663,7 @@ export class SearchRepo {agentBackgroundColor: agents.backgroundColor,agentId: hits.agentId,agentMatchedId: agents.id,+ agentName: agents.name,agentSlug: agents.slug,agentTitle: agents.title,content: hits.content,@@ -764,6 +766,7 @@ export class SearchRepo {const rows = await this.db.select({agentId: hits.agentId,+ agentName: agents.name,agentSlug: agents.slug,agentTitle: agents.title,content: hits.content,diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex ae29856c328..cfb90a1d274 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -752,6 +752,26 @@ export default {'settingAgent.export.untitledFileName': 'agent-profile','settingAgent.name.placeholder': 'Enter agent name','settingAgent.name.title': 'Name',+ 'settingAgent.personalName.label': 'Name',+ 'settingAgent.personalName.placeholder': 'Give it a name, e.g. Alice',+ 'settingAgent.personalName.unnamed': 'This agent has no name yet',+ 'settingAgent.personalName.pickForMe': 'Name it for me',+ 'settingAgent.personalName.pickFailed': 'Could not save the name, please try again',+ 'settingAgent.identity.done': 'Done',+ 'settingAgent.identity.edit': 'Edit identity',+ 'settingAgent.identity.saveFailed': 'Could not save the identity, please try again',+ 'settingAgent.identity.untitled': 'Unnamed agent',+ 'settingAgent.role.label': 'Role',+ 'settingAgent.role.placeholder': 'What it is responsible for, e.g. Health Assistant',+ 'settingAgent.role.unset': 'No role set yet',+ 'settingAgent.slug.label': 'Identifier',+ 'settingAgent.slug.error.builtin': 'A builtin agent’s identifier can’t be changed',+ 'settingAgent.slug.error.invalid': 'Use lowercase letters, numbers and hyphens only',+ 'settingAgent.slug.error.reserved': 'This identifier is reserved',+ 'settingAgent.slug.error.taken': 'This identifier is already in use',+ 'settingAgent.slug.placeholder': 'url-identifier',+ 'settingAgent.slug.openWith': 'Open it directly with /agent/{{slug}}',+ 'settingAgent.slug.tooltip': 'The agent’s url identifier — open it with /agent/<slug>','settingAgent.prompt.desc':'Defines who this agent is, what it is responsible for, and how it works and responds. It serves as a core instruction in every conversation.','settingAgent.prompt.editorPlaceholder':diff --git a/packages/prompts/src/prompts/groupChat/index.ts b/packages/prompts/src/prompts/groupChat/index.tsindex f69162e64e3..adfcf1c0028 100644--- a/packages/prompts/src/prompts/groupChat/index.ts+++ b/packages/prompts/src/prompts/groupChat/index.ts@@ -1,4 +1,5 @@import type { UIChatMessage } from '@lobechat/types';+import { agentDisplayName } from '@lobechat/types';export interface GroupMemberInfo {id: string;@@ -66,7 +67,7 @@ export const buildGroupChatSystemPrompt = ({export interface SupervisorPromptParams {allowDM?: boolean;- availableAgents: Array<{ id: string; title?: string | null }>;+ availableAgents: Array<{ id: string; name?: string | null; title?: string | null }>;conversationHistory: string;scene?: 'casual' | 'productive';systemPrompt?: string;@@ -99,7 +100,7 @@ export const buildSupervisorPrompt = ({// Then include all agents...availableAgents.map((agent) => ({id: agent.id,- name: agent.title || agent.id,+ name: agentDisplayName(agent, agent.id),role: 'assistant',})),];diff --git a/packages/types/src/agent/displayName.test.ts b/packages/types/src/agent/displayName.test.tsnew file mode 100644index 00000000000..553c6453bee--- /dev/null+++ b/packages/types/src/agent/displayName.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from 'vitest';++import { agentDisplayName } from './displayName';++describe('agentDisplayName', () => {+ it('prefers the personal name over the role', () => {+ expect(agentDisplayName({ name: '小艾', title: '健康助手' })).toBe('小艾');+ });++ it('falls back to the title for an agent with no name', () => {+ expect(agentDisplayName({ name: null, title: 'Health Assistant' })).toBe('Health Assistant');+ });++ it('treats a blank name as absent so it cannot beat a real title', () => {+ expect(agentDisplayName({ name: ' ', title: 'Health Assistant' })).toBe('Health Assistant');+ });++ it('trims the resolved label', () => {+ expect(agentDisplayName({ name: ' Alice ' })).toBe('Alice');+ });++ it('uses the caller fallback when both fields are empty', () => {+ expect(agentDisplayName({ name: null, title: ' ' }, 'Custom Agent')).toBe('Custom Agent');+ expect(agentDisplayName(null, 'Custom Agent')).toBe('Custom Agent');+ });++ it('returns undefined without a fallback when nothing is set', () => {+ expect(agentDisplayName({})).toBeUndefined();+ expect(agentDisplayName(undefined)).toBeUndefined();+ });+});diff --git a/packages/types/src/agent/displayName.ts b/packages/types/src/agent/displayName.tsnew file mode 100644index 00000000000..6df122dac2c--- /dev/null+++ b/packages/types/src/agent/displayName.ts@@ -0,0 +1,45 @@+/**+ * How an agent is labelled across the product.+ *+ * An agent carries two identity fields: `name` is the personal name it is+ * addressed by ("Alice", "小艾"), `title` is the role it plays ("Health+ * Assistant"). The name wins wherever we show *who* the agent is, and `title`+ * remains the fallback — agents created before names existed have none, and a+ * user is free to clear it.+ *+ * Use this everywhere a name is rendered. Editing surfaces are the exception:+ * a form that writes `title` must bind to the raw `title`, never to the+ * resolved label, or typing into it would start from the wrong value.+ */++export interface AgentNameFields {+ name?: string | null;+ title?: string | null;+}++const firstNonBlank = (...values: (string | null | undefined)[]): string | undefined => {+ for (const value of values) {+ const trimmed = value?.trim();+ if (trimmed) return trimmed;+ }+ return undefined;+};++/**+ * Resolve the label to show for an agent: `name`, else `title`, else the+ * caller's fallback (usually a translated "Custom Agent").+ *+ * Blank-but-present values are treated as absent, so a whitespace-only title+ * saved by an editor can't beat a real name.+ */+export function agentDisplayName(agent: AgentNameFields | null | undefined): string | undefined;+export function agentDisplayName(+ agent: AgentNameFields | null | undefined,+ fallback: string,+): string;+export function agentDisplayName(+ agent: AgentNameFields | null | undefined,+ fallback?: string,+): string | undefined {+ return firstNonBlank(agent?.name, agent?.title, fallback);+}diff --git a/packages/types/src/agent/index.ts b/packages/types/src/agent/index.tsindex 0736910cd49..2d242ee3245 100644--- a/packages/types/src/agent/index.ts+++ b/packages/types/src/agent/index.ts@@ -1,6 +1,7 @@export * from './agencyConfig';export * from './agentConfig';export * from './chatConfig';+export * from './displayName';export * from './document';export * from './graph';export * from './item';diff --git a/packages/types/src/agent/item.ts b/packages/types/src/agent/item.tsindex 5a9276ccbc9..5f0459b1b51 100644--- a/packages/types/src/agent/item.ts+++ b/packages/types/src/agent/item.ts@@ -18,6 +18,8 @@ export interface AgentRankItem {backgroundColor: string | null;count: number;id: string;+ /** Personal name; resolve the label with `agentDisplayName(item, fallback)`. */+ name: string | null;title: string | null;}@@ -51,6 +53,14 @@ export interface LobeAgentConfig {*/model: string;+ /**+ * The agent's personal name (e.g. "Alice", "小艾") — the identity it is+ * addressed by. Distinct from {@link LobeAgentConfig.title}, which describes+ * the role it plays ("Health Assistant" / "健康助手"). Optional: agents+ * created before this field existed have no name.+ */+ name?: string;+/*** Opening message*/@@ -84,7 +94,8 @@ export interface LobeAgentConfig {systemRole: string;/**- * Agent title/name+ * The role the agent plays, shown as its display label across the app+ * (see {@link LobeAgentConfig.name} for the personal name).*/title?: string;@@ -116,6 +127,7 @@ export const CreateAgentSchema = z.object({fewShots: z.unknown().optional(),marketIdentifier: z.string().nullish(),model: z.string().nullish(),+ name: z.string().nullish(),openingMessage: z.string().nullish(),openingQuestions: z.array(z.string()).optional(),params: z.record(z.string(), z.unknown()).optional(),@@ -152,6 +164,8 @@ export interface AgentItem {/** Market agent identifier for published agents */marketIdentifier?: string | null;model?: string | null;+ /** Personal name of the agent — see {@link LobeAgentConfig.name}. */+ name?: string | null;openingMessage?: string | null;openingQuestions?: string[];params?: any;diff --git a/packages/types/src/home.ts b/packages/types/src/home.tsindex 47f8e7e0968..c76da1b27f9 100644--- a/packages/types/src/home.ts+++ b/packages/types/src/home.ts@@ -74,6 +74,11 @@ export interface SidebarAgentItem {* agents). Used by the agents list to render label tags and group by label.*/labels?: SidebarAgentLabel[];+ /**+ * The agent's personal name. Absent for chat groups and for agents created+ * before names existed — resolve the label with `agentDisplayName(item)`.+ */+ name?: string | null;pinned: boolean;sessionId?: string | null;/**diff --git a/packages/types/src/meta.ts b/packages/types/src/meta.tsindex 25279a865c0..6d580699df3 100644--- a/packages/types/src/meta.ts+++ b/packages/types/src/meta.ts@@ -14,10 +14,16 @@ export const LobeMetaDataSchema = z.object({* Market agent identifier for published agents*/marketIdentifier: z.string().optional(),+ /**+ * Personal name of an agent (e.g. "Alice", "小艾") — the identity it is+ * addressed by, as opposed to `title`, which names the role it plays.+ * Only agents carry it; other metadata holders leave it empty.+ */+ name: z.string().optional(),tags: z.array(z.string()).optional(),/**- * Name+ * Display label — for agents this is the role ("Health Assistant"), see `name`*/title: z.string().optional(),});diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.tsindex 6bae8879fe4..a7907d2d0ef 100644--- a/packages/types/src/task/index.ts+++ b/packages/types/src/task/index.ts@@ -354,6 +354,8 @@ export interface TaskDetailActivityAgent {avatar: string | null;backgroundColor: string | null;id: string;+ /** Personal name; renderers resolve the label with `agentDisplayName(agent, fallback)`. */+ name?: string | null;title: string | null;}diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex 01ac4d9778d..863498fb002 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -624,6 +624,8 @@ export interface SharedTopicData {avatar?: string | null;backgroundColor?: string | null;marketIdentifier?: string | null;+ /** Personal name; renderers resolve the label with `agentDisplayName`. */+ name?: string | null;slug?: string | null;title?: string | null;};@@ -636,6 +638,8 @@ export interface SharedTopicData {avatar: string | null;backgroundColor: string | null;id: string;+ /** Personal name; renderers resolve the label with `agentDisplayName`. */+ name?: string | null;title: string | null;}[];title?: string | null;diff --git a/src/components/MemberSelectionModal/MemberSelectionModal.tsx b/src/components/MemberSelectionModal/MemberSelectionModal.tsxindex 91ee1a67338..afad99a7b61 100644--- a/src/components/MemberSelectionModal/MemberSelectionModal.tsx+++ b/src/components/MemberSelectionModal/MemberSelectionModal.tsx@@ -1,5 +1,6 @@'use client';+import { agentDisplayName } from '@lobechat/types';import { ActionIcon, Avatar, Checkbox, Flexbox, List, SearchBar, Text, Tooltip } from '@lobehub/ui';import { Button, Switch } from '@lobehub/ui/base-ui';import { useHover } from 'ahooks';@@ -31,7 +32,7 @@ const AvailableAgentItem = memo<{const isHovering = useHover(ref);const _agentId = agent.config?.id;- const title = agent.meta?.title || t('defaultSession', { ns: 'common' });+ const title = agentDisplayName(agent.meta, t('defaultSession', { ns: 'common' }));const description = agent.meta?.description || '';const avatar = agent.meta?.avatar || DEFAULT_AVATAR;const avatarBackground = agent.meta?.backgroundColor;@@ -258,7 +259,7 @@ const MemberSelectionModal = memo<MemberSelectionModalProps>(if (!searchTerm.trim()) return availableAgents;return availableAgents.filter((agent) => {- const title = agent.meta?.title || '';+ const title = agentDisplayName(agent.meta) ?? '';const description = agent.meta?.description || '';const searchLower = searchTerm.toLowerCase();@@ -275,7 +276,7 @@ const MemberSelectionModal = memo<MemberSelectionModalProps>(const agent = agentSessions.find((session) => session.config.id === agentId);if (!agent) return null;- const title = agent.meta?.title || t('defaultSession', { ns: 'common' });+ const title = agentDisplayName(agent.meta, t('defaultSession', { ns: 'common' }));const avatar = agent.meta?.avatar || DEFAULT_AVATAR;const avatarBackground = agent.meta?.backgroundColor;const description = agent.meta?.description || '';diff --git a/src/features/AgentBreadcrumb/index.tsx b/src/features/AgentBreadcrumb/index.tsxindex 5f506e27fb4..c613e63ae64 100644--- a/src/features/AgentBreadcrumb/index.tsx+++ b/src/features/AgentBreadcrumb/index.tsx@@ -1,5 +1,6 @@'use client';+import { agentDisplayName } from '@lobechat/types';import { Icon, Text } from '@lobehub/ui';import { Breadcrumb as AntBreadcrumb } from 'antd';import { createStaticStyles } from 'antd-style';@@ -51,7 +52,9 @@ const AgentBreadcrumb = memo<AgentBreadcrumbProps>(({ agentId, extraItems, titleconst { t } = useTranslation(['chat', 'common']);const { pathname } = useLocation();const activeWorkspaceSlug = useActiveWorkspaceSlug();- const agentTitle = useAgentStore((s) => agentSelectors.getAgentMetaById(agentId)(s).title);+ const agentTitle = useAgentStore((s) =>+ agentDisplayName(agentSelectors.getAgentMetaById(agentId)(s)),+ );const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);const isInbox = !!inboxAgentId && agentId === inboxAgentId;const displayTitle = isInboxdiff --git a/src/features/AgentBuilder/SuggestionChips/useBuilderContext.ts b/src/features/AgentBuilder/SuggestionChips/useBuilderContext.tsindex 2f232e2ce51..10e5a67e376 100644--- a/src/features/AgentBuilder/SuggestionChips/useBuilderContext.ts+++ b/src/features/AgentBuilder/SuggestionChips/useBuilderContext.ts@@ -1,5 +1,10 @@import { type BuilderSuggestionMode } from '@lobechat/prompts';-import { type AgentGroupDetail, type AgentPluginEntry, getActivePluginIds } from '@lobechat/types';+import {+ agentDisplayName,+ type AgentGroupDetail,+ type AgentPluginEntry,+ getActivePluginIds,+} from '@lobechat/types';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -31,7 +36,7 @@ const buildAgentSummary = (agent?: AgentLike): string => {const plugins = getActivePluginIds(agent.plugins);const openingQuestions = agent.openingQuestions ?? [];return [- `Name: ${summarize(agent.title, '(untitled)')}`,+ `Name: ${summarize(agentDisplayName(agent), '(untitled)')}`,`Description: ${summarize(agent.description, '(none)')}`,`System role: ${role ? `set (${role.length} chars)` : 'NOT set yet'}`,`Tools enabled: ${plugins.length ? `${plugins.length} (${plugins.slice(0, 6).join(', ')})` : 'none'}`,diff --git a/src/features/AgentDocumentPage/Header/index.tsx b/src/features/AgentDocumentPage/Header/index.tsxindex 296dae40444..927af8af63f 100644--- a/src/features/AgentDocumentPage/Header/index.tsx+++ b/src/features/AgentDocumentPage/Header/index.tsx@@ -1,5 +1,6 @@'use client';+import { agentDisplayName } from '@lobechat/types';import { ActionIcon, Flexbox, Text } from '@lobehub/ui';import { DropdownMenu } from '@lobehub/ui/base-ui';import { cssVar, cx } from 'antd-style';@@ -58,7 +59,7 @@ const Header = memo<HeaderProps>(onClick={onBack}><Text style={{ color: cssVar.colorTextSecondary }}>- {meta.title || t('untitledAgent', { ns: 'chat' })}+ {agentDisplayName(meta, t('untitledAgent', { ns: 'chat' }))}</Text></Flexbox><Text style={{ color: cssVar.colorTextQuaternary, flexShrink: 0 }}>/</Text>diff --git a/src/features/AgentHome/AgentInfo.tsx b/src/features/AgentHome/AgentInfo.tsxindex 76878b2746c..607eb8f68c4 100644--- a/src/features/AgentHome/AgentInfo.tsx+++ b/src/features/AgentHome/AgentInfo.tsx@@ -1,5 +1,6 @@'use client';+import { agentDisplayName } from '@lobechat/types';import { Avatar, Flexbox, Markdown, Skeleton, Text } from '@lobehub/ui';import isEqual from 'fast-deep-equal';import { memo, useMemo } from 'react';@@ -29,8 +30,8 @@ const AgentInfo = memo(() => {const fontSize = useUserStore(userGeneralSettingsSelectors.fontSize);const displayTitle = isInbox- ? meta.title || 'Lobe AI'- : meta.title || t('defaultSession', { ns: 'common' });+ ? agentDisplayName(meta, 'Lobe AI')+ : agentDisplayName(meta, t('defaultSession', { ns: 'common' }));const message = useMemo(() => {if (openingMessage) return openingMessage;diff --git a/src/features/AgentIdentityModal/Content.tsx b/src/features/AgentIdentityModal/Content.tsxnew file mode 100644index 00000000000..c332c46e9b9--- /dev/null+++ b/src/features/AgentIdentityModal/Content.tsx@@ -0,0 +1,114 @@+'use client';++import { Flexbox, Input, Text } from '@lobehub/ui';+import { Button, useModalContext } from '@lobehub/ui/base-ui';+import { cssVar } from 'antd-style';+import { memo, type ReactNode } from 'react';+import { useTranslation } from 'react-i18next';++import { useAgentIdentityForm } from './useAgentIdentityForm';++interface FieldProps {+ children: ReactNode;+ hint?: ReactNode;+ label: string;+}++const Field = memo<FieldProps>(({ label, hint, children }) => (+ <Flexbox gap={6}>+ <Text type={'secondary'}>{label}</Text>+ {children}+ {hint}+ </Flexbox>+));++interface AgentIdentityContentProps {+ agentId: string;+}++/**+ * The three identity fields as a real form. They used to be inline inputs in the+ * profile header, which crowded it and left no room for a per-field label or+ * error. All behaviour lives in {@link useAgentIdentityForm}.+ */+const AgentIdentityContent = memo<AgentIdentityContentProps>(({ agentId }) => {+ const { t } = useTranslation(['setting', 'common']);+ const { close } = useModalContext();+ const form = useAgentIdentityForm({ agentId, onSaved: close });++ return (+ <Flexbox gap={20} padding={20}>+ <Field label={t('settingAgent.personalName.label', { ns: 'setting' })}>+ <Input+ autoFocus+ placeholder={t('settingAgent.personalName.placeholder', { ns: 'setting' })}+ value={form.name}+ onChange={(e) => form.setName(e.target.value)}+ />+ </Field>+ <Field label={t('settingAgent.role.label', { ns: 'setting' })}>+ <Input+ placeholder={t('settingAgent.role.placeholder', { ns: 'setting' })}+ value={form.title}+ onChange={(e) => form.setTitle(e.target.value)}+ />+ </Field>+ {/* A builtin agent's identifier is not an editable field at all, so it is+ not dressed as one: a disabled input still reads as "a control you+ can't use right now" and needs a sentence explaining itself. Rendering+ the bare marker states the fact and needs no caption. */}+ {form.slugLocked ? (+ <Field label={t('settingAgent.slug.label', { ns: 'setting' })}>+ <Text code style={{ alignSelf: 'flex-start', color: cssVar.colorTextSecondary }}>+ <span style={{ color: cssVar.colorTextTertiary }}>@</span>+ {form.slug}+ </Text>+ </Field>+ ) : (+ <Field+ label={t('settingAgent.slug.label', { ns: 'setting' })}+ hint={+ <Text style={{ fontSize: 12 }} type={form.error ? 'danger' : 'secondary'}>+ {/* Show the url the current input actually produces — a literal+ `<slug>` leaves the reader to do the substitution themselves,+ and it updates as they type. Only an empty field falls back to+ describing the field in the abstract. */}+ {form.error ??+ (form.slug.trim()+ ? t('settingAgent.slug.openWith', {+ ns: 'setting',+ slug: form.slug.trim().toLowerCase(),+ })+ : t('settingAgent.slug.tooltip', { ns: 'setting' }))}+ </Text>+ }+ >+ <Input+ placeholder={t('settingAgent.slug.placeholder', { ns: 'setting' })}+ prefix={'@'}+ status={form.error ? 'error' : undefined}+ value={form.slug}+ onChange={(e) => form.setSlug(e.target.value)}+ />+ </Field>+ )}+ <Flexbox horizontal gap={8} justify={'flex-end'}>+ <Button disabled={form.saving} onClick={() => close()}>+ {t('cancel', { ns: 'common' })}+ </Button>+ <Button+ disabled={form.saving}+ loading={form.saving}+ type={'primary'}+ onClick={() => {+ void form.save();+ }}+ >+ {t('save', { ns: 'common' })}+ </Button>+ </Flexbox>+ </Flexbox>+ );+});++export default AgentIdentityContent;diff --git a/src/features/AgentIdentityModal/index.tsx b/src/features/AgentIdentityModal/index.tsxnew file mode 100644index 00000000000..1690aa5d83f--- /dev/null+++ b/src/features/AgentIdentityModal/index.tsx@@ -0,0 +1,16 @@+'use client';++import { createModal } from '@lobehub/ui/base-ui';+import { t } from 'i18next';++import AgentIdentityContent from './Content';++/** Open the identity form (name / role / slug) for a specific agent. */+export const createAgentIdentityModal = (agentId: string) =>+ createModal({+ content: <AgentIdentityContent agentId={agentId} />,+ footer: null,+ styles: { content: { padding: 0 } },+ title: t('settingAgent.identity.edit', { ns: 'setting' }),+ width: 'min(90%, 460px)',+ });diff --git a/src/features/AgentIdentityModal/useAgentIdentityForm.test.ts b/src/features/AgentIdentityModal/useAgentIdentityForm.test.tsnew file mode 100644index 00000000000..1467f1ef324--- /dev/null+++ b/src/features/AgentIdentityModal/useAgentIdentityForm.test.ts@@ -0,0 +1,191 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useAgentIdentityForm } from './useAgentIdentityForm';++const mocks = vi.hoisted(() => ({+ agentMap: {} as Record<string, { name?: string; slug?: string; title?: string }>,+ refreshAgentConfig: vi.fn(),+ refreshAgentList: vi.fn(),+ updateAgentMetaById: vi.fn(),+ updateAgentSlug: vi.fn(),+}));++vi.mock('@/store/home', () => ({+ useHomeStore: (selector: (state: unknown) => unknown) =>+ selector({ refreshAgentList: mocks.refreshAgentList }),+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock('@/services/agent', () => ({+ agentService: {+ updateAgentSlug: (...args: unknown[]) => mocks.updateAgentSlug(...args),+ },+}));++vi.mock('@/store/agent', () => ({+ useAgentStore: (selector: (state: unknown) => unknown) =>+ selector({+ agentMap: mocks.agentMap,+ internal_refreshAgentConfig: mocks.refreshAgentConfig,+ updateAgentMetaById: mocks.updateAgentMetaById,+ }),+}));++vi.mock('@/store/agent/selectors', () => ({+ agentSelectors: {+ getAgentMetaById: (agentId: string) => (state: { agentMap: typeof mocks.agentMap }) =>+ state.agentMap[agentId] || {},+ getAgentSlugById: (agentId: string) => (state: { agentMap: typeof mocks.agentMap }) =>+ state.agentMap[agentId]?.slug,+ },+}));++const setup = () => {+ const onSaved = vi.fn();+ const view = renderHook(() => useAgentIdentityForm({ agentId: 'agent-a', onSaved }));+ return { onSaved, ...view };+};++beforeEach(() => {+ vi.clearAllMocks();+ mocks.agentMap = { 'agent-a': { name: 'Alice', slug: 'old-slug', title: 'Health Assistant' } };+ mocks.updateAgentSlug.mockResolvedValue({ success: true });+ mocks.updateAgentMetaById.mockResolvedValue(undefined);+});++describe('useAgentIdentityForm', () => {+ it('seeds every field from the agent it edits', () => {+ const { result } = setup();++ expect(result.current.name).toBe('Alice');+ expect(result.current.title).toBe('Health Assistant');+ expect(result.current.slug).toBe('old-slug');+ });++ it('saves name and role through the meta patch, leaving an unchanged slug alone', async () => {+ const { result, onSaved } = setup();++ act(() => result.current.setName('小艾'));+ await act(async () => {+ await result.current.save();+ });++ expect(mocks.updateAgentMetaById).toHaveBeenCalledExactlyOnceWith('agent-a', {+ name: '小艾',+ title: 'Health Assistant',+ });+ expect(mocks.updateAgentSlug).not.toHaveBeenCalled();+ expect(onSaved).toHaveBeenCalled();+ });++ // The sidebar keeps its own copy of the label; without a refresh the list+ // shows the old name while the profile shows the new one.+ it('refreshes the sidebar list after a rename', async () => {+ const { result } = setup();++ act(() => result.current.setName('小艾'));+ await act(async () => {+ await result.current.save();+ });++ expect(mocks.refreshAgentList).toHaveBeenCalledOnce();+ });++ it('does not refresh the sidebar when the save was rejected', async () => {+ mocks.updateAgentSlug.mockResolvedValue({ reason: 'taken', success: false });+ const { result } = setup();++ act(() => result.current.setSlug('taken-slug'));+ await act(async () => {+ await result.current.save();+ });++ expect(mocks.refreshAgentList).not.toHaveBeenCalled();+ });++ it('routes a slug change to its own endpoint, normalized to lowercase', async () => {+ const { result, onSaved } = setup();++ act(() => result.current.setSlug('New-Slug'));+ await act(async () => {+ await result.current.save();+ });++ expect(mocks.updateAgentSlug).toHaveBeenCalledExactlyOnceWith('agent-a', 'new-slug');+ expect(mocks.refreshAgentConfig).toHaveBeenCalledWith('agent-a');+ expect(onSaved).toHaveBeenCalled();+ });++ it('keeps the form open with a reason when the slug is rejected', async () => {+ mocks.updateAgentSlug.mockResolvedValue({ reason: 'taken', success: false });+ const { result, onSaved } = setup();++ act(() => result.current.setSlug('taken-slug'));+ await act(async () => {+ await result.current.save();+ });++ expect(result.current.error).toBe('settingAgent.slug.error.taken');+ // A rejected slug must not leave name/role persisted behind a closed form.+ expect(mocks.updateAgentMetaById).not.toHaveBeenCalled();+ expect(onSaved).not.toHaveBeenCalled();+ });++ describe('builtin agents', () => {+ beforeEach(() => {+ mocks.agentMap = { 'agent-a': { slug: 'inbox', title: 'Lobe AI' } };+ });++ it('locks the slug of a builtin agent', () => {+ const { result } = setup();++ expect(result.current.slugLocked).toBe(true);+ });++ it('leaves an ordinary agent unlocked', () => {+ mocks.agentMap = { 'agent-a': { slug: 'my-agent', title: 'Agent' } };+ const { result } = setup();++ expect(result.current.slugLocked).toBe(false);+ });++ // The lock is what the user sees, but the field could still be driven (a+ // stale render, a paste before the disabled prop lands) — an edit must never+ // reach the endpoint, or the builtin lookup would resolve to nothing and+ // mint a second, empty inbox.+ it('never sends a slug change for a builtin agent', async () => {+ const { result, onSaved } = setup();++ act(() => result.current.setSlug('my-inbox'));+ await act(async () => {+ await result.current.save();+ });++ expect(mocks.updateAgentSlug).not.toHaveBeenCalled();+ expect(mocks.updateAgentMetaById).toHaveBeenCalledExactlyOnceWith('agent-a', {+ name: '',+ title: 'Lobe AI',+ });+ expect(onSaved).toHaveBeenCalled();+ });+ });++ it('clears a stale error as soon as the slug is edited again', async () => {+ mocks.updateAgentSlug.mockResolvedValue({ reason: 'taken', success: false });+ const { result } = setup();++ act(() => result.current.setSlug('taken-slug'));+ await act(async () => {+ await result.current.save();+ });+ expect(result.current.error).toBeDefined();++ act(() => result.current.setSlug('another-slug'));++ expect(result.current.error).toBeUndefined();+ });+});diff --git a/src/features/AgentIdentityModal/useAgentIdentityForm.ts b/src/features/AgentIdentityModal/useAgentIdentityForm.tsnew file mode 100644index 00000000000..824f6494915--- /dev/null+++ b/src/features/AgentIdentityModal/useAgentIdentityForm.ts@@ -0,0 +1,87 @@+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import { agentService } from '@/services/agent';+import { useAgentStore } from '@/store/agent';+import { agentSelectors } from '@/store/agent/selectors';+import { useHomeStore } from '@/store/home';++interface UseAgentIdentityFormOptions {+ agentId: string;+ onSaved: () => void;+}++const BUILTIN_SLUGS: ReadonlySet<string> = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));++/**+ * Drives the three identity fields of the agent form.+ *+ * `name` and `title` ride the ordinary meta patch; `slug` has its own validated+ * endpoint (see `updateAgentSlug`). The slug is committed FIRST so a rejected+ * one can keep the form open with its reason — saving the other two first would+ * leave them persisted behind a form the user still has to fix.+ */+export const useAgentIdentityForm = ({ agentId, onSaved }: UseAgentIdentityFormOptions) => {+ const { t } = useTranslation('setting');++ const meta = useAgentStore(agentSelectors.getAgentMetaById(agentId));+ const slug = useAgentStore(agentSelectors.getAgentSlugById(agentId));+ const updateMetaById = useAgentStore((s) => s.updateAgentMetaById);+ const refreshAgentConfig = useAgentStore((s) => s.internal_refreshAgentConfig);+ const refreshAgentList = useHomeStore((s) => s.refreshAgentList);++ const [name, setName] = useState(meta.name || '');+ const [title, setTitle] = useState(meta.title || '');+ const [nextSlug, setNextSlug] = useState(slug || '');+ const [error, setError] = useState<string | undefined>();+ const [saving, setSaving] = useState(false);++ // A builtin agent IS its slug — `getBuiltinAgent` resolves it by that string,+ // so renaming one would mint a second, empty inbox / page agent. The server+ // refuses it too (`reason: 'builtin'`); locking the field here is what makes+ // that legible instead of a rejection after the fact.+ const slugLocked = !!slug && BUILTIN_SLUGS.has(slug);++ const save = async () => {+ setSaving(true);+ try {+ const trimmedSlug = slugLocked ? slug : nextSlug.trim().toLowerCase();+ if (trimmedSlug && trimmedSlug !== (slug || '')) {+ const result = await agentService.updateAgentSlug(agentId, trimmedSlug);+ if (!result.success) {+ setError(t(`settingAgent.slug.error.${result.reason ?? 'invalid'}`));+ return;+ }+ await refreshAgentConfig(agentId);+ }++ await updateMetaById(agentId, { name: name.trim(), title: title.trim() });+ // The sidebar holds its own copy of the label — without this the list keeps+ // showing the old name until something else revalidates. Same convention as+ // the sidebar's own rename popover.+ await refreshAgentList();+ onSaved();+ } catch {+ setError(t('settingAgent.identity.saveFailed'));+ } finally {+ setSaving(false);+ }+ };++ return {+ error,+ name,+ save,+ saving,+ setName,+ setSlug: (value: string) => {+ setNextSlug(value);+ setError(undefined);+ },+ setTitle,+ slug: nextSlug,+ slugLocked,+ title,+ };+};diff --git a/src/features/AgentProfileCard/AgentProfilePopup.tsx b/src/features/AgentProfileCard/AgentProfilePopup.tsxindex b6b45de2d06..77553d12db7 100644--- a/src/features/AgentProfileCard/AgentProfilePopup.tsx+++ b/src/features/AgentProfileCard/AgentProfilePopup.tsx@@ -1,6 +1,6 @@'use client';-import { type AgentItem } from '@lobechat/types';+import { agentDisplayName, type AgentItem } from '@lobechat/types';import { ModelIcon } from '@lobehub/icons';import { ActionIcon, Flexbox, Icon, Popover, Skeleton, Text } from '@lobehub/ui';import { SkillsIcon } from '@lobehub/ui/icons';@@ -52,7 +52,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({type AgentPreview = Pick<AgentItem,- 'avatar' | 'backgroundColor' | 'description' | 'model' | 'provider' | 'title'+ 'avatar' | 'backgroundColor' | 'description' | 'model' | 'name' | 'provider' | 'title'>;interface FetchedAgent extends Partial<AgentPreview> {@@ -101,6 +101,7 @@ const AgentProfilePopup = memo<AgentProfilePopupProps>(backgroundColor: fetched?.backgroundColor ?? agent?.backgroundColor,description: fetched?.description ?? agent?.description,model: fetched?.model ?? agent?.model,+ name: fetched?.name ?? agent?.name,provider: fetched?.provider ?? agent?.provider,title: fetched?.title ?? agent?.title,};@@ -130,7 +131,7 @@ const AgentProfilePopup = memo<AgentProfilePopupProps>(navigate(`/agent/${agentId}/profile`);};- const hasDisplay = Boolean(merged.title || merged.avatar || merged.description);+ const hasDisplay = Boolean(agentDisplayName(merged) || merged.avatar || merged.description);const showSkeleton = !hasDisplay && isLoading;const pluginCount = fetched?.plugins?.length ?? 0;@@ -204,7 +205,7 @@ const AgentProfilePopup = memo<AgentProfilePopupProps>(backgroundColor={merged.backgroundColor}description={merged.description}loading={isLoading && !merged.description}- title={merged.title || t('defaultSession', { ns: 'common' })}+ title={agentDisplayName(merged, t('defaultSession', { ns: 'common' }))}headerAction={groupId && canConfigure ? (<Flexbox horizontal align="center" justify="flex-end" style={{ paddingBlockStart: 0 }}>diff --git a/src/features/AgentRoute/useResolvedAgentRouteId.ts b/src/features/AgentRoute/useResolvedAgentRouteId.tsindex 6f68441305f..438fa952752 100644--- a/src/features/AgentRoute/useResolvedAgentRouteId.ts+++ b/src/features/AgentRoute/useResolvedAgentRouteId.ts@@ -1,10 +1,20 @@import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import useSWR from 'swr';+import { agentService } from '@/services/agent';import { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors';const builtinAgentSlugs = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));+/**+ * Every generated agent id carries an underscore (`agt_…`, `agent_…`) and no+ * generated slug does (`randomSlug` joins words with hyphens, and rename rejects+ * underscores). So the absence of one is what tells a slug route from an id+ * route — and a wrong guess only costs a lookup that resolves to null.+ */+const looksLikeSlug = (routeAgentId?: string) => !!routeAgentId && !routeAgentId.includes('_');+/*** Keep the inbox route valid while its persisted agent ID is still loading.* `useResolvedAgentRouteId` resolves the stable slug once initialization finishes.@@ -14,13 +24,27 @@ export const resolveInboxAgentRouteId = (inboxAgentId?: string) =>export const useResolvedAgentRouteId = (routeAgentId?: string) => {const isBuiltinSlug = !!routeAgentId && builtinAgentSlugs.has(routeAgentId);- const resolvedAgentId = useAgentStore(+ const builtinAgentId = useAgentStore(builtinAgentSelectors.getBuiltinAgentId(isBuiltinSlug ? routeAgentId! : ''),);+ // A user-chosen slug needs a server lookup; builtin slugs already resolve from+ // the store. Gated on the shape check so an ordinary `/agent/<id>` route never+ // pays for a request.+ const isCustomSlug = !isBuiltinSlug && looksLikeSlug(routeAgentId);+ const { data: slugAgentId } = useSWR(+ isCustomSlug ? ['agent-id-by-slug', routeAgentId] : null,+ () => agentService.resolveAgentIdBySlug(routeAgentId!),+ { revalidateOnFocus: false },+ );++ const resolvedAgentId = isBuiltinSlug ? builtinAgentId : (slugAgentId ?? undefined);+return {- agentId: isBuiltinSlug ? resolvedAgentId || routeAgentId : routeAgentId,+ agentId: resolvedAgentId || routeAgentId,isBuiltinSlug,+ /** The route param is a slug (builtin or user-chosen), so it must be swapped for an id. */+ isSlugRoute: isBuiltinSlug || isCustomSlug,resolvedAgentId,};};diff --git a/src/features/AgentSidebar/Header/Agent/index.tsx b/src/features/AgentSidebar/Header/Agent/index.tsxindex 3c95189fbdd..ae2ca16713b 100644--- a/src/features/AgentSidebar/Header/Agent/index.tsx+++ b/src/features/AgentSidebar/Header/Agent/index.tsx@@ -20,7 +20,7 @@ const Agent = memo<PropsWithChildren>(() => {const [isLoading, isInbox, title, avatar, backgroundColor] = useAgentStore((s) => [agentSelectors.isAgentConfigLoading(s),builtinAgentSelectors.isInboxAgent(s),- agentSelectors.currentAgentTitle(s),+ agentSelectors.currentAgentDisplayName(s),agentSelectors.currentAgentAvatar(s),agentSelectors.currentAgentBackgroundColor(s),]);diff --git a/src/features/AgentTaskManager/AgentSelectorAction.tsx b/src/features/AgentTaskManager/AgentSelectorAction.tsxindex 067d672dafc..8103833fc90 100644--- a/src/features/AgentTaskManager/AgentSelectorAction.tsx+++ b/src/features/AgentTaskManager/AgentSelectorAction.tsx@@ -1,3 +1,4 @@+import { agentDisplayName } from '@lobechat/types';import { Center, Flexbox, Popover } from '@lobehub/ui';import { createStaticStyles, cx } from 'antd-style';import isEqual from 'fast-deep-equal';@@ -120,7 +121,7 @@ const AgentSelectorAction = memo<AgentSelectorActionProps>(({ onAgentChange }) =<AgentItemactive={agent.id === agentId}agentId={agent.id}- agentTitle={agent.title || t('untitledAgent', { ns: 'chat' })}+ agentTitle={agentDisplayName(agent, t('untitledAgent', { ns: 'chat' }))}avatar={agent.avatar}key={agent.id}onAgentChange={handleAgentChange}diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskActivities.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskActivities.tsxindex bbb59b17a4a..b6939698066 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskActivities.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskActivities.tsx@@ -34,7 +34,8 @@ const toBriefItem = (act: TaskDetailActivity): BriefItem | null => {avatar: act.agent.avatar,backgroundColor: act.agent.backgroundColor,id: act.agent.id,- title: act.agent.title,+ name: act.agent.name ?? null,+ title: act.agent.title ?? null,}: null,agentId: act.agentId ?? null,diff --git a/src/features/AgentTasks/features/AssigneeAgentSelector.tsx b/src/features/AgentTasks/features/AssigneeAgentSelector.tsxindex 0a0d3b65bb2..c9a6bfd0fa7 100644--- a/src/features/AgentTasks/features/AssigneeAgentSelector.tsx+++ b/src/features/AgentTasks/features/AssigneeAgentSelector.tsx@@ -1,4 +1,5 @@import { DEFAULT_INBOX_AVATAR } from '@lobechat/const';+import { agentDisplayName } from '@lobechat/types';import { Flexbox, Popover, Text, Tooltip } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';import isEqual from 'fast-deep-equal';@@ -107,7 +108,7 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(description: null,id: inboxAgentId,pinned: false,- title: inboxMeta?.title || t('inbox.title', { ns: 'chat' }),+ title: agentDisplayName(inboxMeta, t('inbox.title', { ns: 'chat' })),type: 'agent' as const,updatedAt: new Date(),},@@ -128,13 +129,17 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(const filteredPrivate = useMemo(() => {const q = search.trim().toLowerCase();if (!q) return privateAgents;- return privateAgents.filter((agent) => (agent.title || '').toLowerCase().includes(q));+ return privateAgents.filter((agent) =>+ (agentDisplayName(agent) ?? '').toLowerCase().includes(q),+ );}, [privateAgents, search]);const filteredWorkspace = useMemo(() => {const q = search.trim().toLowerCase();if (!q) return workspaceAgents;- return workspaceAgents.filter((agent) => (agent.title || '').toLowerCase().includes(q));+ return workspaceAgents.filter((agent) =>+ (agentDisplayName(agent) ?? '').toLowerCase().includes(q),+ );}, [workspaceAgents, search]);// Flat order for keyboard navigation and activeIndex: private first, then workspace.@@ -208,7 +213,7 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(<AgentItemactive={flatIndex === activeIndex}agentId={agent.id}- agentTitle={agent.title || t('untitledAgent', { ns: 'chat' })}+ agentTitle={agentDisplayName(agent, t('untitledAgent', { ns: 'chat' }))}avatar={agent.avatar}heterogeneousType={agent.heterogeneousType}onAgentChange={handleAgentChange}diff --git a/src/features/AgentTasks/shared/Breadcrumb.tsx b/src/features/AgentTasks/shared/Breadcrumb.tsxindex 0c872ef4111..ed6684e2143 100644--- a/src/features/AgentTasks/shared/Breadcrumb.tsx+++ b/src/features/AgentTasks/shared/Breadcrumb.tsx@@ -1,3 +1,4 @@+import { agentDisplayName } from '@lobechat/types';import { Icon, Text } from '@lobehub/ui';import { Breadcrumb as AntBreadcrumb } from 'antd';import { ChevronRight } from 'lucide-react';@@ -62,7 +63,7 @@ const Breadcrumb = memo<BreadcrumbProps>(({ taskId }) => {type={taskId ? undefined : 'secondary'}weight={500}>- {agentMeta.title}+ {agentDisplayName(agentMeta)}</Text>),}diff --git a/src/features/AgentTasks/shared/useAgentDisplayMeta.ts b/src/features/AgentTasks/shared/useAgentDisplayMeta.tsindex ebd77b21013..918829beec1 100644--- a/src/features/AgentTasks/shared/useAgentDisplayMeta.ts+++ b/src/features/AgentTasks/shared/useAgentDisplayMeta.ts@@ -1,4 +1,5 @@import { DEFAULT_AVATAR } from '@lobechat/const';+import { agentDisplayName } from '@lobechat/types';import { cssVar } from 'antd-style';import { useTranslation } from 'react-i18next';@@ -41,7 +42,11 @@ export const useAgentDisplayMeta = (const isInbox = isInboxAgentId(agentId, inboxAgentId);const sidebarAvatar = typeof sidebarAgent?.avatar === 'string' ? sidebarAgent.avatar : undefined;const hasResolvedMeta =- isInbox || !!meta?.avatar || !!meta?.backgroundColor || !!meta?.title?.trim() || !!sidebarAgent;+ isInbox ||+ !!meta?.avatar ||+ !!meta?.backgroundColor ||+ !!agentDisplayName(meta) ||+ !!sidebarAgent;if (!fallbackToDefault && !hasResolvedMeta) return undefined;@@ -50,8 +55,8 @@ export const useAgentDisplayMeta = (backgroundColor:meta?.backgroundColor || sidebarAgent?.backgroundColor || cssVar.colorBgContainer,title:- meta?.title?.trim() ||- sidebarAgent?.title ||+ agentDisplayName(meta) ||+ agentDisplayName(sidebarAgent) ||(isInbox ? t('inbox.title', { ns: 'chat' }) : t('defaultSession', { ns: 'common' })),};};diff --git a/src/features/AgentTopicManager/MoveTopicsModal/Content.tsx b/src/features/AgentTopicManager/MoveTopicsModal/Content.tsxindex b534ec99d50..bda851aa560 100644--- a/src/features/AgentTopicManager/MoveTopicsModal/Content.tsx+++ b/src/features/AgentTopicManager/MoveTopicsModal/Content.tsx@@ -1,6 +1,7 @@'use client';import { AGENT_CHAT_URL, DEFAULT_INBOX_AVATAR } from '@lobechat/const';+import { agentDisplayName } from '@lobechat/types';import { Flexbox, Icon, Text } from '@lobehub/ui';import { Button, toast, useModalContext } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';@@ -86,7 +87,7 @@ const MoveTopicsContent = memo<MoveTopicsContentProps>(({ onMoved, sourceAgentIddescription: null,id: inboxAgentId,pinned: false,- title: inboxMeta?.title || t('inbox.title', { ns: 'chat' }),+ title: agentDisplayName(inboxMeta, t('inbox.title', { ns: 'chat' })),type: 'agent' as const,updatedAt: new Date(),},@@ -99,7 +100,7 @@ const MoveTopicsContent = memo<MoveTopicsContentProps>(({ onMoved, sourceAgentIdconst filteredAgents = useMemo(() => {const q = search.trim().toLowerCase();if (!q) return targetAgents;- return targetAgents.filter((a) => (a.title || '').toLowerCase().includes(q));+ return targetAgents.filter((a) => (agentDisplayName(a) ?? '').toLowerCase().includes(q));}, [targetAgents, search]);const handleConfirm = async () => {@@ -148,14 +149,14 @@ const MoveTopicsContent = memo<MoveTopicsContentProps>(({ onMoved, sourceAgentId<AgentItemactive={false}agentId={agent.id}- agentTitle={agent.title || t('untitledAgent', { ns: 'chat' })}+ agentTitle={agentDisplayName(agent, t('untitledAgent', { ns: 'chat' }))}avatar={agent.avatar}key={agent.id}onClose={() => {}}onAgentChange={() => {setTarget({id: agent.id,- title: agent.title || t('untitledAgent', { ns: 'chat' }),+ title: agentDisplayName(agent, t('untitledAgent', { ns: 'chat' })),});setStep('confirm');}}diff --git a/src/features/AgentViewAll/AgentCard.tsx b/src/features/AgentViewAll/AgentCard.tsxindex d139675b49c..85b8c10ecb2 100644--- a/src/features/AgentViewAll/AgentCard.tsx+++ b/src/features/AgentViewAll/AgentCard.tsx@@ -1,13 +1,14 @@'use client';import { AGENT_CHAT_URL, DEFAULT_AVATAR, GROUP_CHAT_URL } from '@lobechat/const';-import { type SidebarAgentItem } from '@lobechat/types';+import { agentDisplayName, type SidebarAgentItem } from '@lobechat/types';import {Avatar,Block,ContextMenuTrigger,Flexbox,type MenuProps,+ Tag,Text,Tooltip,} from '@lobehub/ui';@@ -96,7 +97,12 @@ interface AgentCardProps {const AgentCard = memo<AgentCardProps>(({ author, item, onToggleSidebar, showAuthor, sidebarHidden }) => {const { t } = useTranslation('common');- const { description, id, title, type, updatedAt } = item;+ const { description, id, type, updatedAt } = item;+ // Groups have no personal name, so this resolves to their title.+ const displayTitle = agentDisplayName(item, t('agentViewAll.untitled'));+ // Keep the role visible beside a personal name (same as the sidebar row) —+ // otherwise a named agent's role disappears from this list entirely.+ const roleTag = item.name?.trim() && item.title?.trim() ? item.title : undefined;const [anchor, setAnchor] = useState<HTMLElement | null>(null);// Right-click support — same bridge as AgentRow: the hook-bearing menu@@ -112,7 +118,7 @@ const AgentCard = memo<AgentCardProps>(return (<ContextMenuTrigger items={getContextMenuItems}><WorkspaceLink- aria-label={title || undefined}+ aria-label={displayTitle}className={cardStyles.link}ref={setAnchor}to={type === 'group' ? GROUP_CHAT_URL(id) : AGENT_CHAT_URL(id, false)}@@ -121,9 +127,16 @@ const AgentCard = memo<AgentCardProps>(<Block clickable className={cardStyles.card} height={'100%'} variant={'outlined'}><Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}><AgentAvatar item={item} size={24} />- <Text ellipsis style={{ flex: 1, minWidth: 0 }} weight={600}>- {title || t('agentViewAll.untitled')}- </Text>+ <Flexbox horizontal align={'center'} flex={1} gap={6} style={{ minWidth: 0 }}>+ <Text ellipsis style={{ minWidth: 0 }} weight={600}>+ {displayTitle}+ </Text>+ {roleTag ? (+ <Tag size={'small'} style={{ flex: 'none' }}>+ {roleTag}+ </Tag>+ ) : null}+ </Flexbox><Flexboxflex={'none'}onClick={(e) => {diff --git a/src/features/AgentViewAll/AgentRow.tsx b/src/features/AgentViewAll/AgentRow.tsxindex ea43946a3c5..4eada4b34bc 100644--- a/src/features/AgentViewAll/AgentRow.tsx+++ b/src/features/AgentViewAll/AgentRow.tsx@@ -1,13 +1,14 @@'use client';import { AGENT_CHAT_URL, DEFAULT_AVATAR, GROUP_CHAT_URL } from '@lobechat/const';-import { type SidebarAgentItem } from '@lobechat/types';+import { agentDisplayName, type SidebarAgentItem } from '@lobechat/types';import {ActionIcon,Avatar,ContextMenuTrigger,Flexbox,type MenuProps,+ Tag,Text,Tooltip,} from '@lobehub/ui';@@ -107,7 +108,13 @@ interface AgentRowProps {const AgentRow = memo<AgentRowProps>(({ author, item, onToggleSidebar, showAuthor, sidebarHidden }) => {const { t } = useTranslation('common');- const { id, title, type, updatedAt } = item;+ const { id, type, updatedAt } = item;+ // Groups have no personal name, so this resolves to their title.+ const displayTitle = agentDisplayName(item, t('agentViewAll.untitled'));+ // When the personal name won the label the role would otherwise vanish from+ // this list entirely — keep it beside the name as a muted tag, the same way+ // the sidebar row does. No tag when the label already IS the role.+ const roleTag = item.name?.trim() && item.title?.trim() ? item.title : undefined;const [anchor, setAnchor] = useState<HTMLElement | null>(null);// Right-click support (Task-List-style): the hook-bearing menu mounts on@@ -140,7 +147,7 @@ const AgentRow = memo<AgentRowProps>(onPointerEnter={activateMenu}><WorkspaceLink- aria-label={title || undefined}+ aria-label={displayTitle}className={styles.identity}to={type === 'group' ? GROUP_CHAT_URL(id) : AGENT_CHAT_URL(id, false)}>@@ -148,9 +155,16 @@ const AgentRow = memo<AgentRowProps>(<Flexbox flex={1} style={{ minWidth: 0 }}>{/* Single-line row (Linear-style density) — the description onlyrenders in card mode, where there is room to browse. */}- <Text ellipsis className={'agent-row-title'} weight={500}>- {title || t('agentViewAll.untitled')}- </Text>+ <Flexbox horizontal align={'center'} gap={6} style={{ minWidth: 0 }}>+ <Text ellipsis className={'agent-row-title'} weight={500}>+ {displayTitle}+ </Text>+ {roleTag ? (+ <Tag size={'small'} style={{ flex: 'none' }}>+ {roleTag}+ </Tag>+ ) : null}+ </Flexbox></Flexbox></WorkspaceLink>{/* Trailing cluster (Task-list-style): label pills + author avatar +diff --git a/src/features/AgentViewAll/AgentViewAllPage.tsx b/src/features/AgentViewAll/AgentViewAllPage.tsxindex 9cab5d026bd..8a3afa97e96 100644--- a/src/features/AgentViewAll/AgentViewAllPage.tsx+++ b/src/features/AgentViewAll/AgentViewAllPage.tsx@@ -1,7 +1,7 @@'use client';import { DEFAULT_AVATAR } from '@lobechat/const';-import { type SidebarAgentItem } from '@lobechat/types';+import { agentDisplayName, type SidebarAgentItem } from '@lobechat/types';import { Avatar, Center, Empty, Flexbox, Icon, SearchBar, Text, Tooltip } from '@lobehub/ui';import { Button, DropdownMenu, Segmented, toast } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar, cx } from 'antd-style';@@ -299,6 +299,7 @@ const AgentViewAllPage = memo(() => {let matched = query? items.filter((item) =>+ item.name?.toLowerCase().includes(query) ||item.title?.toLowerCase().includes(query) ||item.description?.toLowerCase().includes(query),)@@ -313,7 +314,10 @@ const AgentViewAllPage = memo(() => {const direction = orderDirection === 'asc' ? 1 : -1;return [...matched].sort((a, b) => {- if (orderBy === 'title') return direction * (a.title ?? '').localeCompare(b.title ?? '');+ // Sort on the label the rows actually render, not the raw title — otherwise+ // a list of personal names comes back ordered by their hidden roles.+ if (orderBy === 'title')+ return direction * agentDisplayName(a, '').localeCompare(agentDisplayName(b, ''));if (orderBy === 'author') return direction * authorName(a).localeCompare(authorName(b));return direction * (dayjs(a.updatedAt).valueOf() - dayjs(b.updatedAt).valueOf());});diff --git a/src/features/AgentViewAll/ItemActions.tsx b/src/features/AgentViewAll/ItemActions.tsxindex d6fbc687080..9a646997d49 100644--- a/src/features/AgentViewAll/ItemActions.tsx+++ b/src/features/AgentViewAll/ItemActions.tsx@@ -1,6 +1,6 @@'use client';-import { type SidebarAgentItem } from '@lobechat/types';+import { agentDisplayName, type SidebarAgentItem } from '@lobechat/types';import type { MenuProps } from '@lobehub/ui';import { ActionIcon, Icon } from '@lobehub/ui';import { DropdownMenu } from '@lobehub/ui/base-ui';@@ -137,7 +137,7 @@ ActionsDropdown.displayName = 'ActionsDropdown';const AgentItemActions = memo<ItemActionsProps>(({ anchor, item, ...rest }) => {const { t } = useTranslation('common');const { openCreateGroupModal } = useAgentModal();- const { avatar, backgroundColor, id, pinned, slug, title, userId, visibility } = item;+ const { avatar, backgroundColor, id, pinned, slug, userId, visibility } = item;const customAvatar = typeof avatar === 'string' ? avatar : undefined;@@ -156,7 +156,7 @@ const AgentItemActions = memo<ItemActionsProps>(({ anchor, item, ...rest }) => {openCreateGroupModal: handleOpenCreateGroupModal,pinned: pinned ?? false,slug,- title: title || t('agentViewAll.untitled'),+ title: agentDisplayName(item, t('agentViewAll.untitled')),userId,visibility,});diff --git a/src/features/AgentViewAll/SidebarAgentsSection.tsx b/src/features/AgentViewAll/SidebarAgentsSection.tsxindex 0e31917cbb5..25d103df16a 100644--- a/src/features/AgentViewAll/SidebarAgentsSection.tsx+++ b/src/features/AgentViewAll/SidebarAgentsSection.tsx@@ -1,8 +1,8 @@'use client';import { AGENT_CHAT_URL, GROUP_CHAT_URL } from '@lobechat/const';-import { type SidebarAgentItem } from '@lobechat/types';-import { Block, ContextMenuTrigger, Flexbox, Icon, type MenuProps, Text } from '@lobehub/ui';+import { agentDisplayName, type SidebarAgentItem } from '@lobechat/types';+import { Block, ContextMenuTrigger, Flexbox, Icon, type MenuProps, Tag, Text } from '@lobehub/ui';import { createStaticStyles, cssVar, responsive } from 'antd-style';import { ChevronDownIcon, ChevronUpIcon } from 'lucide-react';import { memo, useCallback, useRef, useState } from 'react';@@ -101,7 +101,11 @@ interface SidebarMiniCardProps {// Actions live entirely in the right-click menu (same as rows/cards).const SidebarMiniCard = memo<SidebarMiniCardProps>(({ item, onToggleSidebar }) => {const { t } = useTranslation('common');- const { description, id, title, type } = item;+ const { description, id, type } = item;+ // Groups have no personal name, so this resolves to their title.+ const displayTitle = agentDisplayName(item, t('agentViewAll.untitled'));+ // Keep the role visible beside a personal name (same as the sidebar row).+ const roleTag = item.name?.trim() && item.title?.trim() ? item.title : undefined;const [anchor, setAnchor] = useState<HTMLElement | null>(null);const [menuActivated, setMenuActivated] = useState(false);@@ -118,7 +122,7 @@ const SidebarMiniCard = memo<SidebarMiniCardProps>(({ item, onToggleSidebar }) =treats it as one cell. The headless ItemActions lives INSIDE it —rendering it as a sibling would add a phantom grid item. */}<WorkspaceLink- aria-label={title || undefined}+ aria-label={displayTitle}className={styles.link}ref={setAnchor}to={type === 'group' ? GROUP_CHAT_URL(id) : AGENT_CHAT_URL(id, false)}@@ -127,9 +131,14 @@ const SidebarMiniCard = memo<SidebarMiniCardProps>(({ item, onToggleSidebar }) =<Block clickable className={styles.card} height={'100%'} variant={'outlined'}><Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}><AgentAvatar item={item} size={24} />- <Text ellipsis style={{ flex: 1, minWidth: 0 }} weight={600}>- {title || t('agentViewAll.untitled')}+ <Text ellipsis style={{ minWidth: 0 }} weight={600}>+ {displayTitle}</Text>+ {roleTag ? (+ <Tag size={'small'} style={{ flex: 'none' }}>+ {roleTag}+ </Tag>+ ) : null}</Flexbox>{description ? (<Text className={styles.description} fontSize={12} type={'secondary'}>diff --git a/src/features/ChatInput/ActionBar/Mention/index.tsx b/src/features/ChatInput/ActionBar/Mention/index.tsxindex 051b4d9bf3c..7016430e35b 100644--- a/src/features/ChatInput/ActionBar/Mention/index.tsx+++ b/src/features/ChatInput/ActionBar/Mention/index.tsx@@ -1,3 +1,4 @@+import { agentDisplayName } from '@lobechat/types';import { type ItemType } from '@lobehub/ui';import { Avatar } from '@lobehub/ui';import { AtSign } from 'lucide-react';@@ -36,7 +37,7 @@ const Mention = memo(() => {/>),key: agent.id,- label: agent.title || agent.id,+ label: agentDisplayName(agent, agent.id),onClick: () => handleMemberSelect(agent.id),});});diff --git a/src/features/ChatInput/InputEditor/useMentionCategories.tsx b/src/features/ChatInput/InputEditor/useMentionCategories.tsxindex 4bd5b14aeea..e8de834cb54 100644--- a/src/features/ChatInput/InputEditor/useMentionCategories.tsx+++ b/src/features/ChatInput/InputEditor/useMentionCategories.tsx@@ -1,3 +1,4 @@+import { agentDisplayName } from '@lobechat/types';import { Avatar, Icon } from '@lobehub/ui';import { SkillsIcon } from '@lobehub/ui/icons';import isEqual from 'fast-deep-equal';@@ -58,7 +59,7 @@ export const useMentionCategories = (): MentionCategory[] => {/>),key: `agent-${agent.id}`,- label: agent.title || 'Untitled Agent',+ label: agentDisplayName(agent, 'Untitled Agent'),metadata: {id: agent.id,timestamp: agent.updatedAt ? new Date(agent.updatedAt).getTime() : 0,diff --git a/src/features/CommandMenu/AskAIMenu.tsx b/src/features/CommandMenu/AskAIMenu.tsxindex e5e6ad237c2..60e791a2f76 100644--- a/src/features/CommandMenu/AskAIMenu.tsx+++ b/src/features/CommandMenu/AskAIMenu.tsx@@ -1,4 +1,5 @@import { DEFAULT_AVATAR, DEFAULT_INBOX_AVATAR } from '@lobechat/const';+import { agentDisplayName } from '@lobechat/types';import { Avatar } from '@lobehub/ui';import { GroupBotSquareIcon } from '@lobehub/ui/icons';import { Command } from 'cmdk';@@ -87,7 +88,7 @@ const AskAIMenu = memo(() => {{agents.map((agent) => (<CommandItemkey={agent.id}- title={agent.title || t('defaultAgent')}+ title={agentDisplayName(agent, t('defaultAgent'))}trailingLabel={t('cmdk.search.agent')}value={`agent-${agent.id}`}variant="detailed"diff --git a/src/features/CommandMenu/AskAgentCommands.tsx b/src/features/CommandMenu/AskAgentCommands.tsxindex b3e3c44035b..60d0b55943d 100644--- a/src/features/CommandMenu/AskAgentCommands.tsx+++ b/src/features/CommandMenu/AskAgentCommands.tsx@@ -1,4 +1,5 @@import { DEFAULT_AVATAR, DEFAULT_INBOX_AVATAR } from '@lobechat/const';+import { agentDisplayName } from '@lobechat/types';import { Avatar, preventDefault } from '@lobehub/ui';import { Command } from 'cmdk';import { memo, useMemo } from 'react';@@ -36,7 +37,7 @@ const AskAgentCommands = memo(() => {}return agents.filter((agent) => {- const title = (agent.title || '').toLowerCase();+ const title = (agentDisplayName(agent) ?? '').toLowerCase();return title.includes(mentionQuery);}).slice(0, 10);@@ -77,12 +78,12 @@ const AskAgentCommands = memo(() => {{filteredAgents.map((agent) => (<Command.Itemkey={agent.id}- value={`@${agent.title || 'agent'}-${agent.id}`}+ value={`@${agentDisplayName(agent, 'agent')}-${agent.id}`}onMouseDown={preventDefault}onSelect={() =>handleAgentSelect(agent.id,- agent.title || t('defaultAgent'),+ agentDisplayName(agent, t('defaultAgent')),typeof agent.avatar === 'string' ? agent.avatar : DEFAULT_AVATAR,)}@@ -94,7 +95,7 @@ const AskAgentCommands = memo(() => {size={18}/><div className={styles.itemContent}>- <div className={styles.itemLabel}>@{agent.title || t('defaultAgent')}</div>+ <div className={styles.itemLabel}>@{agentDisplayName(agent, t('defaultAgent'))}</div></div></Command.Item>))}diff --git a/src/features/CommandMenu/SearchResults.tsx b/src/features/CommandMenu/SearchResults.tsxindex 04083525f69..82a73f4f293 100644--- a/src/features/CommandMenu/SearchResults.tsx+++ b/src/features/CommandMenu/SearchResults.tsx@@ -4,6 +4,7 @@ import {GROUP_CHAT_TOPIC_URL,GROUP_CHAT_URL,} from '@lobechat/const';+import { agentDisplayName } from '@lobechat/types';import { Avatar, Flexbox } from '@lobehub/ui';import { Command } from 'cmdk';import dayjs from 'dayjs';@@ -271,7 +272,9 @@ const SearchResults = memo<SearchResultsProps>(background={result.agent.backgroundColor || undefined}size={14}/>- <span style={{ flex: 'none' }}>{result.agent.title || t('defaultAgent')}</span>+ <span style={{ flex: 'none' }}>+ {agentDisplayName(result.agent, t('defaultAgent'))}+ </span><span style={{ flex: 'none' }}>·</span><span style={{ flex: 'none' }}>{formattedDate}</span>{description && (diff --git a/src/features/CommandMenu/components/CommandInput.tsx b/src/features/CommandMenu/components/CommandInput.tsxindex 8bc39abe93e..13ba4450830 100644--- a/src/features/CommandMenu/components/CommandInput.tsx+++ b/src/features/CommandMenu/components/CommandInput.tsx@@ -1,4 +1,5 @@import { DEFAULT_AVATAR } from '@lobechat/const';+import { agentDisplayName } from '@lobechat/types';import { Avatar, Tag } from '@lobehub/ui';import { Command } from 'cmdk';import { ArrowLeft, X } from 'lucide-react';@@ -47,7 +48,7 @@ const CommandInput = memo(() => {const getPlaceholder = () => {if (hasSelectedAgent) {- return t('cmdk.askAgentPlaceholder', { agent: selectedAgent.title });+ return t('cmdk.askAgentPlaceholder', { agent: agentDisplayName(selectedAgent) });}if (page === 'ask-ai') {return t('cmdk.aiModePlaceholder');@@ -72,7 +73,7 @@ const CommandInput = memo(() => {/>}>- {activeAgentMeta?.title || t('defaultAgent')}+ {agentDisplayName(activeAgentMeta, t('defaultAgent'))}</Tag>) : (menuContext !== 'general' && <Tag className={styles.contextTag}>{contextName}</Tag>@@ -105,7 +106,7 @@ const CommandInput = memo(() => {}onClose={() => setSelectedAgent(undefined)}>- {selectedAgent.title}+ {agentDisplayName(selectedAgent)}</Tag>)}<Command.Inputdiff --git a/src/features/ConnectAgent/index.tsx b/src/features/ConnectAgent/index.tsxindex b62adc3d0fd..aaaf4549190 100644--- a/src/features/ConnectAgent/index.tsx+++ b/src/features/ConnectAgent/index.tsx@@ -8,6 +8,7 @@ import type {} from '@lobechat/heterogeneous-agents';import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';import type { DeviceListItem } from '@lobechat/types';+import { agentDisplayName } from '@lobechat/types';import { Alert, CopyButton, Flexbox, Icon, Input, Text, TextArea, Tooltip } from '@lobehub/ui';import { Button, createModal, type ModalInstance, useModalContext } from '@lobehub/ui/base-ui';import { Checkbox, Typography } from 'antd';@@ -606,7 +607,7 @@ const ConnectAgentContent = memo<ConnectAgentContentProps>(<agent.provider.brand.Avatar size={32} /><Flexbox flex={1} gap={1} style={{ minWidth: 0 }}><Text strong fontSize={13}>- {agent.title}+ {agentDisplayName(agent)}</Text><Text ellipsis fontSize={12} type={'secondary'}>{agent.provider.title}diff --git a/src/features/Conversation/ChatItem/ChatItem.tsx b/src/features/Conversation/ChatItem/ChatItem.tsxindex d7d7062a8d1..e507ab9eaaa 100644--- a/src/features/Conversation/ChatItem/ChatItem.tsx+++ b/src/features/Conversation/ChatItem/ChatItem.tsx@@ -1,5 +1,6 @@'use client';+import { agentDisplayName } from '@lobechat/types';import { Flexbox } from '@lobehub/ui';import { cx } from 'antd-style';import { memo } from 'react';@@ -55,7 +56,7 @@ const ChatItem = memo<ChatItemProps>(const avatarContent = (<Avatar- alt={avatarProps?.alt || avatar.title || 'avatar'}+ alt={avatarProps?.alt || agentDisplayName(avatar, 'avatar')}loading={loading}shape={'square'}onClick={onAvatarClick}diff --git a/src/features/Conversation/ChatItem/components/Avatar.tsx b/src/features/Conversation/ChatItem/components/Avatar.tsxindex 4865a1dc2b7..ffce892ad06 100644--- a/src/features/Conversation/ChatItem/components/Avatar.tsx+++ b/src/features/Conversation/ChatItem/components/Avatar.tsx@@ -1,3 +1,4 @@+import { agentDisplayName } from '@lobechat/types';import { Avatar as A } from '@lobehub/ui';import { type CSSProperties } from 'react';import { memo } from 'react';@@ -18,14 +19,14 @@ const Avatar = memo<AvatarProps>(({ loading, avatar, unoptimized, onClick, size = 28, style, alt }) => {return (<A- alt={alt || avatar.title}+ alt={alt || agentDisplayName(avatar)}animation={loading}avatar={avatar.avatar}background={avatar.backgroundColor}shape={'square'}size={size}style={style}- title={avatar.title}+ title={agentDisplayName(avatar)}unoptimized={unoptimized}onClick={onClick}/>diff --git a/src/features/Conversation/ChatItem/components/Title.tsx b/src/features/Conversation/ChatItem/components/Title.tsxindex 27a5a51a88d..446677ebc45 100644--- a/src/features/Conversation/ChatItem/components/Title.tsx+++ b/src/features/Conversation/ChatItem/components/Title.tsx@@ -1,4 +1,5 @@-import { Text } from '@lobehub/ui';+import { agentDisplayName } from '@lobechat/types';+import { Tag, Text } from '@lobehub/ui';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -15,7 +16,9 @@ export interface TitleProps {const Title = memo<TitleProps>(({ showTitle, time, avatar, titleAddon }) => {const { t } = useTranslation('chat');- const title = avatar.title || t('untitledAgent');+ const title = agentDisplayName(avatar, t('untitledAgent'));+ // The role is only worth repeating when the personal name took the label slot.+ const roleTag = avatar.name?.trim() && avatar.title?.trim() ? avatar.title.trim() : undefined;const { text: timeText, title: timeTitle } = useActivityTime(time);return (@@ -25,6 +28,7 @@ const Title = memo<TitleProps>(({ showTitle, time, avatar, titleAddon }) => {{title}</Text>)}+ {showTitle && roleTag && <Tag size={'small'}>{roleTag}</Tag>}{showTitle ? titleAddon : undefined}{!timeText ? null : (<Textdiff --git a/src/features/Conversation/ChatItem/type.ts b/src/features/Conversation/ChatItem/type.tsindex 20fa25e1f51..4d1033ce920 100644--- a/src/features/Conversation/ChatItem/type.ts+++ b/src/features/Conversation/ChatItem/type.ts@@ -2,17 +2,24 @@ import type { AlertProps, AvatarProps, DivProps, FlexboxProps } from '@lobehub/uimport type { EditableMessageProps, MetaData } from '@lobehub/ui/chat';import type { ReactNode } from 'react';+/**+ * `MetaData` from `@lobehub/ui/chat` predates the agent's `name`/`title` split, so+ * it only carries `title`. Every caller in this app passes an agent meta that also+ * has `name` (see `useAgentMeta`), which is what the author label resolves from.+ */+export type ChatItemAvatarMeta = MetaData & { name?: string | null };+export interface ChatItemProps extends Omit<FlexboxProps, 'children' | 'onChange'> {aboveMessage?: ReactNode;actionAddon?: ReactNode;actions?: ReactNode;actionsWrapWidth?: number;afterActions?: ReactNode;- avatar: MetaData;+ avatar: ChatItemAvatarMeta;avatarProps?: AvatarProps;belowMessage?: ReactNode;children?: ReactNode;- customAvatarRender?: (avatar: MetaData, node: ReactNode) => ReactNode;+ customAvatarRender?: (avatar: ChatItemAvatarMeta, node: ReactNode) => ReactNode;customErrorRender?: (error: AlertProps) => ReactNode;/*** @description Whether the chat item is disableddiff --git a/src/features/Conversation/MessageForward/ForwardModal.tsx b/src/features/Conversation/MessageForward/ForwardModal.tsxindex d2a4e26346e..59a975e26b7 100644--- a/src/features/Conversation/MessageForward/ForwardModal.tsx+++ b/src/features/Conversation/MessageForward/ForwardModal.tsx@@ -1,5 +1,6 @@'use client';+import { agentDisplayName } from '@lobechat/types';import { Flexbox, SearchBar, Text, TextArea } from '@lobehub/ui';import { Button } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar, cx } from 'antd-style';@@ -118,7 +119,9 @@ const ForwardModal = memo<ForwardModalProps>(({ open, onClose }) => {const trimmed = keyword.trim().toLowerCase();return agents.filter((agent) => agent.type === 'agent' && agent.id !== currentAgentId)- .filter((agent) => !trimmed || (agent.title || '').toLowerCase().includes(trimmed));+ .filter(+ (agent) => !trimmed || (agentDisplayName(agent) ?? '').toLowerCase().includes(trimmed),+ );}, [agents, currentAgentId, keyword]);const selectedAgents = useMemo(@@ -186,7 +189,7 @@ const ForwardModal = memo<ForwardModalProps>(({ open, onClose }) => {<SelectCircle checked={checked} /><AgentAvatar avatar={avatarOf(agent.avatar)} /><Text ellipsis style={{ flex: 1 }}>- {agent.title || t('untitledAgent')}+ {agentDisplayName(agent, t('untitledAgent'))}</Text></Flexbox>);diff --git a/src/features/Conversation/Messages/AssistantGroup/index.tsx b/src/features/Conversation/Messages/AssistantGroup/index.tsxindex 3424f8068c1..075cbf017af 100644--- a/src/features/Conversation/Messages/AssistantGroup/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/index.tsx@@ -221,7 +221,10 @@ const GroupMessage = memo<GroupMessageProps>(return (<ChatItemshowTitle- avatar={isSupervisor ? { ...avatar, title: groupMeta.title } : avatar}+ // The supervisor row is labelled by the group, not by the agent behind it —+ // drop `name` too, or the renderer's name-first resolution would surface the+ // agent's personal name over the group title.+ avatar={isSupervisor ? { ...avatar, name: undefined, title: groupMeta.title } : avatar}id={id}placement={'left'}time={createdAt}diff --git a/src/features/Conversation/Messages/User/index.tsx b/src/features/Conversation/Messages/User/index.tsxindex 30b0e0b5ca5..8b84f8b9cdb 100644--- a/src/features/Conversation/Messages/User/index.tsx+++ b/src/features/Conversation/Messages/User/index.tsx@@ -1,3 +1,4 @@+import { agentDisplayName } from '@lobechat/types';import { Tag } from '@lobehub/ui';import isEqual from 'fast-deep-equal';import { type MouseEventHandler } from 'react';@@ -63,7 +64,10 @@ const UserMessage = memo<UserMessageProps>(({ id, disableEditing, index }) => {const targetName =targetId === 'user'? userName- : agents?.find((agent) => agent.id === targetId)?.title || targetId;+ : agentDisplayName(+ agents?.find((agent) => agent.id === targetId),+ targetId,+ );return <Tag>{t('dm.visibleTo', { target: targetName })}</Tag>;}, [targetId, userName, agents, t]);diff --git a/src/features/Conversation/components/ShareMessageModal/ShareImage/index.tsx b/src/features/Conversation/components/ShareMessageModal/ShareImage/index.tsxindex a2fd91e45d0..cd33f2e58e1 100644--- a/src/features/Conversation/components/ShareMessageModal/ShareImage/index.tsx+++ b/src/features/Conversation/components/ShareMessageModal/ShareImage/index.tsx@@ -1,4 +1,4 @@-import { type UIChatMessage } from '@lobechat/types';+import { agentDisplayName, type UIChatMessage } from '@lobechat/types';import { type FormItemProps } from '@lobehub/ui';import { Flexbox, Form } from '@lobehub/ui';import { Button, Switch, Tabs } from '@lobehub/ui/base-ui';@@ -28,8 +28,8 @@ const DEFAULT_FIELD_VALUE: FieldType = {const ShareImage = memo<{ message: UIChatMessage; mobile?: boolean; uniqueId?: string }>(({ message, uniqueId }) => {const agentId = useConversationStore(contextSelectors.agentId);- const currentAgentTitle = useAgentStore(- (s) => agentSelectors.getAgentMetaById(agentId)(s).title,+ const currentAgentTitle = useAgentStore((s) =>+ agentDisplayName(agentSelectors.getAgentMetaById(agentId)(s)),);const context = useConversationStore((s) => s.context);const [fieldValue, setFieldValue] = useState<FieldType>(DEFAULT_FIELD_VALUE);diff --git a/src/features/Conversation/hooks/useAgentMeta.ts b/src/features/Conversation/hooks/useAgentMeta.tsindex dba7fed2582..3204f747b99 100644--- a/src/features/Conversation/hooks/useAgentMeta.ts+++ b/src/features/Conversation/hooks/useAgentMeta.ts@@ -34,6 +34,9 @@ export const useAgentMeta = (messageAgentId?: string | null): MetaData => {return { ...agentMeta, title: agentMeta.title || LOBE_AI_TITLE };}+ // `name` and `title` both stay intact — resolving them into a single label is+ // the renderer's job (see `agentDisplayName`), not this hook's. Collapsing here+ // would leave a consumer that wants the role holding the personal name.return agentMeta;}, [agentId, agentMeta, builtinAgentIdMap]);};diff --git a/src/features/Electron/ScreenCapture/overlaySnapshot.ts b/src/features/Electron/ScreenCapture/overlaySnapshot.tsindex 34ec3718c1f..f56ef0f7092 100644--- a/src/features/Electron/ScreenCapture/overlaySnapshot.ts+++ b/src/features/Electron/ScreenCapture/overlaySnapshot.ts@@ -1,5 +1,6 @@import { DEFAULT_AVATAR, DEFAULT_INBOX_AVATAR } from '@lobechat/const';import type { ScreenCaptureAgentOption } from '@lobechat/electron-client-ipc';+import { agentDisplayName } from '@lobechat/types';const LOBE_AI_TITLE = 'Lobe AI';const UNTITLED_AGENT_TITLE = 'Untitled Agent';@@ -9,6 +10,7 @@ interface OverlayAgentSource {backgroundColor?: string | null;heterogeneousType?: string | null;id: string;+ name?: string | null;title?: string | null;}@@ -35,13 +37,14 @@ const toOverlayAgentOption = ({backgroundColor,heterogeneousType,id,+ name,title,}: OverlayAgentSource): ScreenCaptureAgentOption => ({avatar: typeof avatar === 'string' ? avatar : DEFAULT_AVATAR,backgroundColor: backgroundColor ?? undefined,heterogeneousType,id,- title: title?.trim() || UNTITLED_AGENT_TITLE,+ title: agentDisplayName({ name, title }, UNTITLED_AGENT_TITLE),});const createInboxOverlayAgentOption = (@@ -51,7 +54,7 @@ const createInboxOverlayAgentOption = (avatar: inboxMeta?.avatar || DEFAULT_INBOX_AVATAR,backgroundColor: inboxMeta?.backgroundColor ?? undefined,id: inboxAgentId,- title: inboxMeta?.title || LOBE_AI_TITLE,+ title: agentDisplayName(inboxMeta, LOBE_AI_TITLE),});export const resolveOverlayAgentOptions = ({diff --git a/src/features/Electron/titlebar/TrayMenu/resolveSnapshot.ts b/src/features/Electron/titlebar/TrayMenu/resolveSnapshot.tsindex 9a47fad6c0c..43646f483fd 100644--- a/src/features/Electron/titlebar/TrayMenu/resolveSnapshot.ts+++ b/src/features/Electron/titlebar/TrayMenu/resolveSnapshot.ts@@ -1,4 +1,5 @@import type { TrayNavigationSnapshot } from '@lobechat/electron-client-ipc';+import { agentDisplayName } from '@lobechat/types';import type { SidebarAgentItem } from '@/database/repositories/home';@@ -70,7 +71,7 @@ export const resolveTrayNavigationSnapshot = ({if (!uniqueAgents.has(agent.id)) uniqueAgents.set(agent.id, agent);}const agentNames = new Map(- [...uniqueAgents.values()].map((agent) => [agent.id, agent.title || 'Untitled']),+ [...uniqueAgents.values()].map((agent) => [agent.id, agentDisplayName(agent, 'Untitled')]),);const visitedPages = [...pinnedPages, ...recentPages].sort(@@ -80,7 +81,7 @@ export const resolveTrayNavigationSnapshot = ({return {agents: [...uniqueAgents.values()].map((agent) => ({id: agent.id,- title: agent.title || 'Untitled',+ title: agentDisplayName(agent, 'Untitled'),url:visitedPages.find((page) => getAgentIdFromUrl(page.tab.url) === agent.id)?.tab.url ??fallbackAgentUrl(scope, agent.id),diff --git a/src/features/GlobalApprovalNotification/ApprovalCard.tsx b/src/features/GlobalApprovalNotification/ApprovalCard.tsxindex b4e9cdef3a5..02d1e28e81d 100644--- a/src/features/GlobalApprovalNotification/ApprovalCard.tsx+++ b/src/features/GlobalApprovalNotification/ApprovalCard.tsx@@ -1,7 +1,7 @@'use client';import { AGENT_CHAT_TOPIC_URL, GROUP_CHAT_TOPIC_URL, GROUP_CHAT_URL } from '@lobechat/const';-import { type UIChatMessage } from '@lobechat/types';+import { agentDisplayName, type UIChatMessage } from '@lobechat/types';import { ActionIcon, Avatar } from '@lobehub/ui';import { ArrowUpRight } from 'lucide-react';import { memo, useCallback, useMemo, useState } from 'react';@@ -148,14 +148,14 @@ const ApprovalCard = memo<ApprovalCardProps>(({ group }) => {avatar={meta.avatar}background={meta.backgroundColor}size={28}- title={meta.title}+ title={agentDisplayName(meta)}/><div className={styles.headerMeta}><div className={styles.headerTitle}>- {topicTitle || meta.title || t('globalApproval.title')}+ {topicTitle || agentDisplayName(meta, t('globalApproval.title'))}</div><div className={styles.headerSubtitle}>- {meta.title ? `${meta.title} · ` : ''}+ {agentDisplayName(meta) ? `${agentDisplayName(meta)} · ` : ''}{t('globalApproval.subtitle')}</div></div>diff --git a/src/features/Home/AgentSelect/index.tsx b/src/features/Home/AgentSelect/index.tsxindex 00a94a8c127..45c2c58c9ea 100644--- a/src/features/Home/AgentSelect/index.tsx+++ b/src/features/Home/AgentSelect/index.tsx@@ -1,5 +1,6 @@'use client';+import { agentDisplayName } from '@lobechat/types';import { Avatar, Text } from '@lobehub/ui';import { Button, Popover } from '@lobehub/ui/base-ui';import { createStaticStyles } from 'antd-style';@@ -67,8 +68,10 @@ const AgentSelect = memo(() => {const agentMapMeta = useAgentStore(agentSelectors.getAgentMetaById(displayAgentId));const showInboxFallback = isInbox || !resolvedAgentId;const displayMeta = showInboxFallback ? inboxMeta : (sidebarItem ?? agentMapMeta);- const displayTitle =- displayMeta?.title || (showInboxFallback ? 'Lobe AI' : t('defaultSession', { ns: 'common' }));+ const displayTitle = agentDisplayName(+ displayMeta,+ showInboxFallback ? 'Lobe AI' : t('defaultSession', { ns: 'common' }),+ );const displayAvatar =(typeof displayMeta?.avatar === 'string' ? displayMeta.avatar : undefined) ||(showInboxFallback ? DEFAULT_INBOX_AVATAR : DEFAULT_AVATAR);diff --git a/src/features/Home/AgentSelect/useHomeAgentRows.ts b/src/features/Home/AgentSelect/useHomeAgentRows.tsindex e13fb84b275..492a2af0691 100644--- a/src/features/Home/AgentSelect/useHomeAgentRows.ts+++ b/src/features/Home/AgentSelect/useHomeAgentRows.ts@@ -1,6 +1,6 @@'use client';-import { type SidebarAgentItem } from '@lobechat/types';+import { agentDisplayName, type SidebarAgentItem } from '@lobechat/types';import isEqual from 'fast-deep-equal';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -82,7 +82,7 @@ export const useHomeAgentRows = (): HomeAgentRows => {backgroundColor: item.backgroundColor || undefined,id: item.id,pinned: item.pinned ?? false,- title: item.title || t('untitledAgent'),+ title: agentDisplayName(item, t('untitledAgent')),});}}@@ -104,7 +104,7 @@ export const useHomeAgentRows = (): HomeAgentRows => {DEFAULT_INBOX_AVATAR,backgroundColor: inboxMeta?.backgroundColor || undefined,id: inboxAgentId,- title: inboxMeta?.title || 'Lobe AI',+ title: agentDisplayName(inboxMeta, 'Lobe AI'),});}workspaceRows.push(diff --git a/src/features/Home/HomeModeContent.tsx b/src/features/Home/HomeModeContent.tsxindex 2312f544881..69617203292 100644--- a/src/features/Home/HomeModeContent.tsx+++ b/src/features/Home/HomeModeContent.tsx@@ -1,4 +1,5 @@import type { TaskStatus } from '@lobechat/types';+import { agentDisplayName } from '@lobechat/types';import type { FlexboxProps } from '@lobehub/ui';import { Avatar, Flexbox, Icon, Skeleton, Text } from '@lobehub/ui';import { createStaticStyles, cssVar, cx } from 'antd-style';@@ -139,7 +140,7 @@ const RecentTopicRow = memo<{ topic: RecentItem }>(({ topic }) => {className={styles.topicAvatar}shape={'circle'}size={22}- title={agent.title}+ title={agentDisplayName(agent)}/>) : (<Icon color={cssVar.colorTextDescription} icon={HashIcon} size={16} />diff --git a/src/features/HomeInbox/InboxBriefCard.tsx b/src/features/HomeInbox/InboxBriefCard.tsxindex b9337a399b2..3f0a4ab1df2 100644--- a/src/features/HomeInbox/InboxBriefCard.tsx+++ b/src/features/HomeInbox/InboxBriefCard.tsx@@ -1,4 +1,5 @@import { DEFAULT_AVATAR, INBOX_SESSION_ID } from '@lobechat/const';+import { agentDisplayName } from '@lobechat/types';import { Avatar, Block, Flexbox, Text } from '@lobehub/ui';import { createStaticStyles, cssVar, cx } from 'antd-style';import { memo } from 'react';@@ -106,9 +107,10 @@ const InboxBriefCard = memo<InboxBriefCardProps>(({ bare, brief }) => {shape={'circle'}size={28}style={{ flex: 'none' }}- title={- agent.title || (isInbox ? t('inbox.title', { ns: 'chat' }) : t('defaultSession'))- }+ title={agentDisplayName(+ agent,+ isInbox ? t('inbox.title', { ns: 'chat' }) : t('defaultSession'),+ )}/>)}<Flexbox flex={1} gap={6} style={{ minWidth: 0 }}>diff --git a/src/features/HomeInbox/NewsList.tsx b/src/features/HomeInbox/NewsList.tsxindex f8877b10826..e1b4dcae926 100644--- a/src/features/HomeInbox/NewsList.tsx+++ b/src/features/HomeInbox/NewsList.tsx@@ -1,3 +1,4 @@+import { agentDisplayName } from '@lobechat/types';import { Avatar, Flexbox, Icon, Markdown, Text } from '@lobehub/ui';import { Button } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar, cx } from 'antd-style';@@ -108,7 +109,7 @@ const NewsItem = memo<NewsItemProps>(({ bare, brief }) => {// Fade the whole row once read: the leading glyph dims with the title// so a scanned item recedes as one, not just a lighter headline.style={{ flex: 'none', opacity: read ? 0.5 : 1 }}- title={brief.agent.title ?? undefined}+ title={agentDisplayName(brief.agent)}/>) : (<BriefIcon muted={read} type={brief.type} />diff --git a/src/features/HomeInbox/RunningTasksCard.tsx b/src/features/HomeInbox/RunningTasksCard.tsxindex 0056339d4cd..71eb09a9ec7 100644--- a/src/features/HomeInbox/RunningTasksCard.tsx+++ b/src/features/HomeInbox/RunningTasksCard.tsx@@ -1,3 +1,4 @@+import { agentDisplayName } from '@lobechat/types';import { Avatar, Flexbox, Icon, Text } from '@lobehub/ui';import { Button } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar, cx } from 'antd-style';@@ -88,7 +89,7 @@ const StackedAgentAvatar = memo<{ agentId: string }>(({ agentId }) => {className={styles.stackedAvatar}shape={'circle'}size={AVATAR_SIZE}- title={agent.title}+ title={agentDisplayName(agent)}/>);});diff --git a/src/features/HomeInbox/TopicRow.tsx b/src/features/HomeInbox/TopicRow.tsxindex 81a8bb1d861..d6957293292 100644--- a/src/features/HomeInbox/TopicRow.tsx+++ b/src/features/HomeInbox/TopicRow.tsx@@ -1,4 +1,5 @@import { AGENT_CHAT_TOPIC_URL } from '@lobechat/const';+import { agentDisplayName } from '@lobechat/types';import { Avatar, Flexbox, Text } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';import { memo, type ReactNode } from 'react';@@ -52,7 +53,7 @@ const TopicRow = memo<TopicRowProps>(({ topic, leading, trailing }) => {shape={'circle'}size={22}style={{ flex: 'none' }}- title={agent.title}+ title={agentDisplayName(agent)}/>)}<Flexbox horizontal align={'center'} flex={1} gap={6} style={{ minWidth: 0 }}>diff --git a/src/features/HomeInbox/UnreadTopicList.tsx b/src/features/HomeInbox/UnreadTopicList.tsxindex 0260c7f28f6..ddbeec69449 100644--- a/src/features/HomeInbox/UnreadTopicList.tsx+++ b/src/features/HomeInbox/UnreadTopicList.tsx@@ -1,5 +1,5 @@import { AGENT_CHAT_TOPIC_URL } from '@lobechat/const';-import { type ConversationContext } from '@lobechat/types';+import { agentDisplayName, type ConversationContext } from '@lobechat/types';import { Avatar, Flexbox, Icon, Markdown, stopPropagation, Text } from '@lobehub/ui';import { Button } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar, cx } from 'antd-style';@@ -181,7 +181,7 @@ const UnreadTopicItem = memo<UnreadTopicItemProps>(shape={'circle'}size={AVATAR_SIZE}style={{ flex: 'none' }}- title={agent.title}+ title={agentDisplayName(agent)}/>)}<Textdiff --git a/src/features/Messenger/AgentSelect.tsx b/src/features/Messenger/AgentSelect.tsxindex 5551aab4965..7232c9a7bc1 100644--- a/src/features/Messenger/AgentSelect.tsx+++ b/src/features/Messenger/AgentSelect.tsx@@ -1,5 +1,6 @@'use client';+import { agentDisplayName } from '@lobechat/types';import { Avatar, Flexbox, Text } from '@lobehub/ui';import { Select, type SelectProps } from '@lobehub/ui/base-ui';import { memo, useEffect, useMemo, useRef } from 'react';@@ -37,7 +38,7 @@ const AgentSelect = memo<AgentSelectProps>(const options = useMemo(() =>(agentsSWR.data ?? []).map((agent) => {- const title = agent.title || defaultAgentTitle;+ const title = agentDisplayName(agent, defaultAgentTitle);return {label: (<Flexbox horizontal align={'center'} gap={8}>diff --git a/src/features/PageEditor/Copilot/AgentSelector/AgentSelectorAction.tsx b/src/features/PageEditor/Copilot/AgentSelector/AgentSelectorAction.tsxindex 65cc1801238..515ebafb978 100644--- a/src/features/PageEditor/Copilot/AgentSelector/AgentSelectorAction.tsx+++ b/src/features/PageEditor/Copilot/AgentSelector/AgentSelectorAction.tsx@@ -1,3 +1,4 @@+import { agentDisplayName } from '@lobechat/types';import { Center, Flexbox, Popover } from '@lobehub/ui';import { createStaticStyles, cx } from 'antd-style';import { ChevronsUpDownIcon } from 'lucide-react';@@ -99,7 +100,7 @@ const AgentSelectorAction = memo<AgentSelectorActionProps>(({ onAgentChange }) =<AgentItemactive={agent.id === agentId}agentId={agent.id}- agentTitle={agent.title || t('untitledAgent', { ns: 'chat' })}+ agentTitle={agentDisplayName(agent, t('untitledAgent', { ns: 'chat' }))}avatar={agent.avatar}key={agent.id}onAgentChange={handleAgentChange}diff --git a/src/features/Portal/AgentDetail/Body.tsx b/src/features/Portal/AgentDetail/Body.tsxindex 7561fb41e7c..4ca0f24794e 100644--- a/src/features/Portal/AgentDetail/Body.tsx+++ b/src/features/Portal/AgentDetail/Body.tsx@@ -1,5 +1,6 @@'use client';+import { agentDisplayName } from '@lobechat/types';import { Avatar, Flexbox, Markdown, Text } from '@lobehub/ui';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -49,7 +50,7 @@ const Body = memo(() => {<Flexbox align="center" flex={1} gap={16} padding={32} style={{ overflowY: 'auto' }}><Avatar avatar={meta.avatar} background={meta.backgroundColor} shape="square" size={80} /><Text align="center" fontSize={24} weight="bold">- {meta.title || t('defaultSession', { ns: 'common' })}+ {agentDisplayName(meta, t('defaultSession', { ns: 'common' }))}</Text>{meta.description && (<Text align="center" type="secondary">diff --git a/src/features/Portal/AgentDetail/Title.tsx b/src/features/Portal/AgentDetail/Title.tsxindex da6084b6d4e..c6626b26d4f 100644--- a/src/features/Portal/AgentDetail/Title.tsx+++ b/src/features/Portal/AgentDetail/Title.tsx@@ -1,5 +1,6 @@'use client';+import { agentDisplayName } from '@lobechat/types';import { Avatar, Flexbox, Text } from '@lobehub/ui';import { memo } from 'react';@@ -16,7 +17,7 @@ const Title = memo(() => {<Flexbox horizontal align="center" gap={8} style={{ minWidth: 0 }}><Avatar avatar={meta.avatar} background={meta.backgroundColor} shape="square" size={24} /><Text ellipsis weight={500}>- {meta.title || agentId}+ {agentDisplayName(meta, agentId ?? '')}</Text></Flexbox>);diff --git a/src/features/Portal/GroupThread/Body/ThreadChatList.tsx b/src/features/Portal/GroupThread/Body/ThreadChatList.tsxindex 3e455bfe4c6..7a0518639bd 100644--- a/src/features/Portal/GroupThread/Body/ThreadChatList.tsx+++ b/src/features/Portal/GroupThread/Body/ThreadChatList.tsx@@ -1,5 +1,6 @@'use client';+import { agentDisplayName } from '@lobechat/types';import { memo, useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -22,7 +23,7 @@ const ThreadChatList = memo(() => {// Get agent info for better empty stateconst agents = useSessionStore(sessionSelectors.currentGroupAgents);const currentAgent = agents?.find((agent) => agent.id === activeThreadAgentId);- const agentTitle = currentAgent?.title || 'this agent';+ const agentTitle = agentDisplayName(currentAgent, 'this agent');// Get thread message IDs using the chat selector with the active agent IDconst data = useChatStore(chatSelectors.getThreadMessageIDs(activeThreadAgentId));diff --git a/src/features/Portal/GroupThread/Header/index.tsx b/src/features/Portal/GroupThread/Header/index.tsxindex 2e91a274291..2bfefbb0f7b 100644--- a/src/features/Portal/GroupThread/Header/index.tsx+++ b/src/features/Portal/GroupThread/Header/index.tsx@@ -1,3 +1,4 @@+import { agentDisplayName } from '@lobechat/types';import { ActionIcon, Avatar, Flexbox } from '@lobehub/ui';import { cssVar } from 'antd-style';import { t } from 'i18next';@@ -36,7 +37,7 @@ const Header = memo(() => {size={20}/><div style={{ fontWeight: 600 }}>- {currentAgent?.title || t('defaultSession', { ns: 'common' })}+ {agentDisplayName(currentAgent, t('defaultSession', { ns: 'common' }))}</div></Flexbox>}diff --git a/src/features/RouteMeta/AgentDynamicMeta.tsx b/src/features/RouteMeta/AgentDynamicMeta.tsxindex d3c9dc353bc..7d9d6e9f53e 100644--- a/src/features/RouteMeta/AgentDynamicMeta.tsx+++ b/src/features/RouteMeta/AgentDynamicMeta.tsx@@ -1,5 +1,6 @@'use client';+import { agentDisplayName } from '@lobechat/types';import { useTranslation } from 'react-i18next';import type { DynamicRouteMetaProps } from '@/spa/router/routeMeta';@@ -37,7 +38,7 @@ const AgentDynamicMeta = ({ onResolve, params }: DynamicRouteMetaProps) => {});const topicTitle = useTopicTitle(params.aid, params.topicId ?? params.topic, routeWorkspaceId);const hasMeta = Object.keys(meta).length > 0;- const agentTitle = hasMeta ? meta.title : undefined;+ const agentTitle = hasMeta ? agentDisplayName(meta) : undefined;usePublishDynamicRouteMeta({@@ -71,7 +72,7 @@ const createAgentSectionDynamicMeta = (titleKey: string) => {return agentSelectors.getAgentMetaById(agentId)(state);});const hasMeta = Object.keys(meta).length > 0;- const agentTitle = hasMeta ? meta.title : undefined;+ const agentTitle = hasMeta ? agentDisplayName(meta) : undefined;usePublishDynamicRouteMeta({diff --git a/src/features/RouteMeta/mobileRouteMeta.ts b/src/features/RouteMeta/mobileRouteMeta.tsindex e300d76e5da..42d3a260c15 100644--- a/src/features/RouteMeta/mobileRouteMeta.ts+++ b/src/features/RouteMeta/mobileRouteMeta.ts@@ -1,3 +1,4 @@+import { agentDisplayName } from '@lobechat/types';import { t } from 'i18next';import { Settings } from 'lucide-react';@@ -12,8 +13,8 @@ const MobileAgentSettingsDynamicMeta = ({ onResolve, params }: DynamicRouteMetaPusePublishDynamicRouteMeta({- title: meta.title- ? t('header.sessionWithName', { name: meta.title, ns: 'setting' })+ title: agentDisplayName(meta)+ ? t('header.sessionWithName', { name: agentDisplayName(meta), ns: 'setting' }): t('header.session', { ns: 'setting' }),},onResolve,diff --git a/src/features/ShareModal/ShareImage/Preview.tsx b/src/features/ShareModal/ShareImage/Preview.tsxindex 3478f904f11..2aa2a091049 100644--- a/src/features/ShareModal/ShareImage/Preview.tsx+++ b/src/features/ShareModal/ShareImage/Preview.tsx@@ -1,4 +1,4 @@-import { type ConversationContext, type UIChatMessage } from '@lobechat/types';+import { agentDisplayName, type ConversationContext, type UIChatMessage } from '@lobechat/types';import { ModelTag } from '@lobehub/icons';import { Avatar, Flexbox, Markdown, Text } from '@lobehub/ui';import { cx } from 'antd-style';@@ -59,7 +59,7 @@ const Preview = memo<PreviewProps>(agentSelectors.displayableAgentPlugins(s),agentSelectors.currentAgentSystemRole(s),builtinAgentSelectors.isInboxAgent(s),- agentSelectors.currentAgentTitle(s),+ agentSelectors.currentAgentDisplayName(s),agentSelectors.currentAgentAvatar(s),agentSelectors.currentAgentBackgroundColor(s),resolvedHeaderAgentId@@ -78,7 +78,9 @@ const Preview = memo<PreviewProps>(});const displayTitle =- (isHeaderInbox ?? isInbox) ? 'Lobe AI' : headerMeta?.title || title || currentTitle;+ (isHeaderInbox ?? isInbox)+ ? 'Lobe AI'+ : agentDisplayName(headerMeta) || title || currentTitle;const displayAvatar = headerMeta?.avatar || currentAvatar;const displayBackgroundColor = headerMeta?.backgroundColor || currentBackgroundColor;const displayModel = headerModel || currentModel;diff --git a/src/features/ShareModal/ShareImage/index.tsx b/src/features/ShareModal/ShareImage/index.tsxindex f11ba679aec..fe0cb3b3ad8 100644--- a/src/features/ShareModal/ShareImage/index.tsx+++ b/src/features/ShareModal/ShareImage/index.tsx@@ -28,7 +28,7 @@ const DEFAULT_FIELD_VALUE: FieldType = {};const ShareImage = memo<{ mobile?: boolean }>(() => {- const currentAgentTitle = useAgentStore(agentSelectors.currentAgentTitle);+ const currentAgentTitle = useAgentStore(agentSelectors.currentAgentDisplayName);const [fieldValue, setFieldValue] = useState<FieldType>(DEFAULT_FIELD_VALUE);const { t } = useTranslation(['chat', 'common']);const { context, dbMessages } = useShareData();diff --git a/src/routes/(main)/agent/_layout/AgentIdSync.tsx b/src/routes/(main)/agent/_layout/AgentIdSync.tsxindex c0e932d8339..c2a51f90799 100644--- a/src/routes/(main)/agent/_layout/AgentIdSync.tsx+++ b/src/routes/(main)/agent/_layout/AgentIdSync.tsx@@ -11,16 +11,16 @@ const AgentIdSync = () => {const [searchParams] = useSearchParams();const navigate = useWorkspaceAwareNavigate();const location = useLocation();- const { agentId: activeId, isBuiltinSlug, resolvedAgentId } = useResolvedAgentRouteId(params.aid);+ const { agentId: activeId, isSlugRoute, resolvedAgentId } = useResolvedAgentRouteId(params.aid);// Redirect slug URL to real agent ID URL, preserving child path and query stringuseEffect(() => {- if (isBuiltinSlug && resolvedAgentId) {+ if (isSlugRoute && resolvedAgentId) {const suffix = location.pathname.replace(`/agent/${params.aid}`, '');const qs = searchParams.toString();navigate(`/agent/${resolvedAgentId}${suffix}${qs ? `?${qs}` : ''}`, { replace: true });}- }, [isBuiltinSlug, resolvedAgentId, navigate, searchParams, location.pathname, params.aid]);+ }, [isSlugRoute, resolvedAgentId, navigate, searchParams, location.pathname, params.aid]);useAgentIdStoreSync({activeId,diff --git a/src/routes/(main)/agent/channel/list.tsx b/src/routes/(main)/agent/channel/list.tsxindex 38f2a3df689..bea6e0358d6 100644--- a/src/routes/(main)/agent/channel/list.tsx+++ b/src/routes/(main)/agent/channel/list.tsx@@ -1,5 +1,6 @@'use client';+import { agentDisplayName } from '@lobechat/types';import { Avatar, Block, Flexbox, Tag, Text } from '@lobehub/ui';import { createStaticStyles, responsive, useTheme } from 'antd-style';import isEqual from 'fast-deep-equal';@@ -120,7 +121,7 @@ const PlatformGrid = memo<PlatformGridProps>(const { t } = useTranslation(['agent', 'common']);const theme = useTheme();const meta = useAgentStore(agentSelectors.getAgentMetaById(agentId), isEqual);- const agentName = meta.title || t('defaultSession', { ns: 'common' });+ const agentName = agentDisplayName(meta, t('defaultSession', { ns: 'common' }));const getPlatformDescription = (id: string, name: string) => {switch (id) {diff --git a/src/routes/(main)/agent/profile/features/Header/index.tsx b/src/routes/(main)/agent/profile/features/Header/index.tsxindex 4d930ed8a23..56d1a504787 100644--- a/src/routes/(main)/agent/profile/features/Header/index.tsx+++ b/src/routes/(main)/agent/profile/features/Header/index.tsx@@ -1,5 +1,5 @@import { isDesktop } from '@lobechat/const';-import { getActivePluginIds } from '@lobechat/types';+import { getActivePluginIds, type LobeAgentConfig } from '@lobechat/types';import { ActionIcon, DropdownMenu, Flexbox, Icon } from '@lobehub/ui';import { confirmModal, type ModalInstance } from '@lobehub/ui/base-ui';import { toast } from '@lobehub/ui/base-ui';@@ -105,7 +105,13 @@ const Header = memo(() => {const navigate = useWorkspaceAwareNavigate();const meta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);- const config = useAgentStore(agentSelectors.currentAgentConfig, isEqual);+ // `currentAgentConfig` is typed non-nullable but reads straight out of+ // `agentMap`, so it IS undefined until the config lands. Reaching a profile by+ // slug adds a resolution hop before that happens, which is long enough for the+ // dependency array below to read `config.model` off nothing and drop the whole+ // page into the error boundary.+ const config = useAgentStore(agentSelectors.currentAgentConfig, isEqual) as+ LobeAgentConfig | undefined;const systemRole = useAgentStore(agentSelectors.currentAgentSystemRole);const activeAgentId = useAgentStore((s) => s.activeAgentId);const isHeterogeneous = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);@@ -171,11 +177,11 @@ const Header = memo(() => {: (editor?.getDocument('markdown') as string | null | undefined);const profileMarkdown = buildAgentProfileMarkdown({description: meta?.description,- model: config.model,+ model: config?.model,// Pinned identifiers only — a disabled plugin shouldn't be advertised// as "enabled" in the exported markdown.- plugins: getActivePluginIds(config.plugins),- provider: config.provider,+ plugins: getActivePluginIds(config?.plugins),+ provider: config?.provider,systemRole: editorMarkdown ?? systemRole,t,tags: meta?.tags,@@ -211,7 +217,16 @@ const Header = memo(() => {console.error('Failed to export agent profile markdown:', error);toast.error(t('settingAgent.export.error', { ns: 'setting' }));}- }, [config.model, config.plugins, config.provider, editor, isHeterogeneous, meta, systemRole, t]);+ }, [+ config?.model,+ config?.plugins,+ config?.provider,+ editor,+ isHeterogeneous,+ meta,+ systemRole,+ t,+ ]);const importMenuItem = useBusinessAgentImportMenuItem(activeAgentId ?? undefined);const transferMenuItems = useAgentTransferMenuItem(activeAgentId ?? undefined, meta);diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsxindex b05418e8479..d6cbe357f06 100644--- a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsx+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsx@@ -13,28 +13,71 @@ const mocks = vi.hoisted(() => {activeAgentId: 'agent-a',agentMap: {} as Record<string,- { avatar?: string | null; backgroundColor?: string; title?: string }+ {+ avatar?: string | null;+ backgroundColor?: string;+ name?: string;+ slug?: string;+ title?: string;+ }>,},agentStoreListeners: new Set<() => void>(),+ actionIconProps: { all: [] as Record<string, unknown>[] },+ createAgentIdentityModal: vi.fn(),+ refreshAgentConfig: vi.fn(),emojiPickerProps: { last: undefined as Record<string, unknown> | undefined },- inputProps: { last: undefined as Record<string, unknown> | undefined },+ // In edit mode the header renders three inputs, in order: personal name,+ // role, slug. `all` accumulates across renders, so read from the TAIL — the+ // head holds a stale closure and a handler taken from it silently no-ops.+ inputProps: {+ all: [] as Record<string, unknown>[],+ /** The headline input — the personal name. */+ get name() {+ return this.all.at(-3);+ },+ /** The second input — the role (`title`). */+ get role() {+ return this.all.at(-2);+ },+ /** The third input — the url slug. */+ get slug() {+ return this.all.at(-1);+ },+ },permissionState: { allowed: false },+ randomAgentName: vi.fn(() => 'Zoe'),+ refreshAgentList: vi.fn(),+ sidebarAgents: [] as { id: string; name?: string | null }[],updateAgentMetaById: vi.fn(),uploadWithProgress: vi.fn(),};});vi.mock('@lobehub/ui', () => ({+ ActionIcon: (props: Record<string, unknown>) => {+ mocks.actionIconProps.all.push(props);+ return (+ <button type="button" onClick={props.onClick as () => void}>+ {props.title as string}+ </button>+ );+ },+ Button: (props: Record<string, unknown>) => (+ <button type="button" onClick={props.onClick as () => void}>+ {props.children as ReactNode}+ </button>+ ),Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,Icon: () => <span />,Input: (props: Record<string, unknown>) => {- mocks.inputProps.last = props;+ mocks.inputProps.all.push(props);return <input readOnly disabled={props.disabled as boolean} value={props.value as string} />;},Skeleton: {Button: () => <div />,},+ Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,Tooltip: ({ children }: { children?: ReactNode }) => <>{children}</>,}));@@ -70,6 +113,7 @@ vi.mock('@/store/agent', async () => {() =>selector({...mocks.agentStoreState,+ internal_refreshAgentConfig: mocks.refreshAgentConfig,updateAgentMetaById: mocks.updateAgentMetaById,}),),@@ -80,6 +124,30 @@ vi.mock('@/store/agent/selectors', () => ({agentSelectors: {getAgentMetaById: (agentId: string) => (state: typeof mocks.agentStoreState) =>state.agentMap[agentId] || {},+ getAgentSlugById: (agentId: string) => (state: typeof mocks.agentStoreState) =>+ state.agentMap[agentId]?.slug,+ },+}));++vi.mock('@/features/AgentIdentityModal', () => ({+ createAgentIdentityModal: (...args: unknown[]) => mocks.createAgentIdentityModal(...args),+}));++vi.mock('@lobechat/const', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ randomAgentName: (...args: unknown[]) => mocks.randomAgentName(...(args as [])),+}));++vi.mock('@/store/home', () => {+ const useHomeStore = (selector: (state: unknown) => unknown) =>+ selector({ refreshAgentList: mocks.refreshAgentList });+ useHomeStore.getState = () => ({ agents: mocks.sidebarAgents });+ return { useHomeStore };+});++vi.mock('@/store/home/selectors', () => ({+ homeAgentListSelectors: {+ allAgents: (state: { agents: unknown[] }) => state.agents,},}));@@ -115,8 +183,11 @@ describe('AgentHeader', () => {};mocks.agentStoreListeners.clear();mocks.emojiPickerProps.last = undefined;- mocks.inputProps.last = undefined;+ mocks.inputProps.all = [];+ mocks.actionIconProps.all = [];mocks.permissionState.allowed = false;+ mocks.randomAgentName.mockReturnValue('Zoe');+ mocks.sidebarAgents = [];});afterEach(() => {@@ -129,53 +200,137 @@ describe('AgentHeader', () => {expect(mocks.emojiPickerProps.last?.open).toBe(false);});- it('flushes a pending title to its original agent and resets the next agent input', async () => {+ it('opens the identity form instead of editing inline', () => {mocks.permissionState.allowed = true;- mocks.agentStoreState.agentMap = {- 'agent-a': { title: 'Same title' },- 'agent-b': { title: 'Same title' },- };- render(<AgentHeader />);+ mocks.agentStoreState.agentMap = { 'agent-a': { name: 'Alice', title: 'Health Assistant' } };+ const view = render(<AgentHeader />);++ // The header is display-only: the three fields live in the modal.+ expect(view.container.querySelectorAll('input')).toHaveLength(0);act(() => {- const onChange = mocks.inputProps.last?.onChange as (event: {- target: { value: string };- }) => void;- onChange({ target: { value: 'Agent A draft' } });+ (mocks.actionIconProps.all.at(-1)?.onClick as () => void)?.();});- expect(mocks.updateAgentMetaById).not.toHaveBeenCalled();+ expect(mocks.createAgentIdentityModal).toHaveBeenCalledExactlyOnceWith('agent-a');+ });- act(() => {- mocks.agentStoreState.activeAgentId = 'agent-b';- mocks.agentStoreListeners.forEach((listener) => listener());- });+ it('shows the slug next to the role', () => {+ mocks.permissionState.allowed = true;+ mocks.agentStoreState.agentMap = {+ 'agent-a': { name: 'Alice', slug: 'brave-otter-lamp', title: 'Health Assistant' },+ };+ const view = render(<AgentHeader />);- expect(mocks.updateAgentMetaById).toHaveBeenCalledExactlyOnceWith('agent-a', {- title: 'Agent A draft',- });- expect(mocks.inputProps.last?.value).toBe('Same title');+ expect(view.container.textContent).toContain('@brave-otter-lamp');});- it('flushes a pending title when the scoped profile unmounts', () => {+ // Regression: the headline used to fall back to the name field's PLACEHOLDER,+ // so every unnamed agent read as though it were called "Give it a name, …".+ it('never renders the input placeholder as a headline', () => {mocks.permissionState.allowed = true;- mocks.agentStoreState.agentMap = { 'agent-a': { title: 'Agent A' } };+ mocks.agentStoreState.agentMap = { 'agent-a': { slug: 'experiment-crop-then' } };const view = render(<AgentHeader />);- act(() => {- const onChange = mocks.inputProps.last?.onChange as (event: {- target: { value: string };- }) => void;- onChange({ target: { value: 'Final Agent A title' } });- });+ expect(view.container.textContent).not.toContain('settingAgent.personalName.placeholder');+ });- view.unmount();+ // The headline is the NAME slot. Borrowing the role printed it twice, since+ // the role already has its own line right below.+ it('does not borrow the role for the headline', () => {+ mocks.permissionState.allowed = true;+ mocks.agentStoreState.agentMap = { 'agent-a': { slug: 'inbox', title: 'Lobe AI' } };+ const view = render(<AgentHeader />);- expect(mocks.updateAgentMetaById).toHaveBeenCalledExactlyOnceWith('agent-a', {- title: 'Final Agent A title',+ // Exactly once: on the role line, never as the headline.+ expect(view.container.textContent?.match(/Lobe AI/g)).toHaveLength(1);+ });++ // With no name there is nothing to headline, so the slot carries the prompt+ // that fixes it — not a placeholder dressed up as a name.+ it('gives the headline slot to the naming prompt while unnamed', () => {+ mocks.permissionState.allowed = true;+ mocks.agentStoreState.agentMap = { 'agent-a': { slug: 'inbox', title: 'Lobe AI' } };+ const view = render(<AgentHeader />);++ expect(view.container.textContent).toContain('settingAgent.personalName.unnamed');+ expect(view.container.textContent).not.toContain('settingAgent.identity.untitled');+ // Naming it IS the next step; the identity form would split attention.+ expect(view.container.textContent).not.toContain('settingAgent.identity.edit');+ });++ // Read-only viewers get the plain label — an action they cannot take would be+ // worse than a stated absence.+ it('falls back to the unnamed label when edits are not allowed', () => {+ mocks.agentStoreState.agentMap = { 'agent-a': { slug: 'inbox', title: 'Lobe AI' } };+ const view = render(<AgentHeader />);++ expect(view.container.textContent).toContain('settingAgent.identity.untitled');+ expect(view.container.textContent).not.toContain('settingAgent.personalName.pickForMe');+ expect(view.container.textContent).not.toContain('settingAgent.identity.edit');+ });++ it('restores the headline and the edit affordance once named', () => {+ mocks.permissionState.allowed = true;+ mocks.agentStoreState.agentMap = { 'agent-a': { name: '思远', slug: 'inbox' } };+ const view = render(<AgentHeader />);++ expect(view.container.textContent).toContain('思远');+ expect(view.container.textContent).not.toContain('settingAgent.personalName.unnamed');+ expect(view.container.textContent).toContain('settingAgent.identity.edit');+ });++ it('states the role is unset instead of leaving a bare slug', () => {+ mocks.permissionState.allowed = true;+ mocks.agentStoreState.agentMap = { 'agent-a': { name: '思远', slug: 'belong-pot-women' } };+ const view = render(<AgentHeader />);++ expect(view.container.textContent).toContain('settingAgent.role.unset');+ expect(view.container.textContent).toContain('@belong-pot-women');+ });++ it('offers one-click naming for an agent with no name', async () => {+ mocks.permissionState.allowed = true;+ mocks.agentStoreState.agentMap = { 'agent-a': { title: 'Health Assistant' } };+ mocks.sidebarAgents = [+ { id: 'agent-a', name: null },+ { id: 'agent-b', name: 'Alice' },+ { id: 'agent-c', name: 'Leo' },+ { id: 'agent-d', name: null },+ ];+ const view = render(<AgentHeader />);++ expect(view.container.textContent).toContain('settingAgent.personalName.unnamed');+ const button = [...view.container.querySelectorAll('button')].find((el) =>+ el.textContent?.includes('settingAgent.personalName.pickForMe'),+ );++ await act(async () => {+ button?.click();});- act(() => vi.runAllTimers());- expect(mocks.updateAgentMetaById).toHaveBeenCalledTimes(1);++ // Names already on screen are excluded — a second "Alice" would defeat the+ // point of having a name at all.+ expect(mocks.randomAgentName).toHaveBeenCalledExactlyOnceWith('en-US', ['Alice', 'Leo']);+ expect(mocks.updateAgentMetaById).toHaveBeenCalledExactlyOnceWith('agent-a', { name: 'Zoe' });+ // Otherwise the sidebar keeps showing the unnamed label next to a now-named+ // profile.+ expect(mocks.refreshAgentList).toHaveBeenCalledOnce();+ });++ it('does not offer naming for an agent that already has one', () => {+ mocks.permissionState.allowed = true;+ mocks.agentStoreState.agentMap = { 'agent-a': { name: 'Alice', title: 'Health Assistant' } };+ const view = render(<AgentHeader />);++ expect(view.container.textContent).not.toContain('settingAgent.personalName.pickForMe');+ });++ it('does not offer naming when edits are not allowed', () => {+ mocks.agentStoreState.agentMap = { 'agent-a': { title: 'Health Assistant' } };+ const view = render(<AgentHeader />);++ expect(view.container.textContent).not.toContain('settingAgent.personalName.pickForMe');});it('keeps an asynchronous avatar upload bound to the agent that started it', async () => {diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.tsxindex 346e48b591a..e8ab5a1a1c5 100644--- a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.tsx+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.tsx@@ -1,15 +1,15 @@'use client';-import { EDITOR_DEBOUNCE_TIME } from '@lobechat/const';-import { Flexbox, Icon, Input, Skeleton, Tooltip } from '@lobehub/ui';-import { toast } from '@lobehub/ui/base-ui';-import { debounce } from 'es-toolkit/compat';+import { ActionIcon, Flexbox, Icon, Skeleton, Text, Tooltip } from '@lobehub/ui';+import { Button, toast } from '@lobehub/ui/base-ui';+import { cssVar } from 'antd-style';import isEqual from 'fast-deep-equal';-import { PaletteIcon } from 'lucide-react';-import { memo, Suspense, useCallback, useEffect, useMemo, useState } from 'react';+import { PaletteIcon, PencilIcon, SparklesIcon } from 'lucide-react';+import { memo, Suspense, useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';import EmojiPicker from '@/components/EmojiPicker';+import { createAgentIdentityModal } from '@/features/AgentIdentityModal';import BackgroundSwatches from '@/features/AgentSetting/AgentMeta/BackgroundSwatches';import { usePermission } from '@/hooks/usePermission';import { useAgentStore } from '@/store/agent';@@ -18,6 +18,8 @@ import { useFileStore } from '@/store/file';import { useGlobalStore } from '@/store/global';import { globalGeneralSelectors } from '@/store/global/selectors';+import { useAutoName } from './useAutoName';+const MAX_AVATAR_SIZE = 1024 * 1024; // 1MB limit for server actionsconst AgentHeader = memo(() => {@@ -27,39 +29,17 @@ const AgentHeader = memo(() => {const agentId = useAgentStore((s) => s.activeAgentId || '');const meta = useAgentStore(agentSelectors.getAgentMetaById(agentId), isEqual);+ const slug = useAgentStore(agentSelectors.getAgentSlugById(agentId));const updateMetaById = useAgentStore((s) => s.updateAgentMetaById);+ const { autoName, naming } = useAutoName(agentId);+ // Without edit rights there is nothing to prompt for, so a nameless agent+ // falls back to the plain label rather than showing an action nobody can take.+ const showNamePrompt = !meta.name?.trim() && canEdit;// File uploadconst uploadWithProgress = useFileStore((s) => s.uploadWithProgress);const [uploading, setUploading] = useState(false);- // Local state for inputs (to avoid stuttering during typing)- const [localTitle, setLocalTitle] = useState(meta.title || '');-- // Sync local state when meta changes from external source- useEffect(() => {- setLocalTitle(meta.title || '');- }, [agentId, meta.title]);-- // Debounced save for title- const debouncedSaveTitle = useMemo(- () =>- debounce((targetAgentId: string, value: string) => {- updateMetaById(targetAgentId, { title: value });- }, EDITOR_DEBOUNCE_TIME),- [updateMetaById],- );-- // A pending title belongs to the agent that was being edited. Commit that- // invocation before adopting another agent's local input state.- useEffect(- () => () => {- debouncedSaveTitle.flush();- debouncedSaveTitle.cancel();- },- [agentId, debouncedSaveTitle],- );-// Handle avatar change (immediate save)const handleAvatarChange = (emoji: string) => {if (!canEdit) return;@@ -172,26 +152,81 @@ const AgentHeader = memo(() => {onDelete={handleAvatarDelete}onUpload={handleAvatarUpload}/>- {/* Title Section */}- <Flexbox flex={1} style={{ minWidth: 0 }}>- <Input- disabled={!canEdit}- placeholder={t('settingAgent.name.placeholder', { ns: 'setting' })}- value={localTitle}- variant={'borderless'}- style={{- fontSize: 36,- fontWeight: 600,- padding: 0,- width: '100%',- }}- onChange={(e) => {- setLocalTitle(e.target.value);- if (!agentId || !canEdit) return;-- debouncedSaveTitle(agentId, e.target.value);- }}- />+ {/* Identity Section — display only. Editing all three fields happens in a+ form modal; inline inputs crowded the header and left no room for a+ per-field label or error. */}+ <Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>+ {/* The headline is the NAME slot. It does not borrow the role the way+ list surfaces do — the role has its own line right below, and falling+ back would print it twice (an agent titled "Lobe AI" read+ "Lobe AI / Lobe AI · @inbox").++ With no name there is nothing to headline, so the slot carries the+ one thing that can fix it instead of a placeholder pretending to be a+ name. The edit affordance stays hidden until then: naming it IS the+ next step, and offering the full identity form alongside would split+ attention between two ways to do the same thing. */}+ {showNamePrompt ? (+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>+ <Text ellipsis style={{ color: cssVar.colorTextTertiary, fontSize: 20 }}>+ {t('settingAgent.personalName.unnamed', { ns: 'setting' })}+ </Text>+ <Button+ icon={SparklesIcon}+ loading={naming}+ size={'small'}+ type={'text'}+ onClick={() => {+ void autoName();+ }}+ >+ {t('settingAgent.personalName.pickForMe', { ns: 'setting' })}+ </Button>+ </Flexbox>+ ) : (+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>+ <Text ellipsis style={{ fontSize: 36, fontWeight: 600 }}>+ {meta.name?.trim() || t('settingAgent.identity.untitled', { ns: 'setting' })}+ </Text>+ {canEdit ? (+ <ActionIcon+ icon={PencilIcon}+ size={'small'}+ title={t('settingAgent.identity.edit', { ns: 'setting' })}+ onClick={() => createAgentIdentityModal(agentId)}+ />+ ) : null}+ </Flexbox>+ )}+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>+ {/* `Text type="secondary"` resolves to `colorTextDescription`, which antd+ maps to the TERTIARY step — too faint for the line that carries the+ agent's role. Set the secondary colour explicitly, and leave only+ the decorative `@` and the separator at tertiary. */}+ {/* The role always occupies its slot. An agent with no role gets a+ stated placeholder rather than a gap — otherwise the line silently+ collapses to a bare slug and the missing role is indistinguishable+ from a role that was never meant to be there. */}+ <Text+ ellipsis+ style={{+ color: meta.title?.trim() ? cssVar.colorTextSecondary : cssVar.colorTextTertiary,+ }}+ >+ {meta.title?.trim() || t('settingAgent.role.unset', { ns: 'setting' })}+ </Text>+ {slug ? <Text style={{ color: cssVar.colorTextTertiary }}>·</Text> : null}+ {/* The tooltip only renders when a slug exists, so it can always name+ the real url rather than a `<slug>` the reader has to substitute. */}+ {slug ? (+ <Tooltip title={t('settingAgent.slug.openWith', { ns: 'setting', slug })}>+ <Text code style={{ color: cssVar.colorTextSecondary, flex: 'none' }}>+ <span style={{ color: cssVar.colorTextTertiary }}>@</span>+ {slug}+ </Text>+ </Tooltip>+ ) : null}+ </Flexbox></Flexbox></Flexbox>);diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/useAutoName.ts b/src/routes/(main)/agent/profile/features/ProfileEditor/useAutoName.tsnew file mode 100644index 00000000000..a2ad3557b47--- /dev/null+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/useAutoName.ts@@ -0,0 +1,54 @@+import { randomAgentName } from '@lobechat/const';+import { toast } from '@lobehub/ui/base-ui';+import { useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useAgentStore } from '@/store/agent';+import { useGlobalStore } from '@/store/global';+import { globalGeneralSelectors } from '@/store/global/selectors';+import { useHomeStore } from '@/store/home';+import { homeAgentListSelectors } from '@/store/home/selectors';++/**+ * One-click naming for an agent that never got a personal name — agents created+ * before names existed, or through a path that doesn't seed one (REST, group+ * members). Draws from the same pool a fresh agent is seeded from, in the user's+ * language.+ *+ * Names already visible in the sidebar are excluded: the point of a name is to+ * tell two agents apart, so handing out a second "Alice" would defeat it. The+ * list is read at click time rather than subscribed to — it only matters at the+ * moment of the draw, and subscribing would re-render the header on every+ * sidebar change.+ */+export const useAutoName = (agentId: string) => {+ const { t } = useTranslation('setting');+ const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);+ const updateMetaById = useAgentStore((s) => s.updateAgentMetaById);+ const refreshAgentList = useHomeStore((s) => s.refreshAgentList);+ const [naming, setNaming] = useState(false);++ const autoName = useCallback(async () => {+ setNaming(true);+ try {+ const takenNames = homeAgentListSelectors+ .allAgents(useHomeStore.getState())+ .filter((agent) => agent.id !== agentId)+ .map((agent) => agent.name)+ .filter((name): name is string => !!name);++ await updateMetaById(agentId, { name: randomAgentName(locale, takenNames) });+ // The sidebar keeps its own copy of the label, so a rename that skips this+ // leaves the new name on the profile and the old one in the list until+ // something else revalidates. Refreshing here follows the same convention+ // as the sidebar's own rename popover.+ await refreshAgentList();+ } catch {+ toast.error(t('settingAgent.personalName.pickFailed'));+ } finally {+ setNaming(false);+ }+ }, [agentId, locale, refreshAgentList, t, updateMetaById]);++ return { autoName, naming };+};diff --git a/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/AgentItem.tsx b/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/AgentItem.tsxindex 3ae0910269e..7b8f8bfc75d 100644--- a/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/AgentItem.tsx+++ b/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/AgentItem.tsx@@ -1,5 +1,6 @@'use client';+import { agentDisplayName } from '@lobechat/types';import { Avatar, Checkbox, Flexbox, Text } from '@lobehub/ui';import { useHover } from 'ahooks';import { createStaticStyles } from 'antd-style';@@ -76,7 +77,7 @@ const AgentItem = memo<AgentItemProps>(({ agent, defaultTitle, showCheckbox, shoconst toggleAgent = useAgentSelectionStore((s) => s.toggleAgent);const removeAgent = useAgentSelectionStore((s) => s.removeAgent);- const title = agent.title || defaultTitle;+ const title = agentDisplayName(agent, defaultTitle);const avatar = agent.avatar || DEFAULT_AVATAR;const avatarBackground = agent.backgroundColor ?? undefined;diff --git a/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/AvailableAgentList.tsx b/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/AvailableAgentList.tsxindex 1f03a15d7ae..fc9ffcf44ba 100644--- a/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/AvailableAgentList.tsx+++ b/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/AvailableAgentList.tsx@@ -1,5 +1,6 @@'use client';+import { agentDisplayName } from '@lobechat/types';import { Flexbox, SearchBar, Skeleton, Text } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';import isEqual from 'fast-deep-equal';@@ -71,7 +72,7 @@ const AvailableAgentList = memo<AvailableAgentListProps>(({ agents, isLoading })const searchLower = searchTerm.toLowerCase();return agents.filter((agent) => {- const title = agent.title || '';+ const title = agentDisplayName(agent) ?? '';const description = agent.description || '';return (title.toLowerCase().includes(searchLower) || description.toLowerCase().includes(searchLower)diff --git a/src/routes/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsx b/src/routes/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsxindex 362d314ba93..c8daa82589a 100644--- a/src/routes/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsx+++ b/src/routes/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsx@@ -1,5 +1,6 @@'use client';+import { agentDisplayName } from '@lobechat/types';import { ActionIcon, Flexbox } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';import { UserMinus } from 'lucide-react';@@ -122,7 +123,7 @@ const GroupMember = memo<GroupMemberProps>(({ addModalOpen, onAddModalOpenChangeavatar={item.avatar || DEFAULT_AVATAR}background={item.backgroundColor ?? undefined}isExternal={!item.virtual}- title={item.title || t('defaultSession', { ns: 'common' })}+ title={agentDisplayName(item, t('defaultSession', { ns: 'common' }))}actions={<ActionIcondangerdiff --git a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsxindex fa249d1fc00..fca2c1a3fb6 100644--- a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx+++ b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx@@ -1,4 +1,4 @@-import { type SidebarAgentItem } from '@lobechat/types';+import { agentDisplayName, type SidebarAgentItem } from '@lobechat/types';import { ActionIcon, Icon } from '@lobehub/ui';import { createStaticStyles, cssVar } from 'antd-style';import { Loader2, PinIcon } from 'lucide-react';@@ -79,7 +79,7 @@ interface AgentItemProps {}const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate }) => {- const { id, avatar, backgroundColor, title, pinned, slug, userId, visibility } = item;+ const { id, avatar, backgroundColor, pinned, slug, userId, visibility } = item;// Unread count is server-computed (topics.status === 'unread') and carried on// the sidebar list item, so it stays accurate across agents whose topics// aren't loaded into the chat store on this client.@@ -95,8 +95,11 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate })// Separate loading state from chat store - only show loading for this specific agentconst isLoading = useChatStore(operationSelectors.isAgentVisiblyRunning(id));- // Get display title with fallback- const displayTitle = title || t('untitledAgent');+ // Name-first label with fallback (see agentDisplayName)+ const displayTitle = agentDisplayName(item, t('untitledAgent'));+ // When the personal name won the label, the role would otherwise be invisible —+ // keep it beside the name as a muted tag. No tag when the label already IS the role.+ const roleTag = item.name?.trim() && item.title?.trim() ? item.title : undefined;const agentUrl = usePreservedAgentUrl(id);@@ -206,7 +209,16 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate })icon={avatarIcon}key={id}style={style}- title={displayTitle}+ title={+ roleTag ? (+ <>+ {displayTitle}+ <span style={{ fontSize: 12, marginInlineStart: 6, opacity: 0.6 }}>{roleTag}</span>+ </>+ ) : (+ displayTitle+ )+ }onDoubleClick={handleDoubleClick}onDragEnd={handleDragEnd}onDragStart={handleDragStart}diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/InboxItem.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/InboxItem.tsxindex 372902b604b..126b60f45fa 100644--- a/src/routes/(main)/home/_layout/Body/Agent/List/InboxItem.tsx+++ b/src/routes/(main)/home/_layout/Body/Agent/List/InboxItem.tsx@@ -1,6 +1,7 @@'use client';import { DEFAULT_INBOX_AVATAR } from '@lobechat/const';+import { agentDisplayName } from '@lobechat/types';import { Avatar, Icon } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';import { Loader2 } from 'lucide-react';@@ -59,7 +60,7 @@ const InboxItem = memo<InboxItemProps>(({ className, style }) => {inboxAgentId ? operationSelectors.isAgentVisiblyRunning(inboxAgentId) : () => false,);const prefetchAgent = usePrefetchAgent();- const inboxAgentTitle = inboxMeta.title || 'Lobe AI';+ const inboxAgentTitle = agentDisplayName(inboxMeta, 'Lobe AI');const inboxAgentAvatar = inboxMeta.avatar || DEFAULT_INBOX_AVATAR;const inboxUrl = usePreservedAgentUrl(inboxRouteAgentId);diff --git a/src/routes/(main)/settings/skill/features/SkillDetail/index.tsx b/src/routes/(main)/settings/skill/features/SkillDetail/index.tsxindex 2d9a6c7eb63..d90d4997576 100644--- a/src/routes/(main)/settings/skill/features/SkillDetail/index.tsx+++ b/src/routes/(main)/settings/skill/features/SkillDetail/index.tsx@@ -1,6 +1,7 @@'use client';import { getLobehubSkillProviderById } from '@lobechat/const';+import { agentDisplayName } from '@lobechat/types';import { Avatar, Markdown, Skeleton, Tooltip } from '@lobehub/ui';import { Button, confirmModal, toast } from '@lobehub/ui/base-ui';import { createStaticStyles } from 'antd-style';@@ -405,15 +406,21 @@ const SkillDetail = memo<SkillDetailProps>(({ identifier, type, onDelete }) => {const usageAgentId = agentBoundConnector?.agentId;return (<ConnectorDetail- agentTitle={agentBoundConnector?.agentTitle}connectorId={identifier}+ agentTitle={agentDisplayName({+ name: agentBoundConnector?.agentName,+ title: agentBoundConnector?.agentTitle,+ })}middleSlot={usageAgentId ? (<Suspense fallback={null}><AgentConnectorUsageagentAvatar={agentBoundConnector?.agentAvatar}agentId={usageAgentId}- agentTitle={agentBoundConnector?.agentTitle}+ agentTitle={agentDisplayName({+ name: agentBoundConnector?.agentName,+ title: agentBoundConnector?.agentTitle,+ })}/></Suspense>) : undefineddiff --git a/src/routes/(main)/settings/stats/features/rankings/AssistantsRank.tsx b/src/routes/(main)/settings/stats/features/rankings/AssistantsRank.tsxindex 8e26eea47a6..1837f226683 100644--- a/src/routes/(main)/settings/stats/features/rankings/AssistantsRank.tsx+++ b/src/routes/(main)/settings/stats/features/rankings/AssistantsRank.tsx@@ -1,4 +1,5 @@import { AGENT_CHAT_URL } from '@lobechat/const';+import { agentDisplayName } from '@lobechat/types';import { BarList } from '@lobehub/charts';import { ActionIcon, Avatar } from '@lobehub/ui';import { MaximizeIcon } from 'lucide-react';@@ -41,7 +42,7 @@ export const AssistantsRank = memo<{ mobile?: boolean }>(({ mobile }) => {return {icon: (<Avatar- alt={item.title || t('defaultAgent', { ns: 'chat' })}+ alt={agentDisplayName(item, t('defaultAgent', { ns: 'chat' }))}avatar={item.avatar || DEFAULT_AVATAR}background={item.backgroundColor || undefined}size={20}@@ -52,7 +53,7 @@ export const AssistantsRank = memo<{ mobile?: boolean }>(({ mobile }) => {<Link href={link} style={{ color: 'inherit' }}>{isInbox? t('inbox.title', { ns: 'chat' })- : item.title || t('defaultAgent', { ns: 'chat' })}+ : agentDisplayName(item, t('defaultAgent', { ns: 'chat' }))}</Link>),value: item.count,diff --git a/src/routes/(mobile)/chat/features/ChatHeader/ChatHeaderTitle.tsx b/src/routes/(mobile)/chat/features/ChatHeader/ChatHeaderTitle.tsxindex e1e5c780fb3..26714578442 100644--- a/src/routes/(mobile)/chat/features/ChatHeader/ChatHeaderTitle.tsx+++ b/src/routes/(mobile)/chat/features/ChatHeader/ChatHeaderTitle.tsx@@ -19,7 +19,7 @@ const ChatHeaderTitle = memo(() => {topicSelectors.currentActiveTopic(s),]);const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);- const title = useAgentStore(agentSelectors.currentAgentTitle);+ const title = useAgentStore(agentSelectors.currentAgentDisplayName);const displayTitle = isInbox ? 'Lobe AI' : title;diff --git a/src/routes/(popup)/agent/[aid]/QuickChatAgentSwitcher.tsx b/src/routes/(popup)/agent/[aid]/QuickChatAgentSwitcher.tsxindex f6f873a41ec..dec9e8324f1 100644--- a/src/routes/(popup)/agent/[aid]/QuickChatAgentSwitcher.tsx+++ b/src/routes/(popup)/agent/[aid]/QuickChatAgentSwitcher.tsx@@ -1,6 +1,7 @@'use client';import { INBOX_SESSION_ID } from '@lobechat/const';+import { agentDisplayName } from '@lobechat/types';import { Avatar, Flexbox, Icon, Input, Popover, Tooltip } from '@lobehub/ui';import { createStaticStyles, cx } from 'antd-style';import isEqual from 'fast-deep-equal';@@ -125,7 +126,7 @@ const useSwitchItems = (): SwitchItem[] => {id: INBOX_SESSION_ID,isInbox: true,navId: INBOX_SESSION_ID,- title: inboxMeta?.title || 'Inbox',+ title: agentDisplayName(inboxMeta, 'Inbox'),};const fromAgent = (a: SidebarAgentItem): SwitchItem => ({@@ -133,7 +134,7 @@ const useSwitchItems = (): SwitchItem[] => {background: a.backgroundColor || undefined,id: a.id,navId: a.id,- title: a.title || 'Untitled',+ title: agentDisplayName(a, 'Untitled'),});const isAgent = (a: SidebarAgentItem): boolean => a.type === 'agent';diff --git a/src/services/agent.ts b/src/services/agent.tsindex 591b850ef82..e9d60facf19 100644--- a/src/services/agent.ts+++ b/src/services/agent.ts@@ -11,6 +11,8 @@ export interface AvailableAgentItem {backgroundColor: string | null;description: string | null;id: string;+ /** Personal name; resolve the label with `agentDisplayName(item, fallback)`. */+ name: string | null;title: string | null;}@@ -28,7 +30,7 @@ type MarketAgentModel =type AgentMetaUpdate = Partial<Pick<AgentItem,- 'avatar' | 'backgroundColor' | 'description' | 'marketIdentifier' | 'tags' | 'title'+ 'avatar' | 'backgroundColor' | 'description' | 'marketIdentifier' | 'name' | 'tags' | 'title'>>;@@ -241,6 +243,20 @@ class AgentService {return lambdaClient.agent.getBuiltinAgent.query({ slug });};+ /**+ * Resolve a url slug to its agent id. Returns `null` for an unknown slug and+ * for one the caller can't see — the two are deliberately indistinguishable.+ */+ resolveAgentIdBySlug = async (slug: string): Promise<string | null> => {+ const { agentId } = await lambdaClient.agent.resolveAgentIdBySlug.query({ slug });+ return agentId;+ };++ /** Rename an agent's url slug (validated server-side; see `updateAgentSlug`). */+ updateAgentSlug = async (agentId: string, slug: string) => {+ return lambdaClient.agent.updateAgentSlug.mutate({ agentId, slug });+ };+/*** Remove an agent and its associated session*/diff --git a/src/services/chat/mecha/contextEngineering.test.ts b/src/services/chat/mecha/contextEngineering.test.tsindex 71c5603ab80..bd1868c92ad 100644--- a/src/services/chat/mecha/contextEngineering.test.ts+++ b/src/services/chat/mecha/contextEngineering.test.ts@@ -222,6 +222,7 @@ describe('contextEngineering', () => {backgroundColor: null,description: null,id: 'agent-1',+ name: null,title: 'Current Agent',},{@@ -229,6 +230,7 @@ describe('contextEngineering', () => {backgroundColor: null,description: 'Helps with setup',id: 'agent-2',+ name: null,title: 'Setup Agent',},],diff --git a/src/store/agent/selectors/selectors.ts b/src/store/agent/selectors/selectors.tsindex e75bb327217..922bcc00a6e 100644--- a/src/store/agent/selectors/selectors.ts+++ b/src/store/agent/selectors/selectors.ts@@ -9,6 +9,7 @@ import {isDesktop,} from '@lobechat/const';import {+ agentDisplayName,type AgentMode,type KnowledgeItem,type LobeAgentConfig,@@ -38,6 +39,13 @@ const currentAgentData = (s: AgentStoreState) =>const currentAgentTitle = (s: AgentStoreState) => currentAgentData(s)?.title;+/**+ * The label to show for the active agent: personal name first, role as the+ * fallback. Use this for rendering; `currentAgentTitle` stays the raw role for+ * anything that edits or reasons about it.+ */+const currentAgentDisplayName = (s: AgentStoreState) => agentDisplayName(currentAgentData(s));+const getDefaultAvatarByAgentId = (s: AgentStoreState, agentId?: string) => {const inboxAgentId = builtinAgentSelectors.inboxAgentId(s);@@ -71,6 +79,7 @@ const currentAgentMeta = (s: AgentStoreState): MetaData => {backgroundColor: data?.backgroundColor || DEFAULT_BACKGROUND_COLOR,description: data?.description || undefined,marketIdentifier: data?.marketIdentifier || undefined,+ name: data?.name || undefined,tags: data?.tags,title: data?.title || undefined,};@@ -91,6 +100,7 @@ const getAgentMetaById =backgroundColor: data.backgroundColor || DEFAULT_BACKGROUND_COLOR,description: data.description || undefined,marketIdentifier: data.marketIdentifier || undefined,+ name: data.name || undefined,tags: data.tags,title: data.title || undefined,};@@ -361,6 +371,7 @@ export const agentSelectors = {currentAgentTTS,currentAgentTTSVoice,currentAgentTags,+ currentAgentDisplayName,currentAgentTitle,currentAgentVisibility,currentAgentWorkingDirectory,diff --git a/src/store/agent/slices/agent/action.test.ts b/src/store/agent/slices/agent/action.test.tsindex 0a88ab20d3b..376fd46f675 100644--- a/src/store/agent/slices/agent/action.test.ts+++ b/src/store/agent/slices/agent/action.test.ts@@ -7,6 +7,7 @@ import { setScopedMutate } from '@/libs/swr';import { agentConfigKeys } from '@/libs/swr/keys';import { agentService } from '@/services/agent';import { agentDocumentService } from '@/services/agentDocument';+import { useGlobalStore } from '@/store/global';import { type LobeAgentConfig } from '@/types/agent';import { withSWR } from '~test-utils';@@ -176,6 +177,7 @@ describe('AgentSlice Actions', () => {backgroundColor: null,description: 'stale',id: 'agent-1',+ name: null,title: 'Stale Agent',},],@@ -188,6 +190,36 @@ describe('AgentSlice Actions', () => {expect(result.current.availableAgents).toBeUndefined();});++ it('should seed a personal name matching the user language', async () => {+ vi.mocked(agentService.createAgent).mockResolvedValue({ agentId: 'agent-2' });+ const status = useGlobalStore.getState().status;+ useGlobalStore.setState({ status: { ...status, language: 'zh-CN' } });+ const { result } = renderHook(() => useAgentStore());++ try {+ await act(async () => {+ await result.current.createAgent({ config: { title: '健康助手' } });+ });++ const config = vi.mocked(agentService.createAgent).mock.calls[0][0].config!;+ expect(config.title).toBe('健康助手');+ expect(config.name).toMatch(/^\p{Script=Han}+$/u);+ } finally {+ useGlobalStore.setState({ status });+ }+ });++ it('should keep a name the caller already provided', async () => {+ vi.mocked(agentService.createAgent).mockResolvedValue({ agentId: 'agent-2' });+ const { result } = renderHook(() => useAgentStore());++ await act(async () => {+ await result.current.createAgent({ config: { name: 'Ada', title: 'Math Tutor' } });+ });++ expect(vi.mocked(agentService.createAgent).mock.calls[0][0].config?.name).toBe('Ada');+ });});describe('useFetchAgentDocuments', () => {@@ -223,6 +255,7 @@ describe('AgentSlice Actions', () => {backgroundColor: null,description: 'Helps with setup',id: 'agent-1',+ name: null,title: 'Setup',},]);@@ -238,6 +271,7 @@ describe('AgentSlice Actions', () => {backgroundColor: null,description: 'Helps with setup',id: 'agent-1',+ name: null,title: 'Setup',},]);@@ -300,6 +334,7 @@ describe('AgentSlice Actions', () => {backgroundColor: null,description: 'stale',id: 'agent-1',+ name: null,title: 'Stale Agent',},],@@ -863,6 +898,7 @@ describe('AgentSlice Actions', () => {backgroundColor: null,description: 'Old Desc',id: 'agent-1',+ name: null,title: 'Old Title',},],diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.tsindex 916e33431f8..165787c2555 100644--- a/src/store/agent/slices/agent/action.ts+++ b/src/store/agent/slices/agent/action.ts@@ -1,4 +1,4 @@-import { isDesktop } from '@lobechat/const';+import { isDesktop, randomAgentName } from '@lobechat/const';import { type AgentContextDocument } from '@lobechat/context-engine';import {isChatGroupSessionId,@@ -24,6 +24,8 @@ import {agentDocumentSWRKeys,resolveAgentDocumentsContext,} from '@/services/agentDocument';+import { useGlobalStore } from '@/store/global';+import { globalGeneralSelectors } from '@/store/global/selectors';import type { StoreSetter } from '@/store/types';import { getUserStoreState } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';@@ -42,7 +44,7 @@ import type { AgentSliceState, LoadingState, SaveStatus } from './initialState';type AgentMetaUpdate = Partial<Pick<AgentItem,- 'avatar' | 'backgroundColor' | 'description' | 'marketIdentifier' | 'tags' | 'title'+ 'avatar' | 'backgroundColor' | 'description' | 'marketIdentifier' | 'name' | 'tags' | 'title'>>;type AgencyConfigPatch = PartialDeep<LobeAgentAgencyConfig>;@@ -140,7 +142,18 @@ export class AgentSliceActionImpl {};createAgent = async (params: CreateAgentParams): Promise<CreateAgentResult> => {- const result = await agentService.createAgent(params);+ // Seed a personal name so a new agent has an identity before the Agent+ // Builder conversation produces one; the builder may replace it later. This+ // lives here rather than in the create endpoint because the language only+ // resolves on the client (`auto` follows the browser). A caller that already+ // carries a name — e.g. a market agent — keeps it.+ const locale = globalGeneralSelectors.currentLanguage(useGlobalStore.getState());+ const config = {+ ...params.config,+ name: params.config?.name || randomAgentName(locale),+ };++ const result = await agentService.createAgent({ ...params, config });this.#get().invalidateAvailableAgents();// Track new agent creation analyticsdiff --git a/src/store/brief/types.ts b/src/store/brief/types.tsindex de909b088ee..22247aa3743 100644--- a/src/store/brief/types.ts+++ b/src/store/brief/types.ts@@ -9,6 +9,8 @@ export interface AgentAvatarInfo {avatar: string | null;backgroundColor: string | null;id: string;+ /** Personal name; renderers resolve the label with `agentDisplayName(agent, fallback)`. */+ name: string | null;title: string | null;}diff --git a/src/store/chat/slices/message/supervisor.ts b/src/store/chat/slices/message/supervisor.tsindex 6c2be51045b..db4b7384b23 100644--- a/src/store/chat/slices/message/supervisor.ts+++ b/src/store/chat/slices/message/supervisor.ts@@ -27,11 +27,7 @@ export interface SupervisorDecisionResult {}export type SupervisorToolName =- | 'create_todo'- | 'finish_todo'- | 'wait_for_user_input'- | 'trigger_agent'- | 'trigger_agent_dm';+ 'create_todo' | 'finish_todo' | 'wait_for_user_input' | 'trigger_agent' | 'trigger_agent_dm';export interface SupervisorToolCall {parameter?: unknown;@@ -94,7 +90,7 @@ export class GroupChatSupervisor {allowDM: context.allowDM,availableAgents: context.availableAgents.filter((agent) => agent.id)- .map((agent) => ({ id: agent.id, title: agent.title })),+ .map((agent) => ({ id: agent.id, name: agent.name, title: agent.title })),messages: context.messages,scene: context.scene,todoList: context.todoList,diff --git a/src/store/chat/utils/desktopNotification.ts b/src/store/chat/utils/desktopNotification.tsindex 5fd8369e781..ba76877795f 100644--- a/src/store/chat/utils/desktopNotification.ts+++ b/src/store/chat/utils/desktopNotification.ts@@ -6,6 +6,7 @@ import {isDesktop,} from '@lobechat/const';import type { ConversationContext } from '@lobechat/types';+import { agentDisplayName } from '@lobechat/types';import { t } from 'i18next';import { getAgentStoreState } from '@/store/agent';@@ -81,7 +82,8 @@ export const resolveNotificationTitle = (if (context.agentId) {const agentMeta = agentSelectors.getAgentMetaById(context.agentId)(getAgentStoreState());- if (agentMeta?.title) return agentMeta.title;+ const agentName = agentDisplayName(agentMeta);+ if (agentName) return agentName;}return fallbackTitle;diff --git a/src/store/tool/slices/connector/types.ts b/src/store/tool/slices/connector/types.tsindex 760fa2b1ea6..7e0e598a68a 100644--- a/src/store/tool/slices/connector/types.ts+++ b/src/store/tool/slices/connector/types.ts@@ -44,5 +44,7 @@ export interface ConnectorWithTools {*/export interface AgentBoundConnector extends ConnectorWithTools {agentAvatar: string | null;+ /** Personal name; resolve the label with `agentDisplayName({ name, title })`. */+ agentName: string | null;agentTitle: string | null;}