π€― 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
π fix(agent): centralize inbox agent meta fallback across read paths (#15948)
Arvin Xu95dc8e00b012
diff --git a/apps/server/src/routers/lambda/messenger.ts b/apps/server/src/routers/lambda/messenger.tsindex 4cfa4fb4734..df072f7dd38 100644--- a/apps/server/src/routers/lambda/messenger.ts+++ b/apps/server/src/routers/lambda/messenger.ts@@ -1,6 +1,5 @@-import { DEFAULT_INBOX_AVATAR, INBOX_SESSION_ID } from '@lobechat/const';import { TRPCError } from '@trpc/server';-import { and, desc, eq, ne, or } from 'drizzle-orm';+import { eq } from 'drizzle-orm';import { z } from 'zod';import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';@@ -12,6 +11,7 @@ import {isMessengerPlatformEnabled,type MessengerPlatform,} from '@/config/messenger';+import { AgentModel } from '@/database/models/agent';import {MessengerAccountLinkConflictError,MessengerAccountLinkModel,@@ -23,7 +23,6 @@ import { RbacModel } from '@/database/models/rbac';import { WorkspaceModel } from '@/database/models/workspace';import { agents, users } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';-import { buildWorkspaceWhere } from '@/database/utils/workspace';import { authedProcedure, publicProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';@@ -122,6 +121,12 @@ const messengerProcedure = authedProcedure.use(serverDatabase).use(async (opts)// userId), and per-agent authorization happens in-handler via// `resolveAuthorizedAgentScope`.messengerLinkModel: new MessengerAccountLinkModel(ctx.serverDB, ctx.userId),+ // The bindable-agents scope is request-driven β the cascading scope+ // picker passes the workspace via input, not the ambient header β so+ // expose a workspace-parameterized AgentModel factory rather than a+ // single pre-scoped instance.+ getAgentModel: (workspaceId?: string | null) =>+ new AgentModel(ctx.serverDB, ctx.userId, workspaceId ?? undefined),},});});@@ -454,44 +459,10 @@ export const messengerRouter = router({}}- const rows = await serverDB- .select({- avatar: agents.avatar,- backgroundColor: agents.backgroundColor,- id: agents.id,- slug: agents.slug,- title: agents.title,- })- .from(agents)- .where(- and(- buildWorkspaceWhere({ userId, workspaceId: workspaceId ?? undefined }, agents),- or(ne(agents.virtual, true), eq(agents.slug, INBOX_SESSION_ID)),- ),- )- .orderBy(desc(agents.updatedAt));-- const mapped = rows- .filter((row) => row.id)- .map((row) => ({- avatar: row.avatar || (row.slug === INBOX_SESSION_ID ? DEFAULT_INBOX_AVATAR : null),- backgroundColor: row.backgroundColor,- id: row.id,- slug: row.slug,- title: row.title || (row.slug === INBOX_SESSION_ID ? 'LobeAI' : null),- }));-- // Pin the inbox/LobeAI agent to the top regardless of updatedAt β it's- // the implicit "default" agent and should always be the first option.- const inboxIdx = mapped.findIndex((row) => row.slug === INBOX_SESSION_ID);- if (inboxIdx > 0) {- const [inbox] = mapped.splice(inboxIdx, 1);- mapped.unshift(inbox);- }- return mapped.map(({ slug, ...rest }) => ({- ...rest,- isInbox: slug === INBOX_SESSION_ID,- }));+ // Inbox meta fallback, the virtual-or-inbox filter, inbox pinning, and the+ // `isInbox` flag all live in the model. Blank non-inbox titles stay null+ // here so the web picker can apply its own i18n default.+ return ctx.getAgentModel(workspaceId).listMessengerBindableAgents();}),/**diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.tsindex 32a78b87c50..b4e5b3ee389 100644--- a/apps/server/src/routers/lambda/topic.ts+++ b/apps/server/src/routers/lambda/topic.ts@@ -4,19 +4,21 @@ import {type RecentTopicGroupMember,} from '@lobechat/types';import { cleanObject } from '@lobechat/utils';-import { eq, inArray } from 'drizzle-orm';+import { inArray } from 'drizzle-orm';import { after } from 'next/server';import { z } from 'zod';import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';+import { AgentModel } from '@/database/models/agent';import { AgentOperationModel } from '@/database/models/agentOperation';+import { ChatGroupModel } from '@/database/models/chatGroup';import { MessageModel } from '@/database/models/message';import { TopicModel } from '@/database/models/topic';import { TopicShareModel } from '@/database/models/topicShare';import { AgentMigrationRepo } from '@/database/repositories/agentMigration';import { TopicImporterRepo } from '@/database/repositories/topicImporter';-import { agents, chatGroups, chatGroupsAgents } from '@/database/schemas';+import { chatGroups } from '@/database/schemas';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { type BatchTaskResult } from '@/types/service';@@ -35,7 +37,9 @@ const topicProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>return opts.next({ctx: {agentMigrationRepo: new AgentMigrationRepo(ctx.serverDB, ctx.userId, wsId),+ agentModel: new AgentModel(ctx.serverDB, ctx.userId, wsId),agentOperationModel: new AgentOperationModel(ctx.serverDB, ctx.userId, wsId),+ chatGroupModel: new ChatGroupModel(ctx.serverDB, ctx.userId, wsId),topicImporterRepo: new TopicImporterRepo(ctx.serverDB, ctx.userId, wsId),topicModel: new TopicModel(ctx.serverDB, ctx.userId, wsId),topicShareModel: new TopicShareModel(ctx.serverDB, ctx.userId, wsId),@@ -445,22 +449,14 @@ export const topicRouter = router({// Collect all agentIds to fetch agent infoconst allAgentIds = [...new Set(topicAgentIdMap.values())];- // Batch query agent info+ // Batch query agent info (already normalized for the inbox agent)const agentInfoMap = new Map<string,{ avatar: string | null; backgroundColor: string | null; id: string; title: string | null }>();if (allAgentIds.length > 0) {- const agentInfos = await ctx.serverDB- .select({- avatar: agents.avatar,- backgroundColor: agents.backgroundColor,- id: agents.id,- title: agents.title,- })- .from(agents)- .where(inArray(agents.id, allAgentIds));+ const agentInfos = await ctx.agentModel.getAgentAvatarsByIds(allAgentIds);for (const agent of agentInfos) {agentInfoMap.set(agent.id, agent);@@ -481,28 +477,9 @@ export const topicRouter = router({.from(chatGroups).where(inArray(chatGroups.id, allGroupIds));- // Query group member agents (get avatar info)- const groupMembersRaw = await ctx.serverDB- .select({- agentAvatar: agents.avatar,- agentBackgroundColor: agents.backgroundColor,- chatGroupId: chatGroupsAgents.chatGroupId,- order: chatGroupsAgents.order,- })- .from(chatGroupsAgents)- .leftJoin(agents, eq(chatGroupsAgents.agentId, agents.id))- .where(inArray(chatGroupsAgents.chatGroupId, allGroupIds));-- // Group members by chatGroupId- const groupMembersMap = new Map<string, RecentTopicGroupMember[]>();- for (const member of groupMembersRaw) {- const members = groupMembersMap.get(member.chatGroupId) || [];- members.push({- avatar: member.agentAvatar,- backgroundColor: member.agentBackgroundColor,- });- groupMembersMap.set(member.chatGroupId, members);- }+ // Query group member avatars (already normalized for the inbox agent)+ const groupMembersMap: Map<string, RecentTopicGroupMember[]> =+ await ctx.chatGroupModel.getMemberAvatarsByGroupIds(allGroupIds);// Build group info mapfor (const group of chatGroupInfos) {diff --git a/apps/server/src/services/agent/index.test.ts b/apps/server/src/services/agent/index.test.tsindex bc10ecb7c3a..76bf36ac7cc 100644--- a/apps/server/src/services/agent/index.test.ts+++ b/apps/server/src/services/agent/index.test.ts@@ -1,5 +1,5 @@// @vitest-environment node-import { DEFAULT_AGENT_CONFIG } from '@lobechat/const';+import { DEFAULT_AGENT_CONFIG, DEFAULT_INBOX_AVATAR, DEFAULT_INBOX_TITLE } from '@lobechat/const';import { beforeEach, describe, expect, it, vi } from 'vitest';import { AgentModel } from '@/database/models/agent';@@ -190,10 +190,12 @@ describe('AgentService', () => {expect(result?.provider).toBe('anthropic');});- it('should merge avatar from builtin-agents package definition', async () => {+ it('should fallback inbox title and avatar', async () => {const mockAgent = {+ avatar: null,id: 'agent-1',slug: 'inbox',+ title: null,model: 'gpt-4',};@@ -207,8 +209,8 @@ describe('AgentService', () => {const newService = new AgentService(mockDb, mockUserId);const result = await newService.getBuiltinAgent('inbox');- // Avatar should be merged from BUILTIN_AGENTS definition- expect((result as any)?.avatar).toBe('/avatars/lobe-ai.png');+ expect((result as any)?.avatar).toBe(DEFAULT_INBOX_AVATAR);+ expect((result as any)?.title).toBe(DEFAULT_INBOX_TITLE);});it('should not include avatar for non-builtin agents', async () => {diff --git a/apps/server/src/services/agent/index.ts b/apps/server/src/services/agent/index.tsindex 76d0ca5639b..b2b0791e6d4 100644--- a/apps/server/src/services/agent/index.ts+++ b/apps/server/src/services/agent/index.ts@@ -10,6 +10,7 @@ import { type PartialDeep } from 'type-fest';import { AgentModel } from '@/database/models/agent';import { SessionModel } from '@/database/models/session';import { UserModel } from '@/database/models/user';+import { normalizeInboxAgentAvatar, normalizeInboxAgentTitle } from '@/database/utils/inboxAgent';import { getRedisConfig } from '@/envs/redis';import {getJSONFromRedis,@@ -83,14 +84,20 @@ export class AgentService {const mergedConfig = this.mergeDefaultConfig(agent, defaultAgentConfig);if (!mergedConfig) return null;+ const identity = { slug: (mergedConfig as { slug?: string | null }).slug ?? slug };+ const normalizedConfig = {+ ...mergedConfig,+ avatar: normalizeInboxAgentAvatar(mergedConfig.avatar, identity),+ title: normalizeInboxAgentTitle(mergedConfig.title, identity),+ };// Use builtin avatar as fallback only when DB has no custom avatarconst builtinAgent = BUILTIN_AGENTS[slug as BuiltinAgentSlug];- if (builtinAgent?.avatar && !mergedConfig.avatar) {- return { ...mergedConfig, avatar: builtinAgent.avatar };+ if (builtinAgent?.avatar && !normalizedConfig.avatar) {+ return { ...normalizedConfig, avatar: builtinAgent.avatar };}- return mergedConfig;+ return normalizedConfig;}/**diff --git a/apps/server/src/services/messenger/MessengerRouter.ts b/apps/server/src/services/messenger/MessengerRouter.tsindex 31b2ae6362c..2d80b499ca0 100644--- a/apps/server/src/services/messenger/MessengerRouter.ts+++ b/apps/server/src/services/messenger/MessengerRouter.ts@@ -1,5 +1,4 @@import { createIoRedisState } from '@chat-adapter/state-ioredis';-import { INBOX_SESSION_ID } from '@lobechat/const';import {Chat,ConsoleLogger,@@ -8,16 +7,14 @@ import {type SlashCommandEvent,} from 'chat';import debug from 'debug';-import { and, desc, eq, ne, or } from 'drizzle-orm';import type { MessengerPlatform } from '@/config/messenger';import { getServerDB } from '@/database/core/db-adaptor';+import { AgentModel } from '@/database/models/agent';import { MessengerAccountLinkModel } from '@/database/models/messengerAccountLink';import { WorkspaceModel } from '@/database/models/workspace';import type { MessengerAccountLinkItem } from '@/database/schemas';-import { agents } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';-import { buildWorkspaceWhere } from '@/database/utils/workspace';import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';import { AiAgentService } from '@/server/services/aiAgent';@@ -1511,33 +1508,17 @@ export class MessengerRouter {userId: string,workspaceId?: string | null,): Promise<AgentSummary[]> {- const rows = await serverDB- .select({ id: agents.id, slug: agents.slug, title: agents.title })- .from(agents)- .where(- and(- buildWorkspaceWhere({ userId, workspaceId: workspaceId ?? undefined }, agents),- or(ne(agents.virtual, true), eq(agents.slug, INBOX_SESSION_ID)),- ),- )- .orderBy(desc(agents.updatedAt));-- const mapped = rows- .filter((row) => row.id)- .map((row) => ({- id: row.id,- slug: row.slug,- title:- (row.title && row.title.trim()) ||- (row.slug === INBOX_SESSION_ID ? 'LobeAI' : 'Custom Agent'),- }));-- const inboxIdx = mapped.findIndex((row) => row.slug === INBOX_SESSION_ID);- if (inboxIdx > 0) {- const [inbox] = mapped.splice(inboxIdx, 1);- mapped.unshift(inbox);- }- return mapped.map(({ slug: _slug, ...rest }) => rest);+ // 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.+ const rows = await new AgentModel(+ serverDB,+ userId,+ workspaceId ?? undefined,+ ).listMessengerBindableAgents({ fallbackTitle: 'Custom Agent' });++ // `fallbackTitle` guarantees a non-null title for every row.+ return rows.map((row) => ({ id: row.id, title: row.title! }));}private async dispatchToAgent(diff --git a/packages/const/src/meta.ts b/packages/const/src/meta.tsindex 33363696629..da467328c12 100644--- a/packages/const/src/meta.ts+++ b/packages/const/src/meta.ts@@ -7,5 +7,6 @@ export const DEFAULT_SUPERVISOR_AVATAR = 'ποΈ';export const DEFAULT_SUPERVISOR_ID = 'supervisor';export const DEFAULT_BACKGROUND_COLOR = undefined;export const DEFAULT_AGENT_META: MetaData = {};+export const DEFAULT_INBOX_TITLE = 'Lobe AI';export const DEFAULT_INBOX_AVATAR = BRANDING_LOGO_URL || '/avatars/lobe-ai.png';export const DEFAULT_USER_AVATAR_URL = BRANDING_LOGO_URL || '/icons/icon-192x192.png';diff --git a/packages/database/src/models/__tests__/agent.getAvatars.test.ts b/packages/database/src/models/__tests__/agent.getAvatars.test.tsindex d2e24172d4c..80a3f4d08c7 100644--- a/packages/database/src/models/__tests__/agent.getAvatars.test.ts+++ b/packages/database/src/models/__tests__/agent.getAvatars.test.ts@@ -1,4 +1,5 @@// @vitest-environment node+import { DEFAULT_INBOX_AVATAR, DEFAULT_INBOX_TITLE, INBOX_SESSION_ID } from '@lobechat/const';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';@@ -78,7 +79,7 @@ describe('AgentModel.getAgentAvatarsByIds', () => {avatar: null,backgroundColor: null,id: 'agent-inbox',- slug: 'inbox',+ slug: INBOX_SESSION_ID,title: null,userId,});@@ -88,10 +89,10 @@ describe('AgentModel.getAgentAvatarsByIds', () => {expect(result).toHaveLength(1);expect(result[0]).toEqual({- avatar: '/avatars/lobe-ai.png',+ avatar: DEFAULT_INBOX_AVATAR,backgroundColor: null,id: 'agent-inbox',- title: 'Lobe AI',+ title: DEFAULT_INBOX_TITLE,});});diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.tsindex 87967f5340c..a9b8b478954 100644--- a/packages/database/src/models/__tests__/agent.test.ts+++ b/packages/database/src/models/__tests__/agent.test.ts@@ -1,5 +1,5 @@// @vitest-environment node-import { INBOX_SESSION_ID } from '@lobechat/const';+import { DEFAULT_INBOX_AVATAR, DEFAULT_INBOX_TITLE, INBOX_SESSION_ID } from '@lobechat/const';import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';@@ -1185,6 +1185,8 @@ describe('AgentModel', () => {expect(result).toBeDefined();expect(result?.id).toBe(agent.id);expect(result?.slug).toBe(INBOX_SESSION_ID);+ expect(result?.title).toBe(DEFAULT_INBOX_TITLE);+ expect(result?.avatar).toBe(DEFAULT_INBOX_AVATAR);});it('should find inbox from legacy session and update agent slug', async () => {@@ -1749,6 +1751,25 @@ describe('AgentModel', () => {);});+ it('should fallback inbox agent meta by slug', async () => {+ await serverDB.insert(agents).values({+ avatar: null,+ id: 'inbox-agent-query',+ slug: INBOX_SESSION_ID,+ title: null,+ userId,+ virtual: null as unknown as boolean,+ });++ const result = await agentModel.queryAgents();+ const inbox = result.find((agent) => agent.id === 'inbox-agent-query');++ expect(inbox).toMatchObject({+ avatar: DEFAULT_INBOX_AVATAR,+ title: DEFAULT_INBOX_TITLE,+ });+ });+it('should filter by keyword in title and description', async () => {await agentModel.create({title: 'Code Assistant',@@ -2196,4 +2217,67 @@ describe('AgentModel', () => {expect(result).toHaveLength(1);});});++ describe('listMessengerBindableAgents', () => {+ it('should keep the inbox, exclude other virtual agents, pin inbox first, and fallback its meta', async () => {+ await serverDB.insert(agents).values([+ // Inbox is the oldest, yet must be pinned to the top.+ {+ avatar: null,+ id: 'mb-inbox',+ slug: INBOX_SESSION_ID,+ title: null,+ updatedAt: new Date('2023-01-01'),+ userId,+ virtual: true,+ },+ {+ id: 'mb-normal',+ title: 'Normal',+ updatedAt: new Date('2024-01-01'),+ userId,+ },+ { id: 'mb-virtual', title: 'Virtual', userId, virtual: true },+ ]);++ const result = await agentModel.listMessengerBindableAgents();++ expect(result.map((r) => r.id)).toEqual(['mb-inbox', 'mb-normal']);+ expect(result[0]).toMatchObject({+ avatar: DEFAULT_INBOX_AVATAR,+ id: 'mb-inbox',+ isInbox: true,+ title: DEFAULT_INBOX_TITLE,+ });+ expect(result[1]).toMatchObject({ id: 'mb-normal', isInbox: false, title: 'Normal' });+ });++ it('should fall back a blank non-inbox title to options.fallbackTitle (null by default)', async () => {+ await serverDB.insert(agents).values([+ { id: 'mb-blank', title: null, userId },+ { id: 'mb-named', title: 'Named', userId },+ ]);++ const withoutFallback = await agentModel.listMessengerBindableAgents();+ expect(withoutFallback.find((r) => r.id === 'mb-blank')?.title).toBeNull();++ const withFallback = await agentModel.listMessengerBindableAgents({+ fallbackTitle: 'Custom Agent',+ });+ expect(withFallback.find((r) => r.id === 'mb-blank')?.title).toBe('Custom Agent');+ // A real title is never overridden by the fallback.+ expect(withFallback.find((r) => r.id === 'mb-named')?.title).toBe('Named');+ });++ it('should only list the current user agents', async () => {+ await serverDB.insert(agents).values([+ { id: 'mb-mine', title: 'Mine', userId },+ { id: 'mb-theirs', title: 'Theirs', userId: userId2 },+ ]);++ const result = await agentModel.listMessengerBindableAgents();++ expect(result.map((r) => r.id)).toEqual(['mb-mine']);+ });+ });});diff --git a/packages/database/src/models/__tests__/chatGroup.test.ts b/packages/database/src/models/__tests__/chatGroup.test.tsindex 92b0b27642d..683343380b5 100644--- a/packages/database/src/models/__tests__/chatGroup.test.ts+++ b/packages/database/src/models/__tests__/chatGroup.test.ts@@ -1,4 +1,5 @@// @vitest-environment node+import { DEFAULT_INBOX_AVATAR, INBOX_SESSION_ID } from '@lobechat/const';import { CHAT_GROUP_SESSION_ID_PREFIX } from '@lobechat/types';import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';@@ -1025,4 +1026,32 @@ describe('ChatGroupModel', () => {expect(result).toEqual([expect.objectContaining({ id: 'workspace-group', workspaceId })]);});});++ describe('getMemberAvatarsByGroupIds', () => {+ it('should group member avatars by chatGroupId in member order with inbox fallback', async () => {+ await serverDB.insert(agentsTable).values([+ { avatar: '/custom.png', id: 'member-custom', slug: 'custom', userId },+ { avatar: null, id: 'member-inbox', slug: INBOX_SESSION_ID, userId },+ ]);+ await serverDB.insert(chatGroups).values({ id: 'group-avatars', title: 'G', userId });+ await serverDB.insert(chatGroupsAgents).values([+ { agentId: 'member-inbox', chatGroupId: 'group-avatars', order: 1, userId },+ { agentId: 'member-custom', chatGroupId: 'group-avatars', order: 0, userId },+ ]);++ const result = await chatGroupModel.getMemberAvatarsByGroupIds(['group-avatars']);++ // Ordered by `order`: custom (0) before inbox (1); inbox avatar falls back.+ expect(result.get('group-avatars')).toEqual([+ { avatar: '/custom.png', backgroundColor: null },+ { avatar: DEFAULT_INBOX_AVATAR, backgroundColor: null },+ ]);+ });++ it('should return an empty map for no group ids', async () => {+ const result = await chatGroupModel.getMemberAvatarsByGroupIds([]);++ expect(result.size).toBe(0);+ });+ });});diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.tsindex bc7d3a50122..35d3b53ce6d 100644--- a/packages/database/src/models/agent.ts+++ b/packages/database/src/models/agent.ts@@ -1,5 +1,5 @@import { getAgentPersistConfig } from '@lobechat/builtin-agents';-import { DEFAULT_INBOX_AVATAR, INBOX_SESSION_ID } from '@lobechat/const';+import { INBOX_SESSION_ID } from '@lobechat/const';import type { AgentRankItem } from '@lobechat/types';import { and, count, desc, eq, gt, ilike, inArray, isNull, ne, or, sql } from 'drizzle-orm';import type { PartialDeep } from 'type-fest';@@ -24,6 +24,7 @@ import {topics,} from '../schemas';import type { LobeChatDatabase } from '../type';+import { normalizeInboxAgentMeta } from '../utils/inboxAgent';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';export class AgentModel {@@ -43,12 +44,13 @@ export class AgentModel {* the recents filter: real agents plus the inbox, excluding other virtual agents.*/rank = async (limit: number = 10): Promise<AgentRankItem[]> => {- return this.db+ const rows = await this.db.select({avatar: agents.avatar,backgroundColor: agents.backgroundColor,count: count(topics.id).as('count'),id: agents.id,+ slug: agents.slug,title: agents.title,}).from(agents)@@ -58,6 +60,8 @@ export class AgentModel {.having(({ count }) => gt(count, 0)).orderBy(desc(sql`count`)).limit(limit);++ return rows.map(({ slug, ...row }) => normalizeInboxAgentMeta(row, { slug }));};/**@@ -158,12 +162,13 @@ export class AgentModel {const { keyword, limit = 9999, offset = 0 } = params ?? {};const searchCondition = this.buildQueryAgentsWhere(keyword);- return this.db+ const rows = await this.db.select({avatar: agents.avatar,backgroundColor: agents.backgroundColor,description: agents.description,id: agents.id,+ slug: agents.slug,title: agents.title,}).from(agents)@@ -171,6 +176,8 @@ export class AgentModel {.orderBy(desc(agents.updatedAt)).limit(limit).offset(offset);++ return rows.map(({ slug, ...row }) => normalizeInboxAgentMeta(row, { slug }));};/**@@ -204,11 +211,68 @@ export class AgentModel {.from(agents).where(and(this.ownership(), inArray(agents.id, ids)));- return rows.map(({ slug, ...row }) => ({- ...row,- avatar: row.avatar || (slug === INBOX_SESSION_ID ? DEFAULT_INBOX_AVATAR : null),- title: row.title || (slug === INBOX_SESSION_ID ? 'Lobe AI' : null),- }));+ return rows.map(({ slug, ...row }) => normalizeInboxAgentMeta(row, { slug }));+ };++ /**+ * List agents bindable by the System Bot messenger picker: real agents plus+ * 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).+ */+ listMessengerBindableAgents = async (options?: {+ fallbackTitle?: string | null;+ }): Promise<+ Array<{+ avatar: string | null;+ backgroundColor: string | null;+ id: string;+ isInbox: boolean;+ title: string | null;+ }>+ > => {+ const fallbackTitle = options?.fallbackTitle ?? null;++ const rows = await this.db+ .select({+ avatar: agents.avatar,+ backgroundColor: agents.backgroundColor,+ id: agents.id,+ slug: agents.slug,+ title: agents.title,+ })+ .from(agents)+ .where(and(this.ownership(), or(ne(agents.virtual, true), eq(agents.slug, INBOX_SESSION_ID))))+ .orderBy(desc(agents.updatedAt));++ const normalized = rows+ .filter((row) => row.id)+ .map(({ slug, ...row }) => {+ const meta = normalizeInboxAgentMeta(row, { slug });+ return {+ avatar: meta.avatar,+ backgroundColor: meta.backgroundColor,+ id: meta.id,+ isInbox: slug === INBOX_SESSION_ID,+ // The inbox title is already resolved by normalizeInboxAgentMeta; any+ // other blank title falls back to the caller-provided default.+ title: meta.title?.trim() || fallbackTitle,+ };+ });++ // Pin the inbox agent to the top regardless of updatedAt β it's the+ // implicit "default" agent and should always be the first option.+ const inboxIdx = normalized.findIndex((row) => row.isInbox);+ if (inboxIdx > 0) {+ const [inbox] = normalized.splice(inboxIdx, 1);+ normalized.unshift(inbox);+ }++ return normalized;};/**@@ -235,6 +299,7 @@ export class AgentModel {*/private enrichAgentWithKnowledge = async (agent: AgentItem) => {const knowledge = await this.getAgentAssignedKnowledge(agent.id);+ const normalizedAgent = normalizeInboxAgentMeta(agent, { slug: agent.slug });// Fetch document content for enabled filesconst enabledFileIds = knowledge.files@@ -256,7 +321,7 @@ export class AgentModel {}));}- return { ...agent, ...knowledge, files };+ return { ...normalizedAgent, ...knowledge, files };};getAgentAssignedKnowledge = async (id: string) => {@@ -672,7 +737,7 @@ export class AgentModel {where: and(eq(agents.slug, slug), this.ownership()),});- if (existing) return existing;+ if (existing) return normalizeInboxAgentMeta(existing, { slug: existing.slug });// For inbox agent, it has special compatibility handling:// Historical inbox was stored as session with slug='inbox' and linked agent via agentsToSessions@@ -696,7 +761,7 @@ export class AgentModel {.where(eq(agents.id, result[0].agent.id)).returning();- return updatedAgent;+ return normalizeInboxAgentMeta(updatedAgent, { slug: updatedAgent.slug });}}@@ -733,13 +798,13 @@ export class AgentModel {.onConflictDoNothing().returning();- if (result[0]) return result[0];+ if (result[0]) return normalizeInboxAgentMeta(result[0], { slug: result[0].slug });- return (- (await this.db.query.agents.findFirst({- where: and(eq(agents.slug, slug), this.ownership()),- })) ?? null- );+ const agent = await this.db.query.agents.findFirst({+ where: and(eq(agents.slug, slug), this.ownership()),+ });++ return agent ? normalizeInboxAgentMeta(agent, { slug: agent.slug }) : null;};/**diff --git a/packages/database/src/models/agentSignal/nightlyReview.ts b/packages/database/src/models/agentSignal/nightlyReview.tsindex 4a077a2730e..058a8a9bd83 100644--- a/packages/database/src/models/agentSignal/nightlyReview.ts+++ b/packages/database/src/models/agentSignal/nightlyReview.ts@@ -16,6 +16,7 @@ import {import { agents, messagePlugins, messages, topics, users, userSettings } from '../../schemas';import type { LobeChatDatabase } from '../../type';+import { normalizeInboxAgentTitle } from '../../utils/inboxAgent';/*** Normalizes database aggregate timestamps.@@ -170,7 +171,7 @@ export class AgentSignalNightlyReviewModel {* Returns:* - Agent targets with message/topic/failure counts*/- listActiveAgentTargets = (+ listActiveAgentTargets = async (userId: string,options: ListAgentSignalNightlyReviewTargetsOptions,) => {@@ -187,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),+ slug: agents.slug,timezone: sql<string>`COALESCE(${userSettings.general}->>'timezone', 'UTC')`,title: agents.title,topicCount: countDistinct(messages.topicId),@@ -223,9 +225,14 @@ export class AgentSignalNightlyReviewModel {),),)- .groupBy(agents.id, agents.title, userSettings.general)+ .groupBy(agents.id, agents.title, agents.slug, userSettings.general).orderBy(sql`MAX(${messages.createdAt}) DESC`);- return options.limit !== undefined ? query.limit(options.limit) : query;+ const rows = await (options.limit !== undefined ? query.limit(options.limit) : query);++ return rows.map(({ slug, ...row }) => ({+ ...row,+ title: normalizeInboxAgentTitle(row.title, { slug }),+ }));};}diff --git a/packages/database/src/models/brief.ts b/packages/database/src/models/brief.tsindex cfaf7f0ca65..90610615c66 100644--- a/packages/database/src/models/brief.ts+++ b/packages/database/src/models/brief.ts@@ -4,6 +4,7 @@ import { agents } from '../schemas/agent';import type { BriefItem, NewBrief } from '../schemas/task';import { briefs, tasks } from '../schemas/task';import type { LobeChatDatabase } from '../type';+import { normalizeInboxAgentAvatar, normalizeInboxAgentTitle } from '../utils/inboxAgent';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';export interface UnresolvedBriefRow {@@ -86,11 +87,12 @@ export class BriefModel {*/async listUnresolvedEnriched(options?: { limit?: number }): Promise<UnresolvedBriefRow[]> {const { limit = 20 } = options ?? {};- return this.db+ const rows = await this.db.select({agentAvatar: agents.avatar,agentBackgroundColor: agents.backgroundColor,agentRowId: agents.id,+ agentSlug: agents.slug,agentTitle: agents.title,brief: briefs,taskStatus: tasks.status,@@ -108,6 +110,16 @@ export class BriefModel {desc(briefs.createdAt),).limit(limit);++ return rows.map(({ agentSlug, ...row }) => ({+ ...row,+ agentAvatar: normalizeInboxAgentAvatar(row.agentAvatar, {+ slug: agentSlug,+ }),+ agentTitle: normalizeInboxAgentTitle(row.agentTitle, {+ slug: agentSlug,+ }),+ }));}/**diff --git a/packages/database/src/models/chatGroup.ts b/packages/database/src/models/chatGroup.tsindex 142c61047c7..e472576d87e 100644--- a/packages/database/src/models/chatGroup.ts+++ b/packages/database/src/models/chatGroup.ts@@ -6,8 +6,9 @@ import type {NewChatGroup,NewChatGroupAgent,} from '../schemas';-import { chatGroups, chatGroupsAgents } from '../schemas';+import { agents, chatGroups, chatGroupsAgents } from '../schemas';import type { LobeChatDatabase } from '../type';+import { normalizeInboxAgentAvatar } from '../utils/inboxAgent';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';export class ChatGroupModel {@@ -24,6 +25,37 @@ export class ChatGroupModel {private ownership = () =>buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, chatGroups);+ /**+ * Get member avatar metas (avatar + backgroundColor) grouped by chatGroupId,+ * ordered by member order. Inbox members fall back to the default avatar.+ */+ getMemberAvatarsByGroupIds = async (+ groupIds: string[],+ ): Promise<Map<string, Array<{ avatar: string | null; backgroundColor: string | null }>>> => {+ const map = new Map<string, Array<{ avatar: string | null; backgroundColor: string | null }>>();+ if (groupIds.length === 0) return map;++ const rows = await this.db+ .select({+ avatar: agents.avatar,+ backgroundColor: agents.backgroundColor,+ chatGroupId: chatGroupsAgents.chatGroupId,+ slug: agents.slug,+ })+ .from(chatGroupsAgents)+ .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))+ .where(inArray(chatGroupsAgents.chatGroupId, groupIds))+ .orderBy(chatGroupsAgents.order);++ for (const { avatar, backgroundColor, chatGroupId, slug } of rows) {+ const list = map.get(chatGroupId) ?? [];+ list.push({ avatar: normalizeInboxAgentAvatar(avatar, { slug }), backgroundColor });+ map.set(chatGroupId, list);+ }++ return map;+ };+// ******* Query Methods ******* //async findById(id: string): Promise<ChatGroupItem | undefined> {diff --git a/packages/database/src/models/topicShare.ts b/packages/database/src/models/topicShare.tsindex 4266cff0f43..2d72b97a2b5 100644--- a/packages/database/src/models/topicShare.ts+++ b/packages/database/src/models/topicShare.ts@@ -4,6 +4,11 @@ import { and, asc, eq, sql } from 'drizzle-orm';import { agents, chatGroups, chatGroupsAgents, topics, topicShares } from '../schemas';import type { LobeChatDatabase } from '../type';+import {+ normalizeInboxAgentAvatar,+ normalizeInboxAgentMeta,+ normalizeInboxAgentTitle,+} from '../utils/inboxAgent';import { buildWorkspaceWhere } from '../utils/workspace';export type TopicShareData = NonNullable<@@ -153,6 +158,7 @@ export class TopicShareModel {avatar: agents.avatar,backgroundColor: agents.backgroundColor,id: agents.id,+ slug: agents.slug,title: agents.title,}).from(chatGroupsAgents)@@ -161,10 +167,21 @@ export class TopicShareModel {.orderBy(asc(chatGroupsAgents.order)).limit(4);- groupMembers = members;+ groupMembers = members.map(({ slug, ...member }) =>+ normalizeInboxAgentMeta(member, { slug }),+ );}- return { ...share, groupMembers };+ return {+ ...share,+ agentAvatar: normalizeInboxAgentAvatar(share.agentAvatar, {+ slug: share.agentSlug,+ }),+ agentTitle: normalizeInboxAgentTitle(share.agentTitle, {+ slug: share.agentSlug,+ }),+ groupMembers,+ };};/**diff --git a/packages/database/src/repositories/agentGroup/index.ts b/packages/database/src/repositories/agentGroup/index.tsindex 09859e0fd6d..223b7f041d8 100644--- a/packages/database/src/repositories/agentGroup/index.ts+++ b/packages/database/src/repositories/agentGroup/index.ts@@ -21,6 +21,7 @@ import {} from '../../schemas';import type { LobeChatDatabase } from '../../type';import { idGenerator } from '../../utils/idGenerator';+import { normalizeInboxAgentMeta } from '../../utils/inboxAgent';import { buildWorkspaceWhere } from '../../utils/workspace';interface CopyAgentGroupToWorkspaceOptions {@@ -485,6 +486,7 @@ export class AgentGroupRepository {avatar: agents.avatar,description: agents.description,id: agents.id,+ slug: agents.slug,title: agents.title,virtual: agents.virtual,})@@ -496,11 +498,16 @@ export class AgentGroupRepository {for (const agent of agentDetails) {if (agent.virtual) {+ const meta = normalizeInboxAgentMeta(+ { avatar: agent.avatar, title: agent.title },+ { slug: agent.slug },+ );+virtualAgents.push({- avatar: agent.avatar,+ avatar: meta.avatar,description: agent.description,id: agent.id,- title: agent.title,+ title: meta.title,});} else {nonVirtualAgentIds.push(agent.id);diff --git a/packages/database/src/repositories/home/index.test.ts b/packages/database/src/repositories/home/index.test.tsindex 51357f22003..4ebb696c043 100644--- a/packages/database/src/repositories/home/index.test.ts+++ b/packages/database/src/repositories/home/index.test.ts@@ -1,4 +1,5 @@// @vitest-environment node+import { DEFAULT_INBOX_AVATAR, DEFAULT_INBOX_TITLE, INBOX_SESSION_ID } from '@lobechat/const';import { beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';@@ -83,6 +84,41 @@ describe('HomeRepository', () => {});});+ it('should fallback inbox agent meta by slug', async () => {+ const [agent] = await serverDB+ .insert(agents)+ .values({+ avatar: null,+ slug: INBOX_SESSION_ID,+ title: null,+ userId,+ virtual: false,+ })+ .returning();++ const [session] = await serverDB+ .insert(sessions)+ .values({+ userId,+ })+ .returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: agent.id,+ sessionId: session.id,+ userId,+ });++ const result = await homeRepo.getSidebarAgentList();++ expect(result.ungrouped[0]).toMatchObject({+ avatar: DEFAULT_INBOX_AVATAR,+ id: agent.id,+ sessionId: session.id,+ title: DEFAULT_INBOX_TITLE,+ });+ });+it('should exclude virtual agents (like inbox)', async () => {// Create virtual agentconst [virtualAgent] = await serverDBdiff --git a/packages/database/src/repositories/home/index.ts b/packages/database/src/repositories/home/index.tsindex d4f73cab417..e5c64bfffb9 100644--- a/packages/database/src/repositories/home/index.ts+++ b/packages/database/src/repositories/home/index.ts@@ -4,18 +4,13 @@ import {type SidebarGroup,} from '@lobechat/types';import { cleanObject } from '@lobechat/utils';-import { and, desc, eq, inArray, not, sql } from 'drizzle-orm';+import { and, desc, eq, not, sql } from 'drizzle-orm';-import {- agents,- agentsToSessions,- chatGroups,- chatGroupsAgents,- sessionGroups,- sessions,-} from '../../schemas';+import { ChatGroupModel } from '../../models/chatGroup';+import { agents, agentsToSessions, chatGroups, sessionGroups, sessions } from '../../schemas';import { type LobeChatDatabase } from '../../type';import { sanitizeBm25Query } from '../../utils/bm25';+import { normalizeInboxAgentMeta } from '../../utils/inboxAgent';import { buildWorkspaceWhere } from '../../utils/workspace';// Re-export types for backward compatibility@@ -61,6 +56,7 @@ export class HomeRepository {sessionGroupId: sessions.groupId,sessionId: sessions.id,sessionPinned: sessions.pinned,+ slug: agents.slug,title: agents.title,updatedAt: agents.updatedAt,})@@ -116,6 +112,7 @@ export class HomeRepository {sessionGroupId: string | null;sessionId: string | null;sessionPinned: boolean | null;+ slug: string | null;title: string | null;updatedAt: Date;}>,@@ -140,19 +137,26 @@ export class HomeRepository {// For pinned status: agents.pinned takes priority, fallback to sessions.pinned for backward compatibility// For groupId: agents.sessionGroupId takes priority, fallback to sessions.groupId for backward compatibilityconst allItems: Array<SidebarAgentItem & { groupId: string | null }> = [- ...agentItems.map((a) => ({- avatar: a.avatar,- backgroundColor: a.backgroundColor,- description: a.description,- groupId: a.agentSessionGroupId ?? a.sessionGroupId,- heterogeneousType: a.agencyConfig?.heterogeneousProvider?.type ?? null,- id: a.id,- pinned: a.pinned ?? a.sessionPinned ?? false,- sessionId: a.sessionId,- title: a.title,- type: 'agent' as const,- updatedAt: a.updatedAt,- })),+ ...agentItems.map((a) => {+ const meta = normalizeInboxAgentMeta(+ { avatar: a.avatar, title: a.title },+ { slug: a.slug },+ );++ return {+ avatar: meta.avatar,+ backgroundColor: a.backgroundColor,+ description: a.description,+ groupId: a.agentSessionGroupId ?? a.sessionGroupId,+ heterogeneousType: a.agencyConfig?.heterogeneousProvider?.type ?? null,+ id: a.id,+ pinned: a.pinned ?? a.sessionPinned ?? false,+ sessionId: a.sessionId,+ title: meta.title,+ type: 'agent' as const,+ updatedAt: a.updatedAt,+ };+ }),...chatGroupItems.map((g) => ({// If group has custom avatar, use it (string); otherwise fallback to member avatars (array)avatar: g.avatar ? g.avatar : (memberAvatarsMap.get(g.id) ?? null),@@ -224,6 +228,7 @@ export class HomeRepository {pinned: agents.pinned,sessionId: sessions.id,sessionPinned: sessions.pinned,+ slug: agents.slug,title: agents.title,updatedAt: agents.updatedAt,})@@ -266,19 +271,24 @@ export class HomeRepository {// 3. Combine and format resultsconst results: SidebarAgentItem[] = [- ...agentResults.map((a) =>- cleanObject({- avatar: a.avatar,+ ...agentResults.map((a) => {+ const meta = normalizeInboxAgentMeta(+ { avatar: a.avatar, title: a.title },+ { slug: a.slug },+ );++ return cleanObject({+ avatar: meta.avatar,backgroundColor: a.backgroundColor,description: a.description,id: a.id,pinned: a.pinned ?? a.sessionPinned ?? false,sessionId: a.sessionId,- title: a.title,+ title: meta.title,type: 'agent' as const,updatedAt: a.updatedAt,- }),- ),+ });+ }),...chatGroupResults.map((g) =>cleanObject({avatar: g.avatar ? g.avatar : (memberAvatarsMap.get(g.id) ?? null),@@ -309,26 +319,22 @@ export class HomeRepository {if (chatGroupIds.length === 0) return memberAvatarsMap;- const memberAvatars = await this.db- .select({- avatar: agents.avatar,- backgroundColor: agents.backgroundColor,- chatGroupId: chatGroupsAgents.chatGroupId,- })- .from(chatGroupsAgents)- .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))- .where(inArray(chatGroupsAgents.chatGroupId, chatGroupIds))- .orderBy(chatGroupsAgents.order);+ const metasMap = await new ChatGroupModel(+ this.db,+ this.userId,+ this.workspaceId,+ ).getMemberAvatarsByGroupIds(chatGroupIds);- for (const member of memberAvatars) {- const existing = memberAvatarsMap.get(member.chatGroupId) || [];- if (member.avatar) {- existing.push({- avatar: member.avatar,- background: member.backgroundColor ?? undefined,- });- }- memberAvatarsMap.set(member.chatGroupId, existing);+ for (const [chatGroupId, members] of metasMap) {+ memberAvatarsMap.set(+ chatGroupId,+ members+ .filter((member) => member.avatar)+ .map((member) => ({+ avatar: member.avatar as string,+ background: member.backgroundColor ?? undefined,+ })),+ );}return memberAvatarsMap;diff --git a/packages/database/src/repositories/search/index.ts b/packages/database/src/repositories/search/index.tsindex b13ec7293a3..865fee87a22 100644--- a/packages/database/src/repositories/search/index.ts+++ b/packages/database/src/repositories/search/index.ts@@ -14,6 +14,7 @@ import {} from '../../schemas';import type { LobeChatDatabase } from '../../type';import { sanitizeBm25Query } from '../../utils/bm25';+import { normalizeInboxAgentMeta, normalizeInboxAgentTitle } from '../../utils/inboxAgent';import { buildWorkspaceWhere } from '../../utils/workspace';export type SearchResultType =@@ -418,19 +419,26 @@ export class SearchRepo {.orderBy(sql`paradedb.score(${agents.id}) DESC`).limit(limit);- return this.mapScoresToRelevance(rows).map((row) => ({- avatar: row.avatar,- backgroundColor: row.backgroundColor,- createdAt: row.createdAt,- description: row.description,- id: row.id,- relevance: row.relevance,- slug: row.slug,- tags: (row.tags as string[]) || [],- title: row.title || '',- type: 'agent' as const,- updatedAt: row.updatedAt,- }));+ return this.mapScoresToRelevance(rows).map((row) => {+ const meta = normalizeInboxAgentMeta(+ { avatar: row.avatar, title: row.title },+ { slug: row.slug },+ );++ return {+ avatar: meta.avatar,+ backgroundColor: row.backgroundColor,+ createdAt: row.createdAt,+ description: row.description,+ id: row.id,+ relevance: row.relevance,+ slug: row.slug,+ tags: (row.tags as string[]) || [],+ title: meta.title || '',+ type: 'agent' as const,+ updatedAt: row.updatedAt,+ };+ });}/**@@ -454,6 +462,7 @@ export class SearchRepo {agentBackgroundColor: agents.backgroundColor,agentId: topics.agentId,agentMatchedId: agents.id,+ agentSlug: agents.slug,agentTitle: agents.title,content: topics.content,createdAt: topics.createdAt,@@ -480,9 +489,14 @@ export class SearchRepo {.map((row) => ({agent: row.agentMatchedId? {- avatar: row.agentAvatar,+ avatar: normalizeInboxAgentMeta(+ { avatar: row.agentAvatar, title: row.agentTitle },+ { slug: row.agentSlug },+ ).avatar,backgroundColor: row.agentBackgroundColor,- title: row.agentTitle,+ title: normalizeInboxAgentTitle(row.agentTitle, {+ slug: row.agentSlug,+ }),}: null,agentId: row.agentId,@@ -513,6 +527,7 @@ export class SearchRepo {const rows = await this.db.select({agentId: messages.agentId,+ agentSlug: agents.slug,agentTitle: agents.title,content: messages.content,createdAt: messages.createdAt,@@ -541,7 +556,10 @@ export class SearchRepo {agentId: row.agentId,content: row.content || '',createdAt: row.createdAt,- description: row.agentTitle || 'General Chat',+ description:+ normalizeInboxAgentTitle(row.agentTitle, {+ slug: row.agentSlug,+ }) || 'General Chat',id: row.id,model: row.model,relevance: row.relevance,diff --git a/packages/database/src/utils/inboxAgent.ts b/packages/database/src/utils/inboxAgent.tsnew file mode 100644index 00000000000..ead4b9c2d98--- /dev/null+++ b/packages/database/src/utils/inboxAgent.ts@@ -0,0 +1,53 @@+import { DEFAULT_INBOX_AVATAR, DEFAULT_INBOX_TITLE, INBOX_SESSION_ID } from '@lobechat/const';++interface InboxAgentIdentity {+ slug?: string | null;+}++interface InboxAgentMeta {+ avatar: string | null;+ title: string | null;+}++const isBlank = (value: string | null | undefined) => !value || value.trim().length === 0;++export const isInboxAgentIdentity = ({ slug }: InboxAgentIdentity) => slug === INBOX_SESSION_ID;++export function normalizeInboxAgentTitle(+ title: string | null,+ identity: InboxAgentIdentity,+): string | null;+export function normalizeInboxAgentTitle(+ title: string | null | undefined,+ identity: InboxAgentIdentity,+): string | null | undefined;+export function normalizeInboxAgentTitle(+ title: string | null | undefined,+ identity: InboxAgentIdentity,+) {+ return isInboxAgentIdentity(identity) && isBlank(title) ? DEFAULT_INBOX_TITLE : title;+}++export function normalizeInboxAgentAvatar(+ avatar: string | null,+ identity: InboxAgentIdentity,+): string | null;+export function normalizeInboxAgentAvatar(+ avatar: string | null | undefined,+ identity: InboxAgentIdentity,+): string | null | undefined;+export function normalizeInboxAgentAvatar(+ avatar: string | null | undefined,+ identity: InboxAgentIdentity,+) {+ return isInboxAgentIdentity(identity) && isBlank(avatar) ? DEFAULT_INBOX_AVATAR : avatar;+}++export const normalizeInboxAgentMeta = <T extends InboxAgentMeta>(+ agent: T,+ identity: InboxAgentIdentity = agent as T & InboxAgentIdentity,+): T => ({+ ...agent,+ avatar: normalizeInboxAgentAvatar(agent.avatar, identity),+ title: normalizeInboxAgentTitle(agent.title, identity),+});diff --git a/packages/openapi/src/services/agent.service.ts b/packages/openapi/src/services/agent.service.tsindex 6e6c53b440a..26bf8c8aca4 100644--- a/packages/openapi/src/services/agent.service.ts+++ b/packages/openapi/src/services/agent.service.ts@@ -99,7 +99,10 @@ export class AgentService extends BaseService {// Insert into databaseconst [createdAgent] = await tx.insert(agents).values(newAgentData).returning();- this.log('info', 'agent created successfully', { id: createdAgent.id, slug: createdAgent.slug });+ this.log('info', 'agent created successfully', {+ id: createdAgent.id,+ slug: createdAgent.slug,+ });return createdAgent;});@@ -123,7 +126,9 @@ export class AgentService extends BaseService {});if (!permissionResult.isPermitted) {- throw this.createAuthorizationError(permissionResult.message || 'No permission to update this agent');+ throw this.createAuthorizationError(+ permissionResult.message || 'No permission to update this agent',+ );}return await this.db.transaction(async (tx) => {@@ -176,7 +181,10 @@ export class AgentService extends BaseService {.where(and(...whereConditions)).returning();- this.log('info', 'agent updated successfully', { id: updatedAgent.id, slug: updatedAgent.slug });+ this.log('info', 'agent updated successfully', {+ id: updatedAgent.id,+ slug: updatedAgent.slug,+ });return updatedAgent;});} catch (error) {@@ -201,7 +209,9 @@ export class AgentService extends BaseService {});if (!permissionResult.isPermitted) {- throw this.createAuthorizationError(permissionResult.message || 'No permission to delete this agent');+ throw this.createAuthorizationError(+ permissionResult.message || 'No permission to delete this agent',+ );}// Check if the Agent to be deleted exists@@ -220,7 +230,9 @@ export class AgentService extends BaseService {});if (!migrateTarget) {- throw this.createBusinessError(`Migration target agent ID ${request.migrateSessionTo} not found`);+ throw this.createBusinessError(+ `Migration target agent ID ${request.migrateSessionTo} not found`,+ );}// Migrate session associations to the target Agent@@ -262,7 +274,9 @@ export class AgentService extends BaseService {});if (!permissionResult.isPermitted) {- throw this.createAuthorizationError(permissionResult.message || 'No permission to access this agent');+ throw this.createAuthorizationError(+ permissionResult.message || 'No permission to access this agent',+ );}if (!this.userId) {