Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(agent): include the inbox and display name in agent queries (#20265)

Arvin Xu4bc6b4ff171d
diff --git a/apps/cli/src/commands/agent.test.ts b/apps/cli/src/commands/agent.test.ts
index 2b38e566866..ea36183111f 100644
--- a/apps/cli/src/commands/agent.test.ts
+++ b/apps/cli/src/commands/agent.test.ts
@@ -183,6 +183,20 @@ describe('agent command', () => {
);
});
+ it('opts the inbox into the lookup, unlike callers that leave the default', async () => {
+ mockTrpcClient.agent.queryAgents.query.mockResolvedValue([]);
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'agent', 'list']);
+
+ // `queryAgents` excludes the product-owned inbox unless a caller opts in,
+ // so `lh agent list` must ask for it explicitly β€” this is the surface the
+ // inbox is meant to appear on.
+ expect(mockTrpcClient.agent.queryAgents.query).toHaveBeenCalledWith(
+ expect.objectContaining({ includeInbox: true }),
+ );
+ });
+
it('should output JSON', async () => {
const agents = [{ id: 'a1', title: 'Test' }];
mockTrpcClient.agent.queryAgents.query.mockResolvedValue(agents);
@@ -208,6 +222,34 @@ describe('agent command', () => {
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Test Agent'));
});
+ it('should show name with the title as the supporting line', async () => {
+ mockTrpcClient.agent.getAgentConfigById.query.mockResolvedValue({
+ id: 'a1',
+ name: 'Sienna',
+ title: 'Lobe',
+ });
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'agent', 'view', 'a1']);
+
+ expect(consoleSpy).toHaveBeenNthCalledWith(1, expect.stringContaining('Sienna'));
+ expect(consoleSpy).toHaveBeenNthCalledWith(2, expect.stringContaining('Lobe'));
+ });
+
+ it('should not append an Untitled placeholder for a named agent without a title', async () => {
+ mockTrpcClient.agent.getAgentConfigById.query.mockResolvedValue({
+ id: 'a1',
+ model: 'gpt-4',
+ name: 'Alice',
+ });
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'agent', 'view', 'a1']);
+
+ expect(consoleSpy).toHaveBeenNthCalledWith(1, expect.stringContaining('Alice'));
+ expect(consoleSpy).not.toHaveBeenCalledWith(expect.stringContaining('Untitled'));
+ });
+
it('should exit when not found', async () => {
mockTrpcClient.agent.getAgentConfigById.query.mockResolvedValue(null);
diff --git a/apps/cli/src/commands/agent.ts b/apps/cli/src/commands/agent.ts
index 866d52bd13a..57ca15fa266 100644
--- a/apps/cli/src/commands/agent.ts
+++ b/apps/cli/src/commands/agent.ts
@@ -69,7 +69,16 @@ export function registerAgentCommand(program: Command) {
.action(async (options: { json?: string | boolean; keyword?: string; limit?: string }) => {
const client = await getTrpcClient();
- const input: { keyword?: string; limit?: number; offset?: number } = {};
+ // The inbox (Lobe AI) is a real assistant the user can open, and this is
+ // exactly where they look for it β€” so opt in. `queryAgents` omits the
+ // product-owned inbox for callers that do not explicitly ask for it, so
+ // that older clients and CRUD/group surfaces keep their old behavior.
+ const input: {
+ includeInbox: boolean;
+ keyword?: string;
+ limit?: number;
+ offset?: number;
+ } = { includeInbox: true };
if (options.keyword) input.keyword = options.keyword;
if (options.limit) input.limit = Number.parseInt(options.limit, 10);
@@ -87,14 +96,19 @@ export function registerAgentCommand(program: Command) {
return;
}
+ // `name` (user-facing display name) and `title` (role/identity) are separate
+ // fields and both are returned β€” collapsing them into one column hides the
+ // only handle the user knows an agent by, e.g. the inbox shows up as
+ // `Sienna` / `Lobe`. `model` is not part of the queryAgents payload, so the
+ // column that used to sit here was always empty.
const rows = items.map((a: any) => [
a.id || a.agentId || '',
- truncate(a.title || a.name || a.meta?.title || 'Untitled', 40),
+ truncate(a.name || a.meta?.name || '', 24),
+ truncate(a.title || a.meta?.title || '', 36),
truncate(a.description || a.meta?.description || '', 50),
- a.model || '',
]);
- printTable(rows, ['ID', 'TITLE', 'DESCRIPTION', 'MODEL']);
+ printTable(rows, ['ID', 'NAME', 'TITLE', 'DESCRIPTION']);
});
// ── view ──────────────────────────────────────────────
@@ -126,8 +140,15 @@ export function registerAgentCommand(program: Command) {
}
const r = result as any;
- console.log(pc.bold(r.title || r.meta?.title || 'Untitled'));
+ // Same rule as the web UI (`agentDisplayName`): the personal `name` is the
+ // primary label and a real (non-blank) title is the supporting line β€” so
+ // the inbox reads `Sienna Β· Lobe`, while a named agent without a title
+ // reads `Alice`, not `Alice Β· Untitled`.
+ const name = (r.name || r.meta?.name)?.trim();
+ const title = (r.title || r.meta?.title)?.trim();
+ console.log(pc.bold(name || title || 'Untitled'));
const meta: string[] = [];
+ if (name && title && title !== name) meta.push(title);
if (r.description || r.meta?.description) meta.push(r.description || r.meta.description);
if (r.model) meta.push(`Model: ${r.model}`);
if (r.provider) meta.push(`Provider: ${r.provider}`);
diff --git a/apps/server/src/routers/lambda/agent.ts b/apps/server/src/routers/lambda/agent.ts
index 6b43ffbbf13..84af3ea0d6a 100644
--- a/apps/server/src/routers/lambda/agent.ts
+++ b/apps/server/src/routers/lambda/agent.ts
@@ -161,14 +161,16 @@ export const agentRouter = router({
}),
/**
- * Count non-virtual agents with optional keyword filter, matching the
- * conditions of queryAgents. Lets paginated callers report real totals.
+ * Count the agents matching the conditions of queryAgents β€” other virtual
+ * rows excluded, and the inbox (Lobe AI) counted only when the caller passes
+ * `includeInbox: true`. Lets paginated callers report real totals.
*/
countAgents: agentProcedure
.input(
z
.object({
endDate: z.string().optional(),
+ includeInbox: z.boolean().optional(),
keyword: z.string().optional(),
range: z.tuple([z.string(), z.string()]).optional(),
startDate: z.string().optional(),
@@ -747,14 +749,18 @@ export const agentRouter = router({
}),
/**
- * Query non-virtual agents with optional keyword filter.
- * Returns agents with minimal info (id, title, description, avatar, backgroundColor).
+ * Query the user's agents with optional keyword filter β€” other virtual rows
+ * excluded, and the inbox (Lobe AI) included and flagged with `isInbox` only
+ * when the caller passes `includeInbox: true`.
+ * Returns agents with minimal info (id, name, title, description, avatar,
+ * backgroundColor).
* Used by AddGroupMemberModal and group-management tool to search/select agents.
*/
queryAgents: agentProcedure
.input(
z
.object({
+ includeInbox: z.boolean().optional(),
keyword: z.string().optional(),
limit: z.number().max(100).optional(),
offset: z.number().optional(),
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts
index 6d4e38d80e1..5dc8d6c1394 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts
@@ -271,7 +271,12 @@ describe('agentManagementRuntime', () => {
const runtime = createRuntime();
const result = await runtime.searchAgent({ limit: 20, source: 'user' });
- expect(mockQueryAgents).toHaveBeenCalledWith({ keyword: undefined, limit: 20, offset: 0 });
+ expect(mockQueryAgents).toHaveBeenCalledWith({
+ includeInbox: false,
+ keyword: undefined,
+ limit: 20,
+ offset: 0,
+ });
expect(result.success).toBe(true);
expect(result.content).toContain('Found 137 agents in your workspace, showing 1-20');
expect(result.content).toContain('call searchAgent with offset=20');
@@ -285,7 +290,12 @@ describe('agentManagementRuntime', () => {
const runtime = createRuntime();
const result = await runtime.searchAgent({ limit: 20, offset: 20, source: 'user' });
- expect(mockQueryAgents).toHaveBeenCalledWith({ keyword: undefined, limit: 20, offset: 20 });
+ expect(mockQueryAgents).toHaveBeenCalledWith({
+ includeInbox: false,
+ keyword: undefined,
+ limit: 20,
+ offset: 20,
+ });
expect(result.content).toContain('Found 50 agents in your workspace, showing 21-40');
expect(result.content).toContain('call searchAgent with offset=40');
expect(result.state).toMatchObject({ hasMore: true, offset: 20, totalCount: 50 });
@@ -298,13 +308,37 @@ describe('agentManagementRuntime', () => {
const runtime = createRuntime();
const result = await runtime.searchAgent({ limit: 50, source: 'user' });
- expect(mockQueryAgents).toHaveBeenCalledWith({ keyword: undefined, limit: 20, offset: 0 });
+ expect(mockQueryAgents).toHaveBeenCalledWith({
+ includeInbox: false,
+ keyword: undefined,
+ limit: 20,
+ offset: 0,
+ });
expect(result.content).toContain(
'Requested limit 50 exceeds the maximum of 20; results were capped at 20 per call.',
);
expect(result.state).toMatchObject({ hasMore: false });
});
+ it('excludes the inbox from the management search and its total', async () => {
+ // This is the CRUD surface: ids it returns can be sent to deleteAgent.
+ // The inbox is product-owned and cannot be deleted, so it must not be
+ // offered here β€” and the count has to match the list, or pagination lies.
+ mockQueryAgents.mockResolvedValue(makeAgents(1));
+ mockCountAgents.mockResolvedValue(1);
+
+ const runtime = createRuntime();
+ await runtime.searchAgent({ keyword: 'lobe', source: 'user' });
+
+ expect(mockQueryAgents).toHaveBeenCalledWith({
+ includeInbox: false,
+ keyword: 'lobe',
+ limit: 10,
+ offset: 0,
+ });
+ expect(mockCountAgents).toHaveBeenCalledWith({ includeInbox: false, keyword: 'lobe' });
+ });
+
it('returns no agents found when nothing matches', async () => {
mockQueryAgents.mockResolvedValue([]);
mockCountAgents.mockResolvedValue(0);
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/groupAgentBuilder.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/groupAgentBuilder.test.ts
index 881fedd2ee0..25f60e4e586 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/groupAgentBuilder.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/groupAgentBuilder.test.ts
@@ -14,6 +14,7 @@ const {
mockGetAgentConfigById,
mockGetGroupAgentsWithMeta,
mockGetResourceConfigAccess,
+ mockQueryAgents,
mockRemoveAgentsFromGroup,
mockSetAccessLevel,
mockUpdateAgent,
@@ -29,6 +30,7 @@ const {
mockGetAgentConfigById: vi.fn(),
mockGetGroupAgentsWithMeta: vi.fn(),
mockGetResourceConfigAccess: vi.fn(),
+ mockQueryAgents: vi.fn(),
mockRemoveAgentsFromGroup: vi.fn(),
mockSetAccessLevel: vi.fn(),
mockUpdateAgent: vi.fn(),
@@ -40,7 +42,7 @@ vi.mock('@/database/models/agent', () => ({
return {
batchCreate: mockBatchCreate,
getAgentConfigById: mockGetAgentConfigById,
- queryAgents: vi.fn(async () => []),
+ queryAgents: mockQueryAgents,
update: mockUpdateAgent,
updateConfig: vi.fn(),
};
@@ -117,6 +119,7 @@ describe('groupAgentBuilderRuntime', () => {
]);
mockGetResourceConfigAccess.mockResolvedValue('full');
mockAssertCanPerformResourceAction.mockResolvedValue(undefined);
+ mockQueryAgents.mockResolvedValue([]);
});
// The bug: gateway mode executes every builtin tool server-side, and a missing
@@ -199,6 +202,28 @@ describe('groupAgentBuilderRuntime', () => {
});
});
+ describe('searchAgent', () => {
+ it('asks the query to exclude the inbox, which can never join a group', async () => {
+ // The exclusion lives in the query: filtering the page here let a
+ // recently updated inbox spend a `limit` slot and hide an addable agent,
+ // so assert the contract instead of re-filtering a page that should no
+ // longer carry the inbox in the first place.
+ mockQueryAgents.mockResolvedValue([
+ { description: null, id: 'agt_writer', isInbox: false, title: 'Writer' },
+ ]);
+
+ const result = await createRuntime().searchAgent({ query: '' }, groupCtx);
+
+ expect(mockQueryAgents).toHaveBeenCalledWith({
+ includeInbox: false,
+ keyword: '',
+ limit: 10,
+ });
+ expect(result.success).toBe(true);
+ expect((result.state as any).agents.map((a: { id: string }) => a.id)).toEqual(['agt_writer']);
+ });
+ });
+
describe('removeAgent', () => {
it('refuses to remove the supervisor', async () => {
const result = await createRuntime().removeAgent({ agentId: 'agt_sup' }, groupCtx);
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts
index a110691d3be..847cc33006a 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts
@@ -310,9 +310,18 @@ export const agentManagementRuntime: ServerRuntimeRegistration = {
let marketTotal = 0;
if (source === 'user' || source === 'all') {
+ // This is the CRUD surface: every id it returns can be forwarded to
+ // `deleteAgent` / `updateAgent`. The inbox is product-owned and must
+ // not be deletable (see `AgentModel.delete`), so keep it out of the
+ // management search instead of letting a delete proposal reach it.
const [userAgents, total] = await Promise.all([
- agentModel.queryAgents({ keyword: params.keyword, limit, offset }),
- agentModel.countAgents({ keyword: params.keyword }),
+ agentModel.queryAgents({
+ includeInbox: false,
+ keyword: params.keyword,
+ limit,
+ offset,
+ }),
+ agentModel.countAgents({ includeInbox: false, keyword: params.keyword }),
]);
userTotal = total;
results.push(...userAgents.map((a) => ({ ...a, isMarket: false })));
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/groupAgentBuilder.ts b/apps/server/src/services/toolExecution/serverRuntimes/groupAgentBuilder.ts
index 603154a9b28..3195a9a2db6 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/groupAgentBuilder.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/groupAgentBuilder.ts
@@ -266,7 +266,15 @@ export const groupAgentBuilderRuntime: ServerRuntimeRegistration = {
const { query, limit = 10 } = params;
try {
- const results = await agentModel.queryAgents({ keyword: query, limit });
+ // A builtin can never join a group (`addAgentsToGroup` refuses it), so
+ // the inbox has to be excluded by the query itself: filtering the page
+ // afterwards lets a recently updated inbox consume a `limit` slot and
+ // hide an addable agent behind it.
+ const results = await agentModel.queryAgents({
+ includeInbox: false,
+ keyword: query,
+ limit,
+ });
const agents = results.map((agent) => ({
avatar: agent.avatar ?? undefined,
description: agent.description ?? undefined,
diff --git a/packages/agent-manager-runtime/src/AgentManagerRuntime.ts b/packages/agent-manager-runtime/src/AgentManagerRuntime.ts
index fbea4abb235..e1eebc56adf 100644
--- a/packages/agent-manager-runtime/src/AgentManagerRuntime.ts
+++ b/packages/agent-manager-runtime/src/AgentManagerRuntime.ts
@@ -430,11 +430,18 @@ export class AgentManagerRuntime {
let userTotal = 0;
let marketTotal = 0;
- // Search user's agents
+ // This is the CRUD surface: every id it returns can be forwarded to
+ // `removeAgent`/`updateAgent`, and the inbox is product-owned. Opt it out
+ // explicitly so the reserved assistant is never offered as a target here.
if (source === 'user' || source === 'all') {
const [userAgents, total] = await Promise.all([
- this.agentService.queryAgents({ keyword: params.keyword, limit, offset }),
- this.agentService.countAgents({ keyword: params.keyword }),
+ this.agentService.queryAgents({
+ includeInbox: false,
+ keyword: params.keyword,
+ limit,
+ offset,
+ }),
+ this.agentService.countAgents({ includeInbox: false, keyword: params.keyword }),
]);
userTotal = total;
diff --git a/packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.ts b/packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.ts
index 4c2d6a0c232..5c0724beb13 100644
--- a/packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.ts
+++ b/packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.ts
@@ -453,6 +453,7 @@ describe('AgentManagerRuntime', () => {
const result = await runtime.searchAgents({ limit: 20, offset: 20, source: 'user' });
expect(mockAgentService.queryAgents).toHaveBeenCalledWith({
+ includeInbox: false,
keyword: undefined,
limit: 20,
offset: 20,
@@ -477,6 +478,7 @@ describe('AgentManagerRuntime', () => {
const result = await runtime.searchAgents({ limit: 50, source: 'user' });
expect(mockAgentService.queryAgents).toHaveBeenCalledWith({
+ includeInbox: false,
keyword: undefined,
limit: 20,
offset: 0,
diff --git a/packages/agent-manager-runtime/src/types.ts b/packages/agent-manager-runtime/src/types.ts
index f0bd2f5e05e..3a0264fca00 100644
--- a/packages/agent-manager-runtime/src/types.ts
+++ b/packages/agent-manager-runtime/src/types.ts
@@ -8,13 +8,18 @@ import type { PartialDeep } from 'type-fest';
* Can be implemented by client-side or server-side services
*/
export interface IAgentService {
- countAgents: (params?: { keyword?: string }) => Promise<number>;
+ countAgents: (params?: { includeInbox?: boolean; keyword?: string }) => Promise<number>;
createAgent: (params: { config: Record<string, unknown> }) => Promise<{
agentId?: string;
}>;
duplicateAgent: (agentId: string, newTitle?: string) => Promise<{ agentId: string } | null>;
getAgentConfigById: (agentId: string) => Promise<LobeAgentConfig | null>;
- queryAgents: (params: { keyword?: string; limit?: number; offset?: number }) => Promise<
+ queryAgents: (params: {
+ includeInbox?: boolean;
+ keyword?: string;
+ limit?: number;
+ offset?: number;
+ }) => Promise<
Array<{
avatar?: string | null;
backgroundColor?: string | null;
diff --git a/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts b/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts
index 1a7b9fa8661..998081d83b3 100644
--- a/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts
@@ -77,7 +77,15 @@ export class GroupAgentBuilderExecutionRuntime {
const { query, limit = 10 } = args;
try {
- const results = await agentService.queryAgents({ keyword: query, limit });
+ // A builtin can never join a group (`addAgentsToGroup` refuses it), so the
+ // inbox has to be excluded by the query itself: filtering the page
+ // afterwards lets a recently updated inbox consume a `limit` slot and hide
+ // an addable agent behind it.
+ const results = await agentService.queryAgents({
+ includeInbox: false,
+ keyword: query,
+ limit,
+ });
const agents = results.map((agent) => ({
avatar: agent.avatar,
diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.ts
index ea6e3d2eb7e..9b01310650b 100644
--- a/packages/database/src/models/__tests__/agent.test.ts
+++ b/packages/database/src/models/__tests__/agent.test.ts
@@ -393,6 +393,112 @@ describe('AgentModel', () => {
});
});
+ describe('queryAgents', () => {
+ it('excludes the inbox by default, so callers that never ask for it keep legacy behavior', async () => {
+ await serverDB.insert(agents).values([
+ { id: 'default-inbox', slug: INBOX_SESSION_ID, userId, virtual: true },
+ { id: 'default-normal', userId },
+ { id: 'default-virtual', userId, virtual: true },
+ ]);
+
+ // The inbox is product-owned; a lookup that does not opt in must not
+ // inherit it, or older clients and CRUD/group surfaces start offering a
+ // row they cannot delete or add.
+ await expect(agentModel.queryAgents()).resolves.toHaveLength(1);
+ await expect(agentModel.countAgents()).resolves.toBe(1);
+ });
+
+ it('includes the inbox (Lobe AI) and flags it with isInbox when the caller opts in', async () => {
+ await serverDB.insert(agents).values([
+ {
+ id: 'inbox-agent',
+ name: 'Sienna',
+ slug: INBOX_SESSION_ID,
+ title: 'Lobe',
+ userId,
+ virtual: true,
+ },
+ { id: 'normal-agent', name: '三村', title: 'Architect', userId, virtual: false },
+ { id: 'group-built-agent', title: 'Group member', userId, virtual: true },
+ ]);
+
+ const result = await agentModel.queryAgents({ includeInbox: true });
+ const byId = new Map(result.map((agent) => [agent.id, agent] as const));
+
+ // The inbox is a real assistant the user talks to; the caller opted in.
+ expect(byId.get('inbox-agent')?.isInbox).toBe(true);
+ expect(byId.get('inbox-agent')?.name).toBe('Sienna');
+ expect(byId.get('inbox-agent')?.title).toBe('Lobe');
+ expect(byId.get('normal-agent')?.isInbox).toBe(false);
+ // Other virtual rows are infrastructure, not user content.
+ expect(byId.has('group-built-agent')).toBe(false);
+ });
+
+ it('matches the user-facing display name in a keyword search', async () => {
+ await serverDB.insert(agents).values([
+ { id: 'sienna-agent', name: 'Sienna', title: 'Lobe', userId },
+ { id: 'coco-agent', name: 'Coco', title: 'Codex', userId },
+ ]);
+
+ const result = await agentModel.queryAgents({ keyword: 'Sienna' });
+
+ expect(result.map((agent) => agent.id)).toEqual(['sienna-agent']);
+ });
+
+ it('matches a blank-title inbox by its default display title when the caller opts in', async () => {
+ await serverDB.insert(agents).values([
+ { id: 'blank-inbox', slug: INBOX_SESSION_ID, title: null, userId, virtual: true },
+ { id: 'normal-agent', title: 'Writer', userId },
+ ]);
+
+ const withInbox = await agentModel.queryAgents({ includeInbox: true, keyword: 'lobe' });
+ expect(withInbox.map((agent) => agent.id)).toEqual(['blank-inbox']);
+ expect(withInbox[0]?.title).toBe(DEFAULT_INBOX_TITLE);
+ await expect(agentModel.countAgents({ includeInbox: true, keyword: 'lobe' })).resolves.toBe(
+ 1,
+ );
+
+ // Without the opt-in the inbox stays out even when the keyword matches.
+ await expect(agentModel.queryAgents({ keyword: 'lobe' })).resolves.toEqual([]);
+ });
+
+ it('counts the inbox in the shared total when the caller opts in, so pagination stays honest', async () => {
+ await serverDB.insert(agents).values([
+ { id: 'inbox-agent', slug: INBOX_SESSION_ID, userId, virtual: true },
+ { id: 'normal-agent', userId },
+ { id: 'group-built-agent', userId, virtual: true },
+ ]);
+
+ await expect(agentModel.countAgents({ includeInbox: true })).resolves.toBe(2);
+ });
+
+ it('keeps the inbox out of a limited page unless the caller opts in', async () => {
+ // The addable agent is the *older* row: if the inbox were merely filtered
+ // after the page was built, `limit: 1` would return the (newer) inbox and
+ // then drop it, leaving nothing.
+ await serverDB.insert(agents).values([
+ { id: 'optin-normal', updatedAt: new Date('2024-01-01'), userId },
+ {
+ id: 'optin-inbox',
+ slug: INBOX_SESSION_ID,
+ updatedAt: new Date('2024-02-01'),
+ userId,
+ virtual: true,
+ },
+ ]);
+
+ // Default (legacy) excludes it inside the where clause, before the limit.
+ const limited = await agentModel.queryAgents({ limit: 1 });
+ expect(limited.map((agent) => agent.id)).toEqual(['optin-normal']);
+ await expect(agentModel.countAgents()).resolves.toBe(1);
+
+ // Opting in brings it back, ordering included.
+ const withInbox = await agentModel.queryAgents({ includeInbox: true, limit: 1 });
+ expect(withInbox.map((agent) => agent.id)).toEqual(['optin-inbox']);
+ await expect(agentModel.countAgents({ includeInbox: true })).resolves.toBe(2);
+ });
+ });
+
describe('getAgentConfig', () => {
it('should find agent by ID', async () => {
const agentId = 'test-agent-by-id';
@@ -1061,6 +1167,35 @@ describe('AgentModel', () => {
});
describe('delete', () => {
+ it('refuses to delete a reserved builtin (the inbox) and keeps its session', async () => {
+ // The inbox is product-owned: nothing recreates it, and its session
+ // cascades every conversation with it. A CRUD surface β€” the
+ // agent-management tool forwards ids straight to `delete` β€” must not be
+ // able to take it down.
+ const [inbox] = await serverDB
+ .insert(agents)
+ .values({ id: 'reserved-inbox', slug: INBOX_SESSION_ID, title: 'Lobe AI', userId })
+ .returning();
+ const [session] = await serverDB
+ .insert(sessions)
+ .values({ userId, type: 'agent' })
+ .returning();
+ await serverDB
+ .insert(agentsToSessions)
+ .values({ agentId: inbox.id, sessionId: session.id, userId });
+
+ await expect(agentModel.delete(inbox.id)).rejects.toThrow(
+ 'A builtin agent cannot be deleted',
+ );
+
+ expect(
+ await serverDB.query.agents.findFirst({ where: eq(agents.id, inbox.id) }),
+ ).toBeDefined();
+ expect(
+ await serverDB.query.sessions.findFirst({ where: eq(sessions.id, session.id) }),
+ ).toBeDefined();
+ });
+
it('refuses to delete an agent a pending history job still maps', async () => {
// A group copy's drain writes the TARGET agent id into `messages.agent_id`.
// Deleting that agent leaves the queue rows behind, so the drain hits a
diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.ts
index 4828ca45f59..6dd04505cf7 100644
--- a/packages/database/src/models/agent.ts
+++ b/packages/database/src/models/agent.ts
@@ -1,5 +1,9 @@
import { BUILTIN_AGENT_SLUGS, getAgentPersistConfig } from '@lobechat/builtin-agents';
-import { INBOX_SESSION_ID, isHeterogeneousAgentModelId } from '@lobechat/const';
+import {
+ DEFAULT_INBOX_TITLE,
+ INBOX_SESSION_ID,
+ isHeterogeneousAgentModelId,
+} from '@lobechat/const';
import type { AgentRankItem, AgentTopicShareSubject, LobeAgentAgencyConfig } from '@lobechat/types';
import {
DEFAULT_WORKSPACE_AGENT_SELECTION_POLICIES,
@@ -610,37 +614,80 @@ export class AgentModel {
};
/**
- * Build the where condition shared by queryAgents / countAgents:
- * non-virtual agents of the current user, with optional keyword filter.
+ * Build the where condition shared by queryAgents / countAgents: the current
+ * user's agents, with optional keyword filter.
+ *
+ * Virtual rows are infrastructure (group-built members, supervisors) and stay
+ * excluded. That includes the inbox (Lobe AI): it is the product-owned
+ * assistant, so including it is a deliberate choice every caller makes with
+ * `includeInbox: true` β€” never something a generic agent lookup inherits. The
+ * default is therefore the long-standing behavior (real, user-created agents
+ * only), so callers that never asked for the inbox β€” older clients, the
+ * CRUD/management tool runtimes, group pickers β€” keep it out instead of
+ * discovering a row they cannot delete or add.
+ *
+ * When a caller does opt in, the inbox joins the page inside the where clause
+ * rather than being filtered afterwards, so `limit` is never spent on an inbox
+ * the caller would drop.
*/
- private buildQueryAgentsWhere = (keyword?: string) => {
- // Include agents where virtual is false OR null (legacy data without virtual field)
+ private buildQueryAgentsWhere = (keyword?: string, includeInbox = false) => {
+ // Include agents where virtual is false OR null (legacy data without virtual
+ // field), plus the inbox when the caller opts into it.
const baseConditions = and(
this.ownership(),
- or(eq(agents.virtual, false), isNull(agents.virtual)),
+ includeInbox
+ ? or(eq(agents.virtual, false), isNull(agents.virtual), eq(agents.slug, INBOX_SESSION_ID))
+ : or(eq(agents.virtual, false), isNull(agents.virtual)),
);
- // Add keyword search condition if provided
- return keyword
- ? and(
- baseConditions,
- or(ilike(agents.title, `%${keyword}%`), ilike(agents.description, `%${keyword}%`)),
- )
- : baseConditions;
+ // `name` is the user-facing display name (see `agents.name`); resolving the
+ // label the UI shows is the primary way users and tools find an agent, so
+ // the keyword must match it alongside `title`/`description`.
+ if (!keyword) return baseConditions;
+
+ // An inbox with a blank title is shown as `DEFAULT_INBOX_TITLE` only after
+ // the query (see `normalizeInboxAgentMeta`), so the raw `title` column can't
+ // match it β€” match that default label here instead.
+ const matchesDefaultInboxTitle =
+ includeInbox && DEFAULT_INBOX_TITLE.toLowerCase().includes(keyword.toLowerCase());
+
+ return and(
+ baseConditions,
+ or(
+ ilike(agents.title, `%${keyword}%`),
+ ilike(agents.name, `%${keyword}%`),
+ ilike(agents.description, `%${keyword}%`),
+ matchesDefaultInboxTitle
+ ? and(
+ eq(agents.slug, INBOX_SESSION_ID),
+ or(isNull(agents.title), sql`trim(${agents.title}) = ''`),
+ )
+ : undefined,
+ ),
+ );
};
/**
- * Query non-virtual agents with optional keyword filter.
- * Returns minimal agent info (id, title, description, avatar, backgroundColor),
- * plus `userId`/`visibility` so callers can gate per-agent actions (e.g.
- * transfer is creator/primary-owner only), and a compact `heteroType` derived
- * from `agencyConfig` so callers can tell which results are heterogeneous
- * (external CLI/device) agents.
- * Excludes virtual agents (like inbox, supervisors, etc).
+ * Query the user's agents with an optional keyword filter.
+ * Returns minimal agent info (id, title, name, description, avatar,
+ * backgroundColor), plus `userId`/`visibility` so callers can gate per-agent
+ * actions (e.g. transfer is creator/primary-owner only), a compact
+ * `heteroType` derived from `agencyConfig` so callers can tell which results
+ * are heterogeneous (external CLI/device) agents, and `isInbox` so callers can
+ * recognize the product-owned inbox (Lobe AI) without re-deriving it from a
+ * slug the row shape no longer carries.
+ * Excludes virtual agents (supervisors, group-built members) and, unless the
+ * caller opts in with `includeInbox: true`, the product-owned inbox (Lobe AI).
+ * See `buildQueryAgentsWhere`.
*/
- queryAgents = async (params?: { keyword?: string; limit?: number; offset?: number }) => {
- const { keyword, limit = 9999, offset = 0 } = params ?? {};
- const searchCondition = this.buildQueryAgentsWhere(keyword);
+ queryAgents = async (params?: {
+ includeInbox?: boolean;
+ keyword?: string;
+ limit?: number;
+ offset?: number;
+ }) => {
+ const { includeInbox = false, keyword, limit = 9999, offset = 0 } = params ?? {};
+ const searchCondition = this.buildQueryAgentsWhere(keyword, includeInbox);
const rows = await this.db
.select({
@@ -662,16 +709,23 @@ export class AgentModel {
.offset(offset);
// Surface only the hetero runtime type, not the full agencyConfig payload.
- return rows.map(({ slug, agencyConfig, ...row }) =>
- normalizeInboxAgentMeta(
+ return rows.map(({ slug, agencyConfig, ...row }) => ({
+ ...normalizeInboxAgentMeta(
{ ...row, heteroType: agencyConfig?.heterogeneousProvider?.type },
{ slug },
),
- );
+ // When the caller opted in, the inbox is the only virtual row this query
+ // keeps, and `slug` is consumed above rather than returned β€” so the flag
+ // is what lets callers pin or annotate Lobe AI without re-deriving it.
+ isInbox: slug === INBOX_SESSION_ID,
+ }));
};
/**
- * Count non-virtual agents matching the same conditions as queryAgents.
+ * Count the agents matching the same conditions as queryAgents β€” the inbox is
+ * counted only when the caller opts in with `includeInbox: true`, other
+ * virtual rows always excluded β€” so the count stays a faithful total for
+ * paginated callers and for the assistants stats.
* Used to report real totals (and pagination) when queryAgents is limited.
* Accepts the same date filters as SessionModel.count so callers can compare
* current vs. prior-period totals without falling back to the legacy
@@ -679,6 +733,7 @@ export class AgentModel {
*/
countAgents = async (params?: {
endDate?: string;
+ includeInbox?: boolean;
keyword?: string;
range?: [string, string];
startDate?: string;
@@ -688,7 +743,7 @@ export class AgentModel {
.from(agents)
.where(
genWhere([
- this.buildQueryAgentsWhere(params?.keyword),
+ this.buildQueryAgentsWhere(params?.keyword, params?.includeInbox ?? false),
params?.range
? genRangeWhere(params.range, agents.createdAt, (date) => date.toDate())
: undefined,
@@ -1027,12 +1082,26 @@ export class AgentModel {
// lock-then-guard order as transferAgents. A concurrent copy enqueue
// locks the same source rows, so the guard here cannot run in the window
// where the enqueue's job row exists but is not yet committed.
- await trx
- .select({ id: agents.id })
+ const [locked] = await trx
+ .select({ id: agents.id, slug: agents.slug })
.from(agents)
.where(and(eq(agents.id, agentId), this.ownership()))
.for('update');
+ // Builtins (the inbox, the agent builders) are provisioned per user and
+ // carry `virtual` exactly like a group's own members. Deleting one takes
+ // its linked session and every conversation with it, and nothing can
+ // recreate them β€” refuse here, the same way `addAgentsToGroup` refuses to
+ // seat one. This only guards callers of `AgentModel.delete`; paths that
+ // delete `agents` rows directly (e.g. the OpenAPI `migrateSessionTo`
+ // delete) bypass it.
+ if (locked?.slug && RESERVED_AGENT_SLUGS.has(locked.slug)) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'A builtin agent cannot be deleted',
+ });
+ }
+
// The junction records every agent an unfinished job still maps, a
// copy's TARGET included β€” and a group copy's drain writes those ids into
// `messages.agent_id`. Deleting one leaves the queue rows behind, so the
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx
index 3a36f933cfd..618990d89fe 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx
@@ -124,7 +124,9 @@ const RunCreateContent: FC<RunCreateContentProps> = ({
useEffect(() => {
setLoadingAgents(true);
agentService
- .queryAgents()
+ // The inbox is added locally as `inboxAgent` just below; asking the query
+ // for it as well would offer Lobe AI twice under two different ids.
+ .queryAgents({ includeInbox: false })
.then((list) => setAgents(list as AgentOption[]))
.finally(() => setLoadingAgents(false));
}, []);
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Content.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Content.tsx
index b0e3607a8f8..b8fc7705ec6 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Content.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Content.tsx
@@ -88,7 +88,9 @@ const RunEditContent: FC<RunEditContentProps> = ({ formId, onLoadingChange, run
if (!canChangeConfig) return;
setLoadingAgents(true);
agentService
- .queryAgents()
+ // The inbox is added locally as `inboxAgent` just below; asking the query
+ // for it as well would offer Lobe AI twice under two different ids.
+ .queryAgents({ includeInbox: false })
.then((list) => setAgents(list as AgentOption[]))
.finally(() => setLoadingAgents(false));
}, [canChangeConfig]);
diff --git a/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/index.tsx b/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/index.tsx
index ca283e9a21e..8eb3285b4b1 100644
--- a/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/index.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/index.tsx
@@ -13,6 +13,7 @@ import { agentService } from '@/services/agent';
import { type AgentItemData } from './AgentItem';
import AvailableAgentList from './AvailableAgentList';
+import { selectAddableAgents } from './selectAddableAgents';
import SelectedAgentList from './SelectedAgentList';
import { useAgentSelectionStore } from './store';
@@ -48,16 +49,17 @@ const AddGroupMemberModal = memo<AddGroupMemberModalProps>(
const selectedAgentIds = useAgentSelectionStore((s) => s.selectedAgentIds);
const clearSelection = useAgentSelectionStore((s) => s.clearSelection);
- // Fetch agents from the new API (non-virtual agents only)
+ // Fetch non-virtual agents; the inbox is excluded unless a caller opts in
const { data: allAgents = [], isLoading: isLoadingAgents } = useSWR(
open ? groupKeys.queryAgents() : null,
() => agentService.queryAgents(),
);
- // Filter out existing members
- const availableAgents = useMemo<AgentItemData[]>(() => {
- return allAgents.filter((agent) => !existingMembers.includes(agent.id));
- }, [allAgents, existingMembers]);
+ // Filter out existing members and the inbox, which cannot join a group
+ const availableAgents = useMemo<AgentItemData[]>(
+ () => selectAddableAgents(allAgents, existingMembers),
+ [allAgents, existingMembers],
+ );
// Clear selection when modal closes
useEffect(() => {
diff --git a/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/selectAddableAgents.test.ts b/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/selectAddableAgents.test.ts
new file mode 100644
index 00000000000..80bbe1b4b06
--- /dev/null
+++ b/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/selectAddableAgents.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+
+import { selectAddableAgents } from './selectAddableAgents';
+
+describe('selectAddableAgents', () => {
+ it('excludes the inbox, which addAgentsToGroup refuses', () => {
+ const agents = [
+ { id: 'inbox', isInbox: true },
+ { id: 'a1', isInbox: false },
+ ];
+
+ expect(selectAddableAgents(agents, []).map((a) => a.id)).toEqual(['a1']);
+ });
+
+ it('excludes agents that are already members', () => {
+ const agents = [
+ { id: 'a1', isInbox: false },
+ { id: 'a2', isInbox: false },
+ ];
+
+ expect(selectAddableAgents(agents, ['a1']).map((a) => a.id)).toEqual(['a2']);
+ });
+});
diff --git a/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/selectAddableAgents.ts b/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/selectAddableAgents.ts
new file mode 100644
index 00000000000..fb0dfd59bfc
--- /dev/null
+++ b/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/selectAddableAgents.ts
@@ -0,0 +1,14 @@
+import { type AvailableAgentItem } from '@/services/agent';
+
+/**
+ * Agents the user may pick as new group members.
+ *
+ * `queryAgents` leaves the inbox (Lobe AI) out unless the caller opts in, and
+ * this picker does not. The `isInbox` check is a guard for that contract:
+ * `ChatGroupModel.addAgentsToGroup` refuses builtins with `BAD_REQUEST`, so an
+ * inbox that ever reached this list would turn a selection into a failed add.
+ */
+export const selectAddableAgents = <T extends Pick<AvailableAgentItem, 'id' | 'isInbox'>>(
+ agents: T[],
+ existingMemberIds: string[],
+): T[] => agents.filter((agent) => !agent.isInbox && !existingMemberIds.includes(agent.id));
diff --git a/src/services/agent.ts b/src/services/agent.ts
index 60c742bfd72..eead60bd918 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;
+ /** Product-owned inbox (Lobe AI). A builtin can never join a chat group. */
+ isInbox?: boolean;
/** Personal name; resolve the label with `agentDisplayName(item, fallback)`. */
name: string | null;
title: string | null;
@@ -289,6 +291,7 @@ class AgentService {
* Returns agents with minimal info (id, title, description, avatar, backgroundColor).
*/
queryAgents = async (params?: {
+ includeInbox?: boolean;
keyword?: string;
limit?: number;
offset?: number;
@@ -302,6 +305,7 @@ class AgentService {
*/
countAgents = async (params?: {
endDate?: string;
+ includeInbox?: boolean;
keyword?: string;
range?: [string, string];
startDate?: string;