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.

πŸ› fix(session): bridge native session contexts to agents (#21364)

Bryan4f058568ad99
diff --git a/apps/server/src/routers/lambda/__tests__/agent.test.ts b/apps/server/src/routers/lambda/__tests__/agent.test.ts
index 927e1a1c09a..e49cbfe5ae0 100644
--- a/apps/server/src/routers/lambda/__tests__/agent.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agent.test.ts
@@ -15,6 +15,11 @@ import { UserModel } from '@/database/models/user';
import { WorkspaceUserSettingsModel } from '@/database/models/workspaceUserSettings';
import { DEFAULT_RESOURCE_ACCESS_LEVELS } from '@/database/schemas';
import { AgentService } from '@/server/services/agent';
+import type * as AgentReferenceModule from '@/server/services/agent/resolveReference';
+import {
+ InboxNotProvisionedError,
+ resolveAgentReference,
+} from '@/server/services/agent/resolveReference';
import { EditLockService } from '@/server/services/editLock';
import { publishResourceEvent } from '@/server/services/resourceEvents';
import {
@@ -31,6 +36,11 @@ import { KnowledgeType } from '@/types/knowledgeBase';
import { agentRouter } from '../agent';
+vi.mock('@/server/services/agent/resolveReference', async (importOriginal) => ({
+ ...(await importOriginal<typeof AgentReferenceModule>()),
+ resolveAgentReference: vi.fn(),
+}));
+
vi.mock('@/server/services/resourceEvents', () => ({ publishResourceEvent: vi.fn() }));
vi.mock('../_helpers/workspaceAgentGuard', () => ({
getWorkspaceAgentParentGroupIds: vi.fn().mockResolvedValue([]),
@@ -140,6 +150,11 @@ describe('agentRouter', () => {
beforeEach(() => {
vi.clearAllMocks();
+ vi.mocked(resolveAgentReference).mockImplementation(async (id) => {
+ if (id === INBOX_SESSION_ID)
+ throw new TRPCError({ cause: new InboxNotProvisionedError(), code: 'NOT_FOUND' });
+ return { agentId: id, sessionId: null };
+ });
vi.mocked(assertCanPerformResourceAction).mockResolvedValue();
vi.mocked(isWorkspacePrimaryOwner).mockResolvedValue(false);
vi.mocked(getResourceMeta).mockResolvedValue({
@@ -247,7 +262,7 @@ describe('agentRouter', () => {
expect(result).toEqual(DEFAULT_AGENT_CONFIG);
});
- it('should create inbox session if user exists but no inbox session', async () => {
+ it('provisions the builtin inbox when no legacy inbox exists', async () => {
const mockUser = { id: userId };
const mockSession = { id: 'inboxSessionId' };
@@ -255,24 +270,30 @@ describe('agentRouter', () => {
sessionModelMock.findByIdOrSlug
.mockResolvedValueOnce(undefined)
.mockResolvedValueOnce(mockSession);
- agentModelMock.findBySessionId.mockResolvedValue(DEFAULT_AGENT_CONFIG);
+ agentServiceMock.getBuiltinAgent = vi.fn().mockResolvedValue(DEFAULT_AGENT_CONFIG);
const caller = agentRouter.createCaller(mockCtx);
const result = await caller.getAgentConfig({ sessionId: INBOX_SESSION_ID });
- expect(agentServiceMock.createInbox).toHaveBeenCalled();
+ expect(agentServiceMock.getBuiltinAgent).toHaveBeenCalledWith(INBOX_SESSION_ID);
+ expect(agentServiceMock.createInbox).not.toHaveBeenCalled();
expect(result).toEqual(DEFAULT_AGENT_CONFIG);
});
it('should find agent by session id if session exists', async () => {
const mockSession = { id: 'session1' };
sessionModelMock.findByIdOrSlug.mockResolvedValue(mockSession);
- agentModelMock.findBySessionId.mockResolvedValue(DEFAULT_AGENT_CONFIG);
+ agentServiceMock.getAgentConfigById = vi.fn().mockResolvedValue(DEFAULT_AGENT_CONFIG);
const caller = agentRouter.createCaller(mockCtx);
const result = await caller.getAgentConfig({ sessionId: 'session1' });
- expect(agentModelMock.findBySessionId).toHaveBeenCalledWith('session1');
+ expect(resolveAgentReference).toHaveBeenCalledWith(
+ 'session1',
+ expect.anything(),
+ userId,
+ undefined,
+ );
expect(result).toEqual(DEFAULT_AGENT_CONFIG);
});
});
diff --git a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts b/apps/server/src/routers/lambda/__tests__/aiChat.test.ts
index a3c657be151..b49c0970dad 100644
--- a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiChat.test.ts
@@ -16,6 +16,13 @@ import { aiChatRouter } from '../aiChat';
const flushAsyncTasks = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
+vi.mock('@/server/routers/lambda/_helpers/resolveContext', () => ({
+ resolveContext: vi.fn(async (input) => ({
+ ...input,
+ agentId: input.agentId ?? null,
+ sessionId: input.sessionId ?? null,
+ })),
+}));
vi.mock('@/database/models/agent');
vi.mock('@/database/models/message');
vi.mock('@/database/models/thread');
@@ -70,7 +77,6 @@ describe('aiChatRouter', () => {
return mockCreateUserAndAssistantMessages;
};
-
it('should create topic optionally, create user/assistant messages, and return payload', async () => {
const mockCreateTopic = vi.fn().mockResolvedValue({ id: 't1' });
const mockCreateMessage = vi
@@ -89,9 +95,7 @@ describe('aiChatRouter', () => {
vi.mocked(AiChatService).mockImplementation(function () {
return { getMessagesAndTopics: mockGet } as any;
});
-
const caller = aiChatRouter.createCaller(mockCtx as any);
-
const input = {
newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },
newTopic: { title: 'T', topicMessageIds: ['a', 'b'] },
@@ -99,7 +103,6 @@ describe('aiChatRouter', () => {
sessionId: 's1',
topicPageSize: 20,
} as any;
-
const res = await caller.sendMessageInServer(input);
expect(mockCreateTopic).toHaveBeenCalledWith(
@@ -155,7 +158,6 @@ describe('aiChatRouter', () => {
expect(res.topics?.items.length).toBe(1);
expect(res.topics?.total).toBe(1);
});
-
it('should forward client-minted ids to the topic and message models', async () => {
const mockCreateTopic = vi.fn().mockResolvedValue({ id: 'tpc_clientMinted1' });
const mockCreateMessage = vi
@@ -174,7 +176,6 @@ describe('aiChatRouter', () => {
vi.mocked(AiChatService).mockImplementation(function () {
return { getMessagesAndTopics: mockGet } as any;
});
-
const caller = aiChatRouter.createCaller(mockCtx as any);
await caller.sendMessageInServer({
@@ -194,7 +195,6 @@ describe('aiChatRouter', () => {
}),
);
});
-
it('should reject a malformed client-minted id before it reaches the database', async () => {
const mockCreateTopic = vi.fn().mockResolvedValue({ id: 't1' });
const mockCreateMessage = vi.fn().mockResolvedValue({ id: 'm-user' });
diff --git a/apps/server/src/routers/lambda/__tests__/integration/message.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/message.integration.test.ts
index cc2df4e0d23..e1f66146b8e 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/message.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/message.integration.test.ts
@@ -6,6 +6,8 @@ import { ChatErrorType } from '@lobechat/types';
import { and, eq, isNull } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { SessionModel } from '@/database/models/session';
+
import { messageRouter } from '../../message';
import { cleanupTestUser, createTestContext, createTestUser } from './setup';
@@ -536,14 +538,8 @@ describe('Message Router Integration Tests', () => {
sessionId: testSessionId,
});
- // Create messages for another session
- const [anotherSession] = await serverDB
- .insert(sessions)
- .values({
- userId,
- type: 'agent',
- })
- .returning();
+ // A legacy session context includes its Agent and relationship.
+ const anotherSession = await new SessionModel(serverDB, userId).create({ type: 'agent' });
await caller.createMessage({
content: 'Message in another session',
diff --git a/apps/server/src/routers/lambda/__tests__/integration/sessionAgentCompat.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/sessionAgentCompat.integration.test.ts
new file mode 100644
index 00000000000..9b3314fb692
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/integration/sessionAgentCompat.integration.test.ts
@@ -0,0 +1,858 @@
+// @vitest-environment node
+import type { LobeChatDatabase } from '@lobechat/database';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { and, eq } from 'drizzle-orm';
+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ResourcePermissionModel } from '@/database/models/resourcePermission';
+import { HomeRepository } from '@/database/repositories/home';
+import {
+ agents,
+ agentsToSessions,
+ messages,
+ sessionGroups,
+ sessions,
+ topics,
+ trashItems,
+ workspaceMembers,
+ workspaces,
+} from '@/database/schemas';
+import { resolveAgentReference } from '@/server/services/agent/resolveReference';
+import { after } from '@/server/utils/scheduleAfterResponse';
+
+import { batchResolveAgentIdFromSessions, resolveContext } from '../../_helpers/resolveContext';
+import { agentRouter } from '../../agent';
+import { aiChatRouter } from '../../aiChat';
+import { messageRouter } from '../../message';
+import { sessionRouter } from '../../session';
+import { topicRouter } from '../../topic';
+import { cleanupTestUser, createTestContext, createTestUser } from './setup';
+
+vi.hoisted(() => vi.stubEnv('FTS_SEARCH_PROVIDER', 'pg_like'));
+afterAll(() => vi.unstubAllEnvs());
+
+let db: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(() => db) }));
+vi.mock('@/server/utils/scheduleAfterResponse', () => ({ after: vi.fn() }));
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn(function () {
+ return { getFileAccessUrl: vi.fn(async () => 'mock-url') };
+ }),
+}));
+
+describe('native Session to Agent compatibility', () => {
+ let userId: string;
+ let otherUserId: string;
+ const callers = (workspaceId?: string, viewer = userId) => {
+ const ctx = { ...createTestContext(viewer), serverDB: db, workspaceId };
+ return {
+ agent: agentRouter.createCaller(ctx),
+ aiChat: aiChatRouter.createCaller(ctx),
+ message: messageRouter.createCaller(ctx),
+ session: sessionRouter.createCaller(ctx),
+ topic: topicRouter.createCaller(ctx),
+ };
+ };
+ const legacy = async (workspaceId?: string) => {
+ const [agent] = await db
+ .insert(agents)
+ .values({ userId, workspaceId, title: 'Legacy' })
+ .returning();
+ const [session] = await db
+ .insert(sessions)
+ .values({ userId, workspaceId, type: 'agent' })
+ .returning();
+ await db
+ .insert(agentsToSessions)
+ .values({ agentId: agent.id, sessionId: session.id, userId, workspaceId });
+ return { agent, session };
+ };
+ const workspace = async () => {
+ const [row] = await db
+ .insert(workspaces)
+ .values({ name: 'Compat', slug: userId, primaryOwnerId: userId })
+ .returning();
+ await db.insert(workspaceMembers).values([
+ { workspaceId: row.id, userId, role: 'owner' },
+ { workspaceId: row.id, userId: otherUserId, role: 'member' },
+ ]);
+ return row.id;
+ };
+
+ beforeEach(async () => {
+ db = await getTestDB();
+ userId = await createTestUser(db);
+ otherUserId = await createTestUser(db);
+ });
+ afterEach(async () => {
+ await cleanupTestUser(db, otherUserId);
+ await cleanupTestUser(db, userId);
+ });
+
+ it('creates a blank Agent with the native envelope and no Session or mapping rows', async () => {
+ const caller = callers();
+ const id = await caller.session.createSession({ type: 'agent', config: {}, session: {} });
+ expect(id).toMatch(/^agt_/);
+ expect(await db.query.agents.findFirst({ where: eq(agents.id, id) })).toMatchObject({
+ id,
+ userId,
+ });
+ expect(await db.query.sessions.findMany({ where: eq(sessions.userId, userId) })).toEqual([]);
+ expect(
+ await db.query.agentsToSessions.findMany({ where: eq(agentsToSessions.userId, userId) }),
+ ).toEqual([]);
+ expect(await caller.agent.getAgentConfigById({ agentId: id })).toMatchObject({ id });
+ });
+
+ it('imports market configuration and metadata while ignoring full-default and server-owned fields', async () => {
+ const payload = {
+ type: 'agent' as const,
+ config: {
+ model: 'model-market',
+ provider: 'openai',
+ params: { temperature: 0.4 },
+ systemRole: 'Market role',
+ plugins: ['search'],
+ chatConfig: { historyCount: 7 },
+ openingMessage: 'Welcome',
+ openingQuestions: ['Hi'],
+ tts: { voice: { openai: 'alloy' } },
+ title: 'Market',
+ avatar: 'avatar',
+ description: 'Description',
+ backgroundColor: '#123456',
+ tags: ['tag'],
+ identifier: 'market-identifier',
+ examples: [{ role: 'user', content: 'example' }],
+ metadata: { source: 'discover' },
+ id: 'agt_injected',
+ userId: otherUserId,
+ workspaceId: 'foreign',
+ createdAt: new Date(0),
+ updatedAt: new Date(0),
+ slug: 'inbox',
+ isDeleted: true,
+ },
+ session: {
+ id: 'ssn_injected',
+ userId: otherUserId,
+ type: 'agent',
+ pinned: true,
+ groupId: 'default',
+ createdAt: 0,
+ updatedAt: 0,
+ },
+ };
+ const id = await callers().session.createSession(payload);
+ const row = await db.query.agents.findFirst({ where: eq(agents.id, id) });
+ expect(row).toMatchObject({
+ userId,
+ workspaceId: null,
+ pinned: true,
+ sessionGroupId: null,
+ model: 'model-market',
+ provider: 'openai',
+ params: { temperature: 0.4 },
+ systemRole: 'Market role',
+ plugins: ['search'],
+ chatConfig: { historyCount: 7 },
+ openingMessage: 'Welcome',
+ openingQuestions: ['Hi'],
+ tts: payload.config.tts,
+ title: 'Market',
+ avatar: 'avatar',
+ description: 'Description',
+ backgroundColor: '#123456',
+ tags: ['tag'],
+ marketIdentifier: 'market-identifier',
+ fewShots: payload.config.examples,
+ metadata: { source: 'discover' },
+ isDeleted: null,
+ });
+ expect(row?.id).not.toBe('agt_injected');
+ expect(row?.slug).not.toBe('inbox');
+ expect(row!.createdAt.getTime()).toBeGreaterThan(0);
+ expect(await db.query.sessions.findMany({ where: eq(sessions.userId, userId) })).toEqual([]);
+ });
+
+ it('uses the same folder visibility and resource permissions as agent.createAgent', async () => {
+ const workspaceId = await workspace();
+ const [folder] = await db
+ .insert(sessionGroups)
+ .values({ name: 'Private', userId, workspaceId, visibility: 'private' })
+ .returning();
+ const caller = callers(workspaceId);
+ const id = await caller.session.createSession({
+ type: 'agent',
+ config: {},
+ session: { groupId: folder.id },
+ });
+ expect(await db.query.agents.findFirst({ where: eq(agents.id, id) })).toMatchObject({
+ sessionGroupId: folder.id,
+ visibility: 'private',
+ workspaceId,
+ });
+ await expect(
+ caller.session.createSession({
+ type: 'agent',
+ config: { visibility: 'public' },
+ session: { groupId: folder.id },
+ }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ const publicId = await caller.session.createSession({ type: 'agent', config: {}, session: {} });
+ expect(
+ await new ResourcePermissionModel(db, workspaceId).getEffectiveAccessLevel('agent', publicId),
+ ).toBe('edit');
+ await expect(
+ callers(workspaceId, otherUserId).session.createSession({
+ type: 'agent',
+ config: {},
+ session: { groupId: folder.id },
+ }),
+ ).rejects.toThrow();
+ });
+
+ it.each(['legacy', 'new'] as const)(
+ 'keeps the %s context usable for config, topics, messages, updates and touch',
+ async (kind) => {
+ const caller = callers();
+ const previous = kind === 'legacy' ? await legacy() : undefined;
+ const id =
+ previous?.session.id ??
+ (await caller.session.createSession({ type: 'agent', config: {}, session: {} }));
+ const agentId = previous?.agent.id ?? id;
+ expect(await caller.agent.getAgentConfigById({ agentId: id })).toMatchObject({ id: agentId });
+ expect(await caller.agent.getAgentConfig({ sessionId: id })).toMatchObject({ id: agentId });
+ await caller.agent.updateAgentConfig({ agentId: id, value: { title: 'Updated config' } });
+ expect(await db.query.agents.findFirst({ where: eq(agents.id, agentId) })).toMatchObject({
+ title: 'Updated config',
+ });
+ const topicId = await caller.topic.createTopic({ sessionId: id, title: 'Native topic' });
+ const result = await caller.message.createMessage({
+ sessionId: id,
+ topicId,
+ role: 'user',
+ content: 'Native message',
+ });
+ expect(result).toHaveProperty('id');
+ expect(await db.query.topics.findFirst({ where: eq(topics.id, topicId) })).toMatchObject({
+ agentId,
+ sessionId: previous?.session.id ?? null,
+ });
+ expect((await caller.topic.getTopics({ agentId: id })).items.map((row) => row.id)).toContain(
+ topicId,
+ );
+ expect(
+ (await caller.topic.getTopics({ sessionId: id })).items.map((row) => row.id),
+ ).toContain(topicId);
+ for (const context of [{ agentId: id }, { sessionId: id }]) {
+ expect(
+ (await caller.message.getMessages({ ...context, topicId })).map((row) => row.content),
+ ).toContain('Native message');
+ }
+ expect(
+ (await caller.message.getMessagesByCursor({ agentId: id, topicId })).messages.map(
+ (row) => row.content,
+ ),
+ ).toContain('Native message');
+ const send = await caller.aiChat.sendMessageInServer({
+ sessionId: id,
+ newUserMessage: { content: 'Native send' },
+ newAssistantMessage: { agentId: id, model: 'model-market', provider: 'openai' },
+ newTopic: { title: 'Send topic', topicMessageIds: [] },
+ });
+ expect(send).toHaveProperty('topicId');
+ const sent = await db.query.messages.findMany({ where: eq(messages.topicId, send.topicId!) });
+ expect(sent).toHaveLength(2);
+ expect(sent.every((row) => row.agentId === agentId)).toBe(true);
+ await db
+ .update(agents)
+ .set({ updatedAt: new Date(0) })
+ .where(eq(agents.id, agentId));
+ const before = Date.now();
+ await caller.session.updateSession({
+ id,
+ value: { updatedAt: new Date(0), groupId: undefined, pinned: undefined },
+ });
+ const touched = await db.query.agents.findFirst({ where: eq(agents.id, agentId) });
+ expect(touched!.updatedAt.getTime()).toBeGreaterThanOrEqual(before);
+ if (previous)
+ expect(
+ (await db.query.sessions.findFirst({ where: eq(sessions.id, previous.session.id) }))!
+ .updatedAt,
+ ).toEqual(previous.session.updatedAt);
+ const sidebar = await new HomeRepository(db, userId).getSidebarAgentList();
+ expect(sidebar.ungrouped[0].id).toBe(agentId);
+ if (!previous)
+ expect(
+ await db.query.agentsToSessions.findMany({ where: eq(agentsToSessions.userId, userId) }),
+ ).toEqual([]);
+ },
+ );
+
+ it('reads unmigrated legacy history immediately and isolates new Agent bulk clears from Inbox', async () => {
+ const { agent, session } = await legacy();
+ const [oldTopic] = await db
+ .insert(topics)
+ .values({ userId, sessionId: session.id, title: 'Old' })
+ .returning();
+ await db.insert(messages).values({
+ userId,
+ sessionId: session.id,
+ topicId: oldTopic.id,
+ role: 'user',
+ content: 'Old history',
+ });
+ const caller = callers();
+ expect(
+ (await caller.topic.getTopics({ agentId: session.id })).items.map((row) => row.id),
+ ).toContain(oldTopic.id);
+ expect(
+ (await caller.message.getMessages({ agentId: session.id, topicId: oldTopic.id })).map(
+ (row) => row.content,
+ ),
+ ).toContain('Old history');
+ expect(
+ (await caller.topic.searchTopics({ keywords: 'Old', sessionId: session.id })).map(
+ (row) => row.id,
+ ),
+ ).toContain(oldTopic.id);
+ const id = await caller.session.createSession({ type: 'agent', config: {}, session: {} });
+ await caller.message.createMessage({ sessionId: id, role: 'user', content: 'New context' });
+ await db.insert(messages).values({ userId, role: 'user', content: 'Inbox orphan' });
+ await caller.message.removeMessagesByAssistant({ sessionId: id });
+ expect(
+ (await db.query.messages.findMany({ where: eq(messages.userId, userId) })).map(
+ (row) => row.content,
+ ),
+ ).toEqual(expect.arrayContaining(['Inbox orphan', 'Old history']));
+ expect(await db.query.messages.findMany({ where: eq(messages.agentId, id) })).toEqual([]);
+ const newTopic = await caller.topic.createTopic({ sessionId: id, title: 'Clear me' });
+ await caller.topic.batchDeleteBySessionId({ id });
+ expect(await db.query.topics.findFirst({ where: eq(topics.id, newTopic) })).toMatchObject({
+ isDeleted: true,
+ });
+ expect(await db.query.topics.findFirst({ where: eq(topics.id, oldTopic.id) })).toMatchObject({
+ isDeleted: null,
+ });
+ expect(await resolveContext({ agentId: session.id }, db, userId)).toMatchObject({
+ agentId: agent.id,
+ sessionId: session.id,
+ });
+ });
+
+ it('fails closed for foreign, trashed, group and multi-agent contexts', async () => {
+ const { agent, session } = await legacy();
+ const caller = callers();
+ await expect(
+ callers(undefined, otherUserId).agent.getAgentConfigById({ agentId: session.id }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ const workspaceId = await workspace();
+ await expect(
+ callers(workspaceId).agent.getAgentConfigById({ agentId: agent.id }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ const [otherAgent] = await db.insert(agents).values({ userId }).returning();
+ expect(
+ await resolveContext({ agentId: otherAgent.id, sessionId: session.id }, db, userId),
+ ).toMatchObject({ agentId: otherAgent.id, sessionId: null });
+ await db
+ .insert(agentsToSessions)
+ .values({ agentId: otherAgent.id, sessionId: session.id, userId });
+ await expect(caller.agent.getAgentConfigById({ agentId: session.id })).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ });
+ await expect(caller.session.updateSession({ id: session.id, value: {} })).rejects.toMatchObject(
+ { code: 'BAD_REQUEST' },
+ );
+ await db.update(sessions).set({ type: 'group' }).where(eq(sessions.id, session.id));
+ await db.delete(agentsToSessions).where(eq(agentsToSessions.agentId, otherAgent.id));
+ await expect(resolveAgentReference(session.id, db, userId)).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ });
+ expect(await batchResolveAgentIdFromSessions([session.id, 'ssn_missing'], db, userId)).toEqual(
+ new Map(),
+ );
+ await db.update(sessions).set({ type: 'agent' }).where(eq(sessions.id, session.id));
+ await db.update(agents).set({ isDeleted: true }).where(eq(agents.id, agent.id));
+ for (const id of [session.id, agent.id]) {
+ await expect(caller.agent.getAgentConfigById({ agentId: id })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ await expect(caller.session.updateSession({ id, value: {} })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ }
+ });
+
+ it('keeps persisted nonstandard Agent ids usable without treating unknown ids as authorized', async () => {
+ const [agent] = await db
+ .insert(agents)
+ .values({ id: `agent_imported_${userId}`, userId, title: 'Imported' })
+ .returning();
+ expect(await callers().agent.getAgentConfigById({ agentId: agent.id })).toMatchObject({
+ id: agent.id,
+ });
+ await callers().agent.updateAgentConfig({ agentId: agent.id, value: { title: 'Renamed' } });
+ expect(await db.query.agents.findFirst({ where: eq(agents.id, agent.id) })).toMatchObject({
+ title: 'Renamed',
+ });
+ await expect(
+ callers(undefined, otherUserId).agent.getAgentConfigById({ agentId: agent.id }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ await expect(resolveAgentReference('agent_missing', db, userId)).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ await db.update(agents).set({ isDeleted: true }).where(eq(agents.id, agent.id));
+ await expect(callers().agent.getAgentConfigById({ agentId: agent.id })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ });
+
+ it.each(['agent', 'session'] as const)(
+ 'clears delegated replies inside an authorized concrete topic through %s',
+ async (context) => {
+ const { agent: parent, session } = await legacy();
+ const [callee] = await db.insert(agents).values({ userId }).returning();
+ const [topic, otherTopic, visitorTopic] = await db
+ .insert(topics)
+ .values([
+ { userId, agentId: parent.id },
+ { userId, agentId: parent.id },
+ { userId, agentId: parent.id, senderId: 'visitor' },
+ ])
+ .returning();
+ const target = await db
+ .insert(messages)
+ .values([
+ { userId, agentId: parent.id, topicId: topic.id, role: 'user', content: 'Parent turn' },
+ {
+ userId,
+ agentId: callee.id,
+ topicId: topic.id,
+ role: 'assistant',
+ content: 'Delegated reply',
+ },
+ {
+ userId,
+ sessionId: session.id,
+ topicId: topic.id,
+ role: 'user',
+ content: 'Legacy turn',
+ },
+ ])
+ .returning();
+ const protectedRows = await db
+ .insert(messages)
+ .values([
+ {
+ userId,
+ agentId: callee.id,
+ topicId: otherTopic.id,
+ role: 'assistant',
+ content: 'Other topic',
+ },
+ { userId, agentId: callee.id, role: 'assistant', content: 'Default callee' },
+ { userId: otherUserId, topicId: topic.id, role: 'user', content: 'Foreign' },
+ {
+ userId,
+ agentId: parent.id,
+ topicId: visitorTopic.id,
+ role: 'assistant',
+ content: 'Visitor',
+ },
+ ])
+ .returning();
+ const id = context === 'agent' ? parent.id : session.id;
+ const input = { agentId: id, topicId: topic.id };
+ expect((await callers().message.getMessages(input)).map((row) => row.id).sort()).toEqual(
+ target.map((row) => row.id).sort(),
+ );
+ await callers().message.removeMessagesByAssistant(input);
+ expect(await callers().message.getMessages(input)).toEqual([]);
+ for (const row of target)
+ expect(
+ await db.query.messages.findFirst({ where: eq(messages.id, row.id) }),
+ ).toBeUndefined();
+ await expect(
+ callers().message.removeMessagesByAssistant({ agentId: id, topicId: visitorTopic.id }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ await callers().message.removeMessagesByAssistant({ agentId: id });
+ for (const row of protectedRows)
+ expect(await db.query.messages.findFirst({ where: eq(messages.id, row.id) })).toEqual(row);
+ },
+ );
+
+ it.each(['inbox', 'ssn_inbox', 'agent', 'session'] as const)(
+ 'trashes unmigrated Inbox orphan topics through %s before background migration',
+ async (context) => {
+ const [inbox, other] = await db
+ .insert(agents)
+ .values([{ userId, slug: 'inbox' }, { userId }])
+ .returning();
+ let sessionId: string | undefined;
+ if (context === 'session') {
+ const [session] = await db
+ .insert(sessions)
+ .values({ userId, slug: 'inbox', type: 'agent' })
+ .returning();
+ sessionId = session.id;
+ await db.insert(agentsToSessions).values({ userId, agentId: inbox.id, sessionId });
+ }
+ const workspaceId = await workspace();
+ const targets = await db
+ .insert(topics)
+ .values([
+ { userId, agentId: inbox.id },
+ { userId },
+ ...(sessionId ? [{ userId, sessionId }] : []),
+ ])
+ .returning();
+ const protectedRows = await db
+ .insert(topics)
+ .values([
+ { userId, agentId: other.id },
+ { userId: otherUserId },
+ { userId, workspaceId },
+ { userId, senderId: 'visitor' },
+ { userId, isDeleted: true },
+ ])
+ .returning();
+ const [message] = await db
+ .insert(messages)
+ .values({ userId, topicId: targets[1].id, role: 'user', content: 'Keep until purge' })
+ .returning();
+ const id = context === 'agent' ? inbox.id : context === 'session' ? sessionId! : context;
+ // No listing/migration is needed for an effective bulk delete.
+ await callers().topic.batchDeleteBySessionId(context === 'agent' ? { agentId: id } : { id });
+ for (const row of targets)
+ expect(await db.query.topics.findFirst({ where: eq(topics.id, row.id) })).toMatchObject({
+ isDeleted: true,
+ });
+ for (const row of protectedRows)
+ expect(await db.query.topics.findFirst({ where: eq(topics.id, row.id) })).toEqual(row);
+ expect(await db.query.messages.findFirst({ where: eq(messages.id, message.id) })).toEqual(
+ message,
+ );
+ const registry = await db.query.trashItems.findMany({ where: eq(trashItems.userId, userId) });
+ expect(registry.map((row) => row.resourceId).sort()).toEqual(
+ targets.map((row) => row.id).sort(),
+ );
+ },
+ );
+
+ it('trashes unmigrated Session topics together with Agent topics without adopting another Agent', async () => {
+ const { agent, session } = await legacy();
+ const [other] = await db.insert(agents).values({ userId }).returning();
+ const rows = await db
+ .insert(topics)
+ .values([
+ { userId, sessionId: session.id, title: 'Unmigrated' },
+ { userId, agentId: agent.id, title: 'Canonical' },
+ { userId, agentId: other.id, sessionId: session.id, title: 'Another Agent' },
+ { userId, title: 'Inbox' },
+ ])
+ .returning();
+ await callers().topic.batchDeleteBySessionId({ id: session.id });
+ const actual = await db.query.topics.findMany({ where: eq(topics.userId, userId) });
+ expect(
+ actual
+ .filter((row) => row.isDeleted)
+ .map((row) => row.id)
+ .sort(),
+ ).toEqual(
+ rows
+ .slice(0, 2)
+ .map((row) => row.id)
+ .sort(),
+ );
+ });
+
+ it.each(['inbox', 'ssn_inbox', 'agent', 'session'] as const)(
+ 'lists all three Inbox topic shapes through %s without trusting the client flag',
+ async (context) => {
+ const { agent: inbox, session } = await legacy();
+ await db.update(agents).set({ slug: 'inbox' }).where(eq(agents.id, inbox.id));
+ await db.update(sessions).set({ slug: 'inbox' }).where(eq(sessions.id, session.id));
+ const { agent: other } = await legacy();
+ const workspaceId = await workspace();
+ const visible = await db
+ .insert(topics)
+ .values([
+ { userId, agentId: inbox.id, title: 'Current Inbox' },
+ { userId, sessionId: session.id, title: 'Session Inbox' },
+ { userId, title: 'Orphan Inbox' },
+ ])
+ .returning();
+ const excluded = await db
+ .insert(topics)
+ .values([
+ { userId, agentId: other.id, title: 'Other Agent' },
+ { userId: otherUserId, title: 'Foreign orphan' },
+ { userId, workspaceId, title: 'Workspace orphan' },
+ { userId, isDeleted: true, title: 'Trashed orphan' },
+ ])
+ .returning();
+ const caller = callers().topic;
+ const id = context === 'agent' ? inbox.id : context === 'session' ? session.id : context;
+ for (const isInbox of [undefined, false, true]) {
+ vi.mocked(after).mockClear();
+ const input = { sessionId: id, ...(isInbox === undefined ? {} : { isInbox }) };
+ const result = await caller.getTopics(input);
+ expect(result.total).toBe(3);
+ expect(result.items.map((row) => row.id).sort()).toEqual(
+ visible.map((row) => row.id).sort(),
+ );
+ // The immediate response must include history before deferred migration runs.
+ expect(
+ (await db.query.topics.findFirst({ where: eq(topics.id, visible[2].id) }))?.agentId,
+ ).toBeNull();
+ }
+ vi.mocked(after).mockClear();
+ await caller.getTopics({ sessionId: id });
+ const migration = vi.mocked(after).mock.calls.at(-1)?.[0];
+ if (typeof migration !== 'function') throw new Error('Missing deferred migration');
+ await migration();
+ expect(
+ (await db.query.topics.findFirst({ where: eq(topics.id, visible[2].id) }))?.agentId,
+ ).toBe(inbox.id);
+ expect(
+ (await db.query.topics.findFirst({ where: eq(topics.id, visible[1].id) }))?.agentId,
+ ).toBe(inbox.id);
+ const protectedRows = await db.query.topics.findMany({
+ where: eq(topics.userId, otherUserId),
+ });
+ expect(protectedRows.map((row) => row.agentId)).toEqual([null]);
+ expect(
+ (await db.query.topics.findFirst({ where: eq(topics.id, excluded[2].id) }))?.agentId,
+ ).toBeNull();
+ },
+ );
+
+ it('lists and migrates orphan Inbox topics when no Session relationship exists', async () => {
+ const [inbox] = await db.insert(agents).values({ userId, slug: 'inbox' }).returning();
+ const [orphan] = await db
+ .insert(topics)
+ .values({ userId, title: 'Inbox without Session' })
+ .returning();
+ vi.mocked(after).mockClear();
+ const result = await callers().topic.getTopics({ agentId: inbox.id, isInbox: false });
+ expect(result.items.map((row) => row.id)).toEqual([orphan.id]);
+ const migration = vi.mocked(after).mock.calls.at(-1)?.[0];
+ if (typeof migration !== 'function') throw new Error('Missing deferred migration');
+ await migration();
+ expect((await db.query.topics.findFirst({ where: eq(topics.id, orphan.id) }))?.agentId).toBe(
+ inbox.id,
+ );
+ });
+
+ it('does not let a normal Agent adopt Inbox orphans with a forged isInbox flag', async () => {
+ const { agent, session } = await legacy();
+ await db.insert(agents).values({ userId, slug: 'inbox' });
+ const [orphan] = await db.insert(topics).values({ userId, title: 'Inbox only' }).returning();
+ const [own] = await db
+ .insert(topics)
+ .values({ userId, sessionId: session.id, title: 'Own' })
+ .returning();
+ vi.mocked(after).mockClear();
+ const result = await callers().topic.getTopics({ agentId: agent.id, isInbox: true });
+ expect(result.items.map((row) => row.id)).toEqual([own.id]);
+ expect(result.total).toBe(1);
+ const migration = vi.mocked(after).mock.calls.at(-1)?.[0];
+ if (typeof migration !== 'function') throw new Error('Missing deferred migration');
+ await migration();
+ expect(
+ (await db.query.topics.findFirst({ where: eq(topics.id, orphan.id) }))?.agentId,
+ ).toBeNull();
+ });
+
+ it.each(['inbox', 'ssn_inbox', 'agent'] as const)(
+ 'reads and clears %s Inbox history without touching standalone or foreign messages',
+ async (context) => {
+ const [inbox] = await db.insert(agents).values({ userId, slug: 'inbox' }).returning();
+ const [other] = await db.insert(agents).values({ userId }).returning();
+ await db.insert(messages).values([
+ { userId, role: 'user', content: 'Orphan Inbox' },
+ { userId, agentId: inbox.id, role: 'user', content: 'Current Inbox' },
+ { userId, agentId: other.id, role: 'user', content: 'Standalone' },
+ { userId: otherUserId, role: 'user', content: 'Foreign Inbox' },
+ ]);
+ const id = context === 'agent' ? inbox.id : context;
+ expect(
+ (await callers().message.getMessages({ sessionId: id })).map((row) => row.content).sort(),
+ ).toEqual(['Current Inbox', 'Orphan Inbox']);
+ expect(
+ (await callers().message.getMessages({ agentId: other.id })).map((row) => row.content),
+ ).toEqual(['Standalone']);
+ await callers().message.removeMessagesByAssistant({ sessionId: id });
+ expect(await callers().message.getMessages({ sessionId: id })).toEqual([]);
+ expect(
+ (await db.query.messages.findMany({ where: eq(messages.userId, userId) })).map(
+ (row) => row.content,
+ ),
+ ).toEqual(['Standalone']);
+ expect(
+ (await db.query.messages.findMany({ where: eq(messages.userId, otherUserId) })).map(
+ (row) => row.content,
+ ),
+ ).toEqual(['Foreign Inbox']);
+ },
+ );
+
+ it.each(['inbox', 'ssn_inbox', 'agent', 'session'] as const)(
+ 'clears %s Inbox topic history while checking the parent topic',
+ async (context) => {
+ const { agent: inbox, session } = await legacy();
+ await db.update(agents).set({ slug: 'inbox' }).where(eq(agents.id, inbox.id));
+ await db.update(sessions).set({ slug: 'inbox' }).where(eq(sessions.id, session.id));
+ const [other] = await db.insert(agents).values({ userId }).returning();
+ const [otherTopic] = await db
+ .insert(topics)
+ .values({ userId, agentId: other.id })
+ .returning();
+ const guards = await db
+ .insert(messages)
+ .values([
+ { userId, role: 'user', content: 'Default Inbox' },
+ { userId, topicId: otherTopic.id, role: 'user', content: 'Other Agent topic' },
+ ])
+ .returning();
+ const id = context === 'agent' ? inbox.id : context === 'session' ? session.id : context;
+ const caller = callers();
+ for (const parent of ['unassigned', 'agent', 'session'] as const) {
+ const [topic] = await db
+ .insert(topics)
+ .values({
+ userId,
+ agentId: parent === 'agent' ? inbox.id : null,
+ sessionId: parent === 'session' ? session.id : null,
+ })
+ .returning();
+ const targets = await db
+ .insert(messages)
+ .values([
+ { userId, topicId: topic.id, role: 'user', content: 'Orphan topic history' },
+ {
+ userId,
+ agentId: inbox.id,
+ topicId: topic.id,
+ role: 'user',
+ content: 'Current topic',
+ },
+ ])
+ .returning();
+ const [foreign] = await db
+ .insert(messages)
+ .values({
+ userId: otherUserId,
+ topicId: topic.id,
+ role: 'user',
+ content: 'Foreign topic history',
+ })
+ .returning();
+ expect(
+ (await caller.message.getMessages({ sessionId: id, topicId: topic.id }))
+ .map((row) => row.id)
+ .sort(),
+ ).toEqual(targets.map((row) => row.id).sort());
+ await db.update(topics).set({ isDeleted: true }).where(eq(topics.id, topic.id));
+ await caller.message.removeMessagesByAssistant({ sessionId: id, topicId: topic.id });
+ for (const target of targets) {
+ expect(await db.query.messages.findFirst({ where: eq(messages.id, target.id) })).toEqual(
+ target,
+ );
+ }
+ await db.update(topics).set({ isDeleted: null }).where(eq(topics.id, topic.id));
+ await caller.message.removeMessagesByAssistant({ sessionId: id, topicId: topic.id });
+ expect(await caller.message.getMessages({ sessionId: id, topicId: topic.id })).toEqual([]);
+ expect(await db.query.messages.findFirst({ where: eq(messages.id, foreign.id) })).toEqual(
+ foreign,
+ );
+ }
+ for (const guard of guards) {
+ expect(await db.query.messages.findFirst({ where: eq(messages.id, guard.id) })).toEqual(
+ guard,
+ );
+ }
+ },
+ );
+
+ it('passes the canonical id to config redaction and denies use-only operations at view access', async () => {
+ const workspaceId = await workspace();
+ const { agent, session } = await legacy(workspaceId);
+ await db
+ .update(agents)
+ .set({ systemRole: 'Owner secret', title: 'Profile' })
+ .where(eq(agents.id, agent.id));
+ await new ResourcePermissionModel(db, workspaceId).setAccessLevel(
+ 'agent',
+ agent.id,
+ 'view',
+ userId,
+ );
+ const [topic] = await db
+ .insert(topics)
+ .values({ userId, workspaceId, agentId: agent.id })
+ .returning();
+ const [allowed] = await db
+ .insert(agents)
+ .values({ userId: otherUserId, workspaceId })
+ .returning();
+ const member = callers(workspaceId, otherUserId);
+ await expect(
+ member.message.removeMessagesByAssistant({ agentId: allowed.id, topicId: topic.id }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ const config = await member.agent.getAgentConfigById({ agentId: session.id });
+ expect(config).toMatchObject({ id: agent.id, title: 'Profile' });
+ expect(config).not.toHaveProperty('systemRole');
+ await expect(
+ member.agent.updateAgentConfig({ agentId: session.id, value: { title: 'Stolen' } }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ await expect(member.session.updateSession({ id: session.id, value: {} })).rejects.toMatchObject(
+ { code: 'FORBIDDEN' },
+ );
+ await expect(
+ member.message.createMessage({ sessionId: session.id, role: 'user', content: 'Forbidden' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(
+ await db.query.messages.findMany({
+ where: and(eq(messages.agentId, agent.id), eq(messages.userId, otherUserId)),
+ }),
+ ).toEqual([]);
+ });
+
+ it('never reprovisions a trashed or private Inbox through the legacy config fallback', async () => {
+ const workspaceId = await workspace();
+ const { agent, session } = await legacy(workspaceId);
+ await db.update(sessions).set({ slug: 'inbox' }).where(eq(sessions.id, session.id));
+ await db.update(agents).set({ visibility: 'private' }).where(eq(agents.id, agent.id));
+ await expect(
+ callers(workspaceId, otherUserId).agent.getAgentConfig({ sessionId: 'inbox' }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ await db.update(agents).set({ isDeleted: true }).where(eq(agents.id, agent.id));
+ await expect(
+ callers(workspaceId).agent.getAgentConfig({ sessionId: 'inbox' }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(
+ await db.query.agents.findMany({ where: eq(agents.workspaceId, workspaceId) }),
+ ).toHaveLength(1);
+ expect(await db.query.agents.findFirst({ where: eq(agents.id, agent.id) })).toMatchObject({
+ isDeleted: true,
+ });
+ });
+
+ it('resolves explicit Inbox aliases without creating Session rows and rejects metadata writes through touch', async () => {
+ const [inbox] = await db.insert(agents).values({ userId, slug: 'inbox' }).returning();
+ for (const id of ['inbox', 'ssn_inbox'])
+ expect(await resolveAgentReference(id, db, userId)).toEqual({
+ agentId: inbox.id,
+ sessionId: null,
+ });
+ expect(await callers().agent.getAgentConfig({ sessionId: 'inbox' })).toMatchObject({
+ id: inbox.id,
+ });
+ await expect(
+ callers().session.updateSession({ id: inbox.id, value: { pinned: true } as never }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect(await db.query.sessions.findMany({ where: eq(sessions.userId, userId) })).toEqual([]);
+ });
+});
diff --git a/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.ts
index 63c7579cda1..25639a6cbf2 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.ts
@@ -284,6 +284,16 @@ describe('Topic Router Integration Tests', () => {
})
.returning();
+ // A native agent Session has a real relationship. An unlinked shell
+ // cannot serve as an Agent alias.
+ const { agentsToSessions } = await import('@/database/schemas');
+ const anotherAgentId = await createTestAgent(serverDB, userId);
+ await serverDB.insert(agentsToSessions).values({
+ agentId: anotherAgentId,
+ sessionId: anotherSession.id,
+ userId,
+ });
+
const result = await caller.batchCreateTopics([
{ title: 'Topic with agentId', agentId: testAgentId },
{ title: 'Topic with sessionId', sessionId: anotherSession.id },
diff --git a/apps/server/src/routers/lambda/__tests__/shareVisitorEntryGuard.router.test.ts b/apps/server/src/routers/lambda/__tests__/shareVisitorEntryGuard.router.test.ts
index c1326089f4a..6ea5d409244 100644
--- a/apps/server/src/routers/lambda/__tests__/shareVisitorEntryGuard.router.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/shareVisitorEntryGuard.router.test.ts
@@ -116,10 +116,14 @@ vi.mock('@/server/services/file', () => ({
}),
}));
-// Topic creation canonicalizes agent/session through the DB; the guard under
+// Creation canonicalizes agent/session through the DB; the guard under
// test runs after that step, so short-circuit it.
vi.mock('../_helpers/resolveContext', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
+ resolveContext: vi.fn(async (input: { agentId?: string; topicId?: string }) => ({
+ ...input,
+ sessionId: 'session-1',
+ })),
resolveContextWithAgentId: vi.fn(async (input: { agentId?: string }) => ({
agentId: input.agentId,
sessionId: 'session-1',
diff --git a/apps/server/src/routers/lambda/_helpers/messagesByCursor.ts b/apps/server/src/routers/lambda/_helpers/messagesByCursor.ts
index 48e9afaf68d..51ac7d947b3 100644
--- a/apps/server/src/routers/lambda/_helpers/messagesByCursor.ts
+++ b/apps/server/src/routers/lambda/_helpers/messagesByCursor.ts
@@ -7,8 +7,12 @@ import { TopicShareModel } from '@/database/models/topicShare';
import type { LobeChatDatabase } from '@/database/type';
import { FileService } from '@/server/services/file';
-import { assertCanUseTopicTargets } from './conversationResourceGuard';
+import {
+ assertCanUseConversationTargets,
+ assertCanUseTopicTargets,
+} from './conversationResourceGuard';
import { projectSharedTopicMessages } from './projectSharedTopicMessages';
+import { resolveContext } from './resolveContext';
/**
* Upper bound on rounds per `getMessagesByCursor` page. The scan itself is bounded
@@ -121,8 +125,18 @@ export const readMessagesByCursor = async (
const messageModel = new MessageModel(ctx.serverDB, ctx.userId, wsId);
const fileService = new FileService(ctx.serverDB, ctx.userId, wsId);
+ const resolved = await resolveContext(
+ { ...queryParams, agentId: queryParams.agentId ?? undefined },
+ ctx.serverDB,
+ ctx.userId,
+ wsId,
+ );
+ await assertCanUseConversationTargets(
+ { db: ctx.serverDB, userId: ctx.userId, workspaceId: wsId },
+ [resolved],
+ );
const page = await messageModel.queryTopicMessagesByCursor(
- { ...queryParams, direction, topicId },
+ { ...queryParams, ...resolved, direction, topicId },
{
postProcessUrl: (path, file) => fileService.getFileAccessUrl({ id: file.id, url: path }),
},
diff --git a/apps/server/src/routers/lambda/_helpers/resolveContext.test.ts b/apps/server/src/routers/lambda/_helpers/resolveContext.test.ts
deleted file mode 100644
index 81f86e097be..00000000000
--- a/apps/server/src/routers/lambda/_helpers/resolveContext.test.ts
+++ /dev/null
@@ -1,352 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import {
- batchResolveAgentIdFromSessions,
- resolveAgentIdFromSession,
- resolveContext,
- resolveContextWithAgentId,
-} from './resolveContext';
-
-const { mockBuildWorkspaceWhere } = vi.hoisted(() => ({
- mockBuildWorkspaceWhere: vi.fn(function () {
- return 'workspace-where';
- }),
-}));
-
-// Mock the database module
-vi.mock('@/database/schemas', () => ({
- agentsToSessions: {
- agentId: 'agent_id',
- sessionId: 'session_id',
- userId: 'user_id',
- workspaceId: 'workspace_id',
- },
-}));
-
-vi.mock('@/database/utils/workspace', () => ({
- buildWorkspaceWhere: mockBuildWorkspaceWhere,
-}));
-
-describe('resolveContext', () => {
- const mockUserId = 'user-1';
-
- // Helper to create a mock database
- const createMockDb = (queryResult: any[] = []) => {
- const mockLimit = vi.fn().mockResolvedValue(queryResult);
- const mockWhere = vi.fn().mockReturnValue({ limit: mockLimit });
- const mockFrom = vi.fn().mockReturnValue({ where: mockWhere });
- const mockSelect = vi.fn().mockReturnValue({ from: mockFrom });
-
- return {
- select: mockSelect,
- _mocks: { mockSelect, mockFrom, mockWhere, mockLimit },
- } as any;
- };
-
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- describe('resolveContext', () => {
- it('should return sessionId when only sessionId is provided', async () => {
- const mockDb = createMockDb([]);
-
- const result = await resolveContext(
- { sessionId: 'session-1', topicId: 'topic-1' },
- mockDb,
- mockUserId,
- );
-
- expect(result).toEqual({
- agentId: null,
- groupId: null,
- sessionId: 'session-1',
- threadId: null,
- topicId: 'topic-1',
- });
- // Should not query database when no agentId
- expect(mockDb.select).not.toHaveBeenCalled();
- });
-
- it('should resolve agentId to sessionId when agentId is provided', async () => {
- const mockDb = createMockDb([{ sessionId: 'resolved-session-1' }]);
-
- const result = await resolveContext({ agentId: 'agent-1' }, mockDb, mockUserId);
-
- expect(result.sessionId).toBe('resolved-session-1');
- expect(mockDb.select).toHaveBeenCalled();
- });
-
- it('should scope agentId resolution by workspaceId when provided', async () => {
- const mockDb = createMockDb([{ sessionId: 'workspace-session-1' }]);
-
- const result = await resolveContext({ agentId: 'agent-1' }, mockDb, mockUserId, 'ws-1');
-
- expect(result.sessionId).toBe('workspace-session-1');
- expect(mockBuildWorkspaceWhere).toHaveBeenCalledWith(
- { userId: mockUserId, workspaceId: 'ws-1' },
- expect.objectContaining({ workspaceId: 'workspace_id' }),
- );
- });
-
- it('should prefer agentId over sessionId when both are provided', async () => {
- const mockDb = createMockDb([{ sessionId: 'resolved-from-agent' }]);
-
- const result = await resolveContext(
- { agentId: 'agent-1', sessionId: 'original-session' },
- mockDb,
- mockUserId,
- );
-
- // Should use the sessionId resolved from agentId, not the provided sessionId
- expect(result.sessionId).toBe('resolved-from-agent');
- });
-
- it('should return null sessionId when agentId is not found in database', async () => {
- const mockDb = createMockDb([]); // Empty result
-
- const result = await resolveContext({ agentId: 'non-existent-agent' }, mockDb, mockUserId);
-
- // When agentId doesn't exist and no sessionId provided, should return null
- expect(result.sessionId).toBeNull();
- });
-
- it('should fall back to provided sessionId when agentId is not found', async () => {
- const mockDb = createMockDb([]); // Empty result - agentId not found
-
- const result = await resolveContext(
- { agentId: 'non-existent-agent', sessionId: 'fallback-session' },
- mockDb,
- mockUserId,
- );
-
- // When agentId doesn't resolve, keep the original sessionId
- expect(result.sessionId).toBe('fallback-session');
- });
-
- it('should pass through all context fields correctly', async () => {
- const mockDb = createMockDb([]);
-
- const result = await resolveContext(
- {
- sessionId: 'session-1',
- topicId: 'topic-1',
- threadId: 'thread-1',
- groupId: 'group-1',
- },
- mockDb,
- mockUserId,
- );
-
- expect(result).toEqual({
- agentId: null,
- sessionId: 'session-1',
- topicId: 'topic-1',
- threadId: 'thread-1',
- groupId: 'group-1',
- });
- });
-
- it('should handle null values in input', async () => {
- const mockDb = createMockDb([]);
-
- const result = await resolveContext(
- {
- sessionId: null,
- topicId: null,
- threadId: null,
- groupId: null,
- },
- mockDb,
- mockUserId,
- );
-
- expect(result).toEqual({
- agentId: null,
- sessionId: null,
- topicId: null,
- threadId: null,
- groupId: null,
- });
- });
-
- it('should handle undefined values in input', async () => {
- const mockDb = createMockDb([]);
-
- const result = await resolveContext({}, mockDb, mockUserId);
-
- expect(result).toEqual({
- agentId: null,
- sessionId: null,
- topicId: null,
- threadId: null,
- groupId: null,
- });
- });
- });
-
- describe('resolveAgentIdFromSession', () => {
- it('should resolve sessionId to agentId', async () => {
- const mockDb = createMockDb([{ agentId: 'resolved-agent-1' }]);
-
- const result = await resolveAgentIdFromSession('session-1', mockDb, mockUserId);
-
- expect(result).toBe('resolved-agent-1');
- expect(mockDb.select).toHaveBeenCalled();
- });
-
- it('should return undefined when sessionId is not found', async () => {
- const mockDb = createMockDb([]); // Empty result
-
- const result = await resolveAgentIdFromSession('non-existent-session', mockDb, mockUserId);
-
- expect(result).toBeUndefined();
- });
-
- it('should query with correct userId filter', async () => {
- const mockLimit = vi.fn().mockResolvedValue([{ agentId: 'agent-1' }]);
- const mockWhere = vi.fn().mockReturnValue({ limit: mockLimit });
- const mockFrom = vi.fn().mockReturnValue({ where: mockWhere });
- const mockSelect = vi.fn().mockReturnValue({ from: mockFrom });
- const mockDb = { select: mockSelect } as any;
-
- await resolveAgentIdFromSession('session-1', mockDb, 'specific-user');
-
- expect(mockWhere).toHaveBeenCalled();
- // The where clause should be called with userId filter
- });
-
- it('should scope session reverse lookup by workspaceId when provided', async () => {
- const mockDb = createMockDb([{ agentId: 'agent-1' }]);
-
- const result = await resolveAgentIdFromSession('session-1', mockDb, mockUserId, 'ws-1');
-
- expect(result).toBe('agent-1');
- expect(mockBuildWorkspaceWhere).toHaveBeenCalledWith(
- { userId: mockUserId, workspaceId: 'ws-1' },
- expect.objectContaining({ workspaceId: 'workspace_id' }),
- );
- });
- });
-
- describe('resolveContextWithAgentId', () => {
- it('reverse-resolves a session-only context before resolving the canonical session', async () => {
- const mockDb = createMockDb([{ agentId: 'agent-1', sessionId: 'session-1' }]);
-
- const result = await resolveContextWithAgentId(
- { sessionId: 'session-1', topicId: 'topic-1' },
- mockDb,
- mockUserId,
- 'ws-1',
- );
-
- expect(result).toEqual({
- agentId: 'agent-1',
- groupId: null,
- sessionId: 'session-1',
- threadId: null,
- topicId: 'topic-1',
- });
- expect(mockDb.select).toHaveBeenCalledTimes(1);
- });
-
- it('keeps an unresolved legacy session without inventing an agent id', async () => {
- const mockDb = createMockDb([]);
-
- const result = await resolveContextWithAgentId(
- { sessionId: 'legacy-session' },
- mockDb,
- mockUserId,
- );
-
- expect(result.agentId).toBeNull();
- expect(result.sessionId).toBe('legacy-session');
- expect(mockDb.select).toHaveBeenCalledTimes(1);
- });
-
- it('replaces a stale agent id with the agent linked to the fallback session', async () => {
- const mockDb = createMockDb();
- mockDb._mocks.mockLimit
- .mockResolvedValueOnce([])
- .mockResolvedValueOnce([{ agentId: 'fallback-agent' }]);
-
- const result = await resolveContextWithAgentId(
- { agentId: 'stale-agent', sessionId: 'fallback-session' },
- mockDb,
- mockUserId,
- );
-
- expect(result.agentId).toBe('fallback-agent');
- expect(result.sessionId).toBe('fallback-session');
- expect(mockDb.select).toHaveBeenCalledTimes(2);
- });
- });
-
- describe('batchResolveAgentIdFromSessions', () => {
- // Helper to create a mock database for batch queries (no limit)
- const createBatchMockDb = (queryResult: any[] = []) => {
- const mockWhere = vi.fn().mockResolvedValue(queryResult);
- const mockFrom = vi.fn().mockReturnValue({ where: mockWhere });
- const mockSelect = vi.fn().mockReturnValue({ from: mockFrom });
-
- return {
- select: mockSelect,
- _mocks: { mockSelect, mockFrom, mockWhere },
- } as any;
- };
-
- it('should return empty map when sessionIds is empty', async () => {
- const mockDb = createBatchMockDb([]);
-
- const result = await batchResolveAgentIdFromSessions([], mockDb, 'user-1');
-
- expect(result).toBeInstanceOf(Map);
- expect(result.size).toBe(0);
- expect(mockDb.select).not.toHaveBeenCalled();
- });
-
- it('should resolve multiple sessionIds to agentIds', async () => {
- const mockDb = createBatchMockDb([
- { sessionId: 'session-1', agentId: 'agent-1' },
- { sessionId: 'session-2', agentId: 'agent-2' },
- ]);
-
- const result = await batchResolveAgentIdFromSessions(
- ['session-1', 'session-2'],
- mockDb,
- 'user-1',
- );
-
- expect(result).toBeInstanceOf(Map);
- expect(result.size).toBe(2);
- expect(result.get('session-1')).toBe('agent-1');
- expect(result.get('session-2')).toBe('agent-2');
- });
-
- it('should scope batch reverse lookup by workspaceId when provided', async () => {
- const mockDb = createBatchMockDb([{ sessionId: 'session-1', agentId: 'agent-1' }]);
-
- const result = await batchResolveAgentIdFromSessions(['session-1'], mockDb, 'user-1', 'ws-1');
-
- expect(result.get('session-1')).toBe('agent-1');
- expect(mockBuildWorkspaceWhere).toHaveBeenCalledWith(
- { userId: 'user-1', workspaceId: 'ws-1' },
- expect.objectContaining({ workspaceId: 'workspace_id' }),
- );
- });
-
- it('should handle partial matches', async () => {
- const mockDb = createBatchMockDb([{ sessionId: 'session-1', agentId: 'agent-1' }]);
-
- const result = await batchResolveAgentIdFromSessions(
- ['session-1', 'session-not-found'],
- mockDb,
- 'user-1',
- );
-
- expect(result.size).toBe(1);
- expect(result.get('session-1')).toBe('agent-1');
- expect(result.get('session-not-found')).toBeUndefined();
- });
- });
-});
diff --git a/apps/server/src/routers/lambda/_helpers/resolveContext.ts b/apps/server/src/routers/lambda/_helpers/resolveContext.ts
index a9764889c4a..12edf34dcfb 100644
--- a/apps/server/src/routers/lambda/_helpers/resolveContext.ts
+++ b/apps/server/src/routers/lambda/_helpers/resolveContext.ts
@@ -1,8 +1,13 @@
-import { and, eq, inArray } from 'drizzle-orm';
+import { TRPCError } from '@trpc/server';
+import { and, eq } from 'drizzle-orm';
import { agentsToSessions } from '@/database/schemas';
import { type LobeChatDatabase } from '@/database/type';
import { buildWorkspaceWhere } from '@/database/utils/workspace';
+import {
+ batchResolveSessionAgentIds,
+ resolveAgentReference,
+} from '@/server/services/agent/resolveReference';
import { type ConversationContextInput } from '../_schema/context';
@@ -31,30 +36,56 @@ export const resolveContext = async (
userId: string,
workspaceId?: string,
): Promise<ResolvedContext> => {
- let resolvedSessionId: string | null = input.sessionId ?? null;
-
- // If agentId is provided, prioritize looking up the corresponding sessionId from agentsToSessions table
- if (input.agentId) {
- const [relation] = await db
- .select({ sessionId: agentsToSessions.sessionId })
- .from(agentsToSessions)
- .where(
- and(
- eq(agentsToSessions.agentId, input.agentId),
- buildWorkspaceWhere({ userId, workspaceId }, agentsToSessions),
- ),
+ const id = input.agentId || input.sessionId;
+ let agentId: string | null = null;
+ let sessionId: string | null = null;
+ if (id) {
+ let resolved;
+ try {
+ resolved = await resolveAgentReference(id, db, userId, workspaceId);
+ } catch (error) {
+ // Preserve the existing stale-agent fallback, but authorize and write
+ // using the fallback's real agent identity, never the stale input.
+ if (
+ !(error instanceof TRPCError) ||
+ error.code !== 'NOT_FOUND' ||
+ !input.agentId ||
+ !input.sessionId
)
- .limit(1);
-
- if (relation) {
- resolvedSessionId = relation.sessionId;
+ throw error;
+ resolved = await resolveAgentReference(input.sessionId, db, userId, workspaceId);
+ }
+ agentId = resolved.agentId;
+ sessionId = resolved.sessionId;
+ if (!sessionId && agentId) {
+ const links = await db
+ .select({ sessionId: agentsToSessions.sessionId })
+ .from(agentsToSessions)
+ .where(
+ and(
+ eq(agentsToSessions.agentId, agentId),
+ buildWorkspaceWhere({ userId, workspaceId }, agentsToSessions),
+ ),
+ )
+ .limit(2);
+ // Never select an arbitrary shell when an agent belongs to several.
+ if (links.length === 1) {
+ try {
+ sessionId = (await resolveAgentReference(links[0].sessionId, db, userId, workspaceId))
+ .sessionId;
+ } catch (error) {
+ // An Agent can participate in an old group shell. It remains an
+ // Agent context; the group must never become its legacy container.
+ if (!(error instanceof TRPCError) || !['NOT_FOUND', 'BAD_REQUEST'].includes(error.code))
+ throw error;
+ }
+ }
}
}
-
return {
- agentId: input.agentId ?? null,
+ agentId,
groupId: input.groupId ?? null,
- sessionId: resolvedSessionId,
+ sessionId,
threadId: input.threadId ?? null,
topicId: input.topicId ?? null,
};
@@ -76,18 +107,7 @@ export const resolveAgentIdFromSession = async (
userId: string,
workspaceId?: string,
): Promise<string | undefined> => {
- const [relation] = await db
- .select({ agentId: agentsToSessions.agentId })
- .from(agentsToSessions)
- .where(
- and(
- eq(agentsToSessions.sessionId, sessionId),
- buildWorkspaceWhere({ userId, workspaceId }, agentsToSessions),
- ),
- )
- .limit(1);
-
- return relation?.agentId;
+ return (await resolveAgentReference(sessionId, db, userId, workspaceId)).agentId ?? undefined;
};
/**
@@ -100,16 +120,7 @@ export const resolveContextWithAgentId = async (
userId: string,
workspaceId?: string,
): Promise<ResolvedContext> => {
- const resolved = await resolveContext(input, db, userId, workspaceId);
- if (!resolved.sessionId) return resolved;
-
- // Canonicalize the agent from the session that actually won resolution.
- // This preserves the legacy fallback contract when a stale/non-existent
- // agentId is sent together with a valid sessionId, instead of carrying the
- // stale id into a foreign-keyed write.
- const agentId = await resolveAgentIdFromSession(resolved.sessionId, db, userId, workspaceId);
-
- return { ...resolved, agentId: agentId ?? resolved.agentId };
+ return resolveContext(input, db, userId, workspaceId);
};
/**
@@ -128,17 +139,5 @@ export const batchResolveAgentIdFromSessions = async (
userId: string,
workspaceId?: string,
): Promise<Map<string, string>> => {
- if (sessionIds.length === 0) return new Map();
-
- const relations = await db
- .select({ agentId: agentsToSessions.agentId, sessionId: agentsToSessions.sessionId })
- .from(agentsToSessions)
- .where(
- and(
- buildWorkspaceWhere({ userId, workspaceId }, agentsToSessions),
- inArray(agentsToSessions.sessionId, sessionIds),
- ),
- );
-
- return new Map(relations.map((r) => [r.sessionId, r.agentId]));
+ return batchResolveSessionAgentIds(sessionIds, db, userId, workspaceId);
};
diff --git a/apps/server/src/routers/lambda/agent/config.ts b/apps/server/src/routers/lambda/agent/config.ts
index f7348f59502..14f9ff90064 100644
--- a/apps/server/src/routers/lambda/agent/config.ts
+++ b/apps/server/src/routers/lambda/agent/config.ts
@@ -7,6 +7,10 @@ import { z } from 'zod';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
import { UserModel } from '@/database/models/user';
import { router } from '@/libs/trpc/lambda';
+import {
+ InboxNotProvisionedError,
+ resolveAgentReference,
+} from '@/server/services/agent/resolveReference';
import { assertCanEditResource } from '@/server/services/resourcePermission';
import { isWorkspacePrimaryOwner } from '@/server/services/workspacePermission';
@@ -70,26 +74,34 @@ export const configRouter = router({
}),
)
.query(async ({ input, ctx }) => {
- if (input.sessionId === INBOX_SESSION_ID) {
- const item = await ctx.sessionModel.findByIdOrSlug(INBOX_SESSION_ID);
- // if there is no session for user, create one
- if (!item) {
- // if there is no user, return default config
+ if (input.sessionId === INBOX_SESSION_ID || input.sessionId === 'ssn_inbox') {
+ try {
+ const resolved = await resolveAgentReference(
+ input.sessionId,
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+ const config = await ctx.agentService.getAgentConfigById(resolved.agentId);
+ return protectAgentConfig(ctx, resolved.agentId, config);
+ } catch (error) {
+ if (!(error instanceof TRPCError) || !(error.cause instanceof InboxNotProvisionedError))
+ throw error;
const user = await UserModel.findById(ctx.serverDB, ctx.userId);
if (!user) return DEFAULT_AGENT_CONFIG;
-
- const res = await ctx.agentService.createInbox();
- console.info('create inbox session', res);
+ const config = await ctx.agentService.getBuiltinAgent(INBOX_SESSION_ID);
+ return config?.id ? protectAgentConfig(ctx, config.id, config) : config;
}
}
- const session = await ctx.sessionModel.findByIdOrSlug(input.sessionId);
-
- if (!session) throw new Error(`Session [${input.sessionId}] not found`);
- const sessionId = session.id;
-
- const config = await ctx.agentModel.findBySessionId(sessionId);
- return config?.id ? protectAgentConfig(ctx, config.id, config) : config;
+ const { agentId } = await resolveAgentReference(
+ input.sessionId,
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+ const config = await ctx.agentService.getAgentConfigById(agentId);
+ return protectAgentConfig(ctx, agentId, config);
}),
getAgentConfigById: agentProcedure
.input(
@@ -98,8 +110,14 @@ export const configRouter = router({
}),
)
.query(async ({ input, ctx }) => {
- const config = await ctx.agentService.getAgentConfigById(input.agentId);
- return protectAgentConfig(ctx, input.agentId, config);
+ const { agentId } = await resolveAgentReference(
+ input.agentId,
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+ const config = await ctx.agentService.getAgentConfigById(agentId);
+ return protectAgentConfig(ctx, agentId, config);
}),
/**
* Get a builtin agent by slug, creating it if it doesn't exist.
@@ -126,10 +144,17 @@ export const configRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ const resolved = await resolveAgentReference(
+ input.agentId,
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+ const agentId = resolved.agentId;
// General-access write guard: only `edit` permits collaborative updates.
await assertCanEditResource({
db: ctx.serverDB,
- resourceId: input.agentId,
+ resourceId: agentId,
resourceType: 'agent',
userId: ctx.userId,
workspaceId: ctx.workspaceId ?? undefined,
@@ -147,7 +172,7 @@ export const configRouter = router({
if (policyPatch) {
const canUpdatePolicies =
- (await ctx.agentModel.existsOwnedById(input.agentId)) ||
+ (await ctx.agentModel.existsOwnedById(agentId)) ||
(await isWorkspacePrimaryOwner({
db: ctx.serverDB,
userId: ctx.userId,
@@ -161,7 +186,7 @@ export const configRouter = router({
// Collaborative edit lock: reject writes to a workspace agent another
// member is actively editing. Inert until a client acquires the lock.
if (ctx.workspaceId) {
- const blockedBy = await ctx.editLockService.getBlockingHolder('agent', input.agentId);
+ const blockedBy = await ctx.editLockService.getBlockingHolder('agent', agentId);
if (blockedBy) {
throw new TRPCError({
cause: { data: { code: 'DocumentLocked' } },
@@ -173,7 +198,7 @@ export const configRouter = router({
// Use AgentService to update and return the updated agent data
return ctx.agentService.updateAgentConfig(
- input.agentId,
+ agentId,
safeValue,
input.replaceWorkingDirDeviceIds,
);
diff --git a/apps/server/src/routers/lambda/agent/lifecycle.ts b/apps/server/src/routers/lambda/agent/lifecycle.ts
index e64e5240b5b..34aeaf10400 100644
--- a/apps/server/src/routers/lambda/agent/lifecycle.ts
+++ b/apps/server/src/routers/lambda/agent/lifecycle.ts
@@ -50,8 +50,7 @@ export const lifecycleRouter = router({
return ctx.agentModel.countAgents(input);
}),
/**
- * Create a new agent with session
- * Returns the created agent ID and session ID
+ * Create a standalone agent. Returns the created agent ID.
*/
createAgent: agentProcedure
.use(withScopedPermission('agent:create'))
@@ -63,51 +62,7 @@ export const lifecycleRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
- // Creating inside a Category has to land in that Category. The folder's
- // visibility decides the new agent's, rather than the other way round:
- // the sidebar resolves a public agent's folder only against public
- // folders (and a private agent's only against private ones), so a
- // default-public agent created from a private Category would render in
- // Ungrouped β€” for its creator too. The "New Agent" action inside a
- // private Category sends only `{ groupId }`, so this is the normal path,
- // not a crafted one. An explicit conflicting `visibility` is refused
- // rather than silently overridden.
- const folderVisibility = input.groupId
- ? await ctx.agentModel.getAssignableSessionGroupVisibility(input.groupId)
- : undefined;
-
- if (folderVisibility && input.visibility && input.visibility !== folderVisibility)
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: `A ${input.visibility} agent cannot be created in a ${folderVisibility} folder`,
- });
-
- const agent = await ctx.agentModel.create({
- ...input.config,
- // The DB-layer AgentItem (packages/database/src/schemas/agent.ts) is
- // intentionally still typed `plugins?: string[]` β€” the JSONB column
- // itself isn't widened, only the domain-level `@lobechat/types`
- // shapes. Bridges the tri-state object shape through.
- plugins: input.config?.plugins as unknown as string[] | undefined,
- sessionGroupId: input.groupId,
- // Router-level `visibility` wins over any nested config value so the
- // sidebar's "Create in Private" entry can't be overridden by a stale
- // default config.
- ...(input.visibility || folderVisibility
- ? { visibility: input.visibility ?? folderVisibility }
- : {}),
- });
-
- if (ctx.workspaceId && agent.visibility !== 'private') {
- await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).setAccessLevel(
- 'agent',
- agent.id,
- DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
- ctx.userId,
- );
- }
-
- return { agentId: agent.id };
+ return ctx.agentService.createAgent(input);
}),
/**
* Create an agent without session.
diff --git a/apps/server/src/routers/lambda/aiChat.ts b/apps/server/src/routers/lambda/aiChat.ts
index c943e0a1667..0d346fc30e2 100644
--- a/apps/server/src/routers/lambda/aiChat.ts
+++ b/apps/server/src/routers/lambda/aiChat.ts
@@ -22,7 +22,9 @@ import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { markSilentTRPCErrorLog } from '@/libs/trpc/utils/errorLogger';
import { unwrapPgError } from '@/server/modules/AgentRuntime/pgError';
+import { assertCanUseConversationTargets } from '@/server/routers/lambda/_helpers/conversationResourceGuard';
import { resolveContext } from '@/server/routers/lambda/_helpers/resolveContext';
+import { resolveAgentReference } from '@/server/services/agent/resolveReference';
import { AiChatService } from '@/server/services/aiChat';
import { AiGenerationService } from '@/server/services/aiGeneration';
import { FileService } from '@/server/services/file';
@@ -204,7 +206,34 @@ export const aiChatRouter = router({
sendMessageInServer: aiChatWriteProcedure
.input(AiSendMessageServerSchema)
- .mutation(async ({ input, ctx }) => {
+ .mutation(async ({ input: rawInput, ctx }) => {
+ const context = await resolveContext(
+ rawInput,
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+ await assertCanUseConversationTargets(
+ { db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId },
+ [context],
+ );
+ const replyId = rawInput.newAssistantMessage.agentId;
+ const replyAgentId =
+ replyId && (replyId.startsWith('ssn_') || replyId === 'inbox')
+ ? (
+ await resolveAgentReference(
+ replyId,
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ )
+ ).agentId
+ : replyId;
+ const input = {
+ ...rawInput,
+ agentId: context.agentId ?? undefined,
+ sessionId: context.sessionId ?? undefined,
+ };
const timingContext =
input.newAssistantMessage.provider === 'lobehub'
? { requestId: createTimingRequestId(), startedAt: Date.now() }
@@ -223,16 +252,7 @@ export const aiChatRouter = router({
input.newTopic,
input.newThread,
);
- let sessionId = input.sessionId;
- if (!sessionId) {
- const context = await runTimedStage(
- timingContext,
- 'lambda.aiChat.resolveContext',
- () => resolveContext(input, ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined),
- { hasAgentId: !!input.agentId },
- );
- if (!!context.sessionId) sessionId = context.sessionId;
- }
+ const sessionId = input.sessionId;
let topicId = input.topicId!;
let threadId = input.threadId;
@@ -449,7 +469,7 @@ export const aiChatRouter = router({
topicId,
} satisfies CreateMessageParams;
const assistantMessage = {
- agentId: input.newAssistantMessage.agentId ?? input.agentId,
+ agentId: replyAgentId ?? input.agentId,
content: LOADING_FLAT,
groupId: input.groupId,
metadata: input.newAssistantMessage.metadata,
diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.ts
index c3a2950ab22..a38e55312d3 100644
--- a/apps/server/src/routers/lambda/message.ts
+++ b/apps/server/src/routers/lambda/message.ts
@@ -35,7 +35,7 @@ import {
import { getMessagesPageSizeSchema } from './_helpers/getMessagesPageSize';
import { messagesByCursorInputSchema, readMessagesByCursor } from './_helpers/messagesByCursor';
import { projectSharedTopicMessages } from './_helpers/projectSharedTopicMessages';
-import { resolveAgentIdFromSession, resolveContext } from './_helpers/resolveContext';
+import { resolveContext } from './_helpers/resolveContext';
import {
assertCreatorMessageTargets,
assertCreatorTopicTargets,
@@ -176,16 +176,9 @@ export const messageRouter = router({
},
}
: rawOperation;
- if (
- operation.type !== 'createMessage' ||
- operation.message.agentId ||
- !operation.message.sessionId
- ) {
- return operation as MessageBatchOperation;
- }
-
- const agentId = await resolveAgentIdFromSession(
- operation.message.sessionId,
+ if (operation.type !== 'createMessage') return operation as MessageBatchOperation;
+ const resolved = await resolveContext(
+ { ...operation.message, agentId: operation.message.agentId ?? undefined },
ctx.serverDB,
ctx.userId,
ctx.workspaceId ?? undefined,
@@ -195,7 +188,8 @@ export const messageRouter = router({
...operation,
message: {
...operation.message,
- agentId: agentId!,
+ agentId: resolved.agentId,
+ sessionId: resolved.sessionId,
},
} as MessageBatchOperation;
}),
@@ -337,18 +331,13 @@ export const messageRouter = router({
.use(withScopedPermission('message:create'))
.input(CreateNewMessageParamsSchema)
.mutation(async ({ input, ctx }) => {
- // If there's no agentId but has sessionId, resolve agentId from sessionId
- let agentId = input.agentId;
- if (!agentId && input.sessionId) {
- agentId = (await resolveAgentIdFromSession(
- input.sessionId,
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- ))!;
- }
-
- await assertCanUseConversationTargets(guardCtx(ctx), [{ agentId, groupId: input.groupId }]);
+ const resolved = await resolveContext(
+ { ...input, agentId: input.agentId ?? undefined },
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+ await assertCanUseConversationTargets(guardCtx(ctx), [resolved]);
// The declared agent/group is client-supplied and can be omitted or
// forged while still inserting into `topicId` β€” guard the topic's own
// DB-resolved target as well.
@@ -363,7 +352,8 @@ export const messageRouter = router({
// server-owned metadata a client slipped in is dropped here.
return ctx.messageService.createMessage({
...input,
- agentId,
+ agentId: resolved.agentId,
+ sessionId: resolved.sessionId,
metadata: omitServerOwnedMessageMetadata(input.metadata),
} as any);
}),
@@ -538,9 +528,19 @@ export const messageRouter = router({
const messageModel = new MessageModel(ctx.serverDB, ctx.userId, wsId);
const fileService = new FileService(ctx.serverDB, ctx.userId, wsId);
- const messages = await messageModel.query(queryParams, {
- postProcessUrl: (path, file) => fileService.getFileAccessUrl({ id: file.id, url: path }),
- });
+ const resolved = await resolveContext(
+ { ...queryParams, agentId: queryParams.agentId ?? undefined },
+ ctx.serverDB,
+ ctx.userId,
+ wsId,
+ );
+ await assertCanUseConversationTargets(guardCtx({ ...ctx, userId: ctx.userId }), [resolved]);
+ const messages = await messageModel.query(
+ { ...queryParams, ...resolved },
+ {
+ postProcessUrl: (path, file) => fileService.getFileAccessUrl({ id: file.id, url: path }),
+ },
+ );
// Only the caller knows whether this list is going to be rendered or fed
// to a model: a run that executes in the browser assembles its context
@@ -644,24 +644,21 @@ export const messageRouter = router({
)
.mutation(async ({ input, ctx }) => {
const { agentId, ...options } = input;
- // Row-based guard via the topic when available; sweeps without a topic
- // fall back to the declared agent target.
- if (options.topicId) await assertCanUseTopicTargets(guardCtx(ctx), [options.topicId]);
- else
- await assertCanUseConversationTargets(guardCtx(ctx), [{ agentId, groupId: input.groupId }]);
- // Same visitor guard as `addFilesToMessage` above.
- if (options.topicId) await assertCreatorTopicTargets(guardCtx(ctx), [options.topicId]);
const resolved = await resolveContext(
{ agentId, ...options },
ctx.serverDB,
ctx.userId,
ctx.workspaceId ?? undefined,
);
+ if (options.topicId) await assertCanUseTopicTargets(guardCtx(ctx), [options.topicId]);
+ await assertCanUseConversationTargets(guardCtx(ctx), [resolved]);
+ if (options.topicId) await assertCreatorTopicTargets(guardCtx(ctx), [options.topicId]);
return ctx.messageModel.deleteMessagesBySession(
resolved.sessionId,
resolved.topicId,
input.groupId,
+ { agentId: resolved.agentId ?? undefined },
);
}),
diff --git a/apps/server/src/routers/lambda/session.ts b/apps/server/src/routers/lambda/session.ts
index 7fed993fc92..34956fa12d7 100644
--- a/apps/server/src/routers/lambda/session.ts
+++ b/apps/server/src/routers/lambda/session.ts
@@ -1,13 +1,16 @@
+import { CreateAgentSchema } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
-import { SessionModel } from '@/database/models/session';
-import { insertAgentSchema, insertSessionSchema } from '@/database/schemas';
+import { AgentModel } from '@/database/models/agent';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { AgentService } from '@/server/services/agent';
+import { resolveAgentReference } from '@/server/services/agent/resolveReference';
-import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';
+import { assertCanUseConversationTargets } from './_helpers/conversationResourceGuard';
const sessionProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
@@ -15,57 +18,78 @@ const sessionProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts)
return opts.next({
ctx: {
- sessionModel: new SessionModel(ctx.serverDB, ctx.userId, wsId),
+ agentModel: new AgentModel(ctx.serverDB, ctx.userId, wsId),
+ agentService: new AgentService(ctx.serverDB, ctx.userId, wsId),
},
});
});
-/**
- * @deprecated Session router is legacy. Use agent router for agent CRUD operations.
- * Session-based agent creation (createSession) should migrate
- * to agent.createAgent which uses agentModel.create directly.
- * Retains legacy session creation and session-shell updates for compatibility.
- */
+/** Native Session compatibility adapters. New clients should use the Agent router. */
export const sessionRouter = router({
- /** @deprecated Use agent.createAgent instead */
+ /** Native compatibility adapter: keep the Session envelope, create only an Agent. */
createSession: sessionProcedure
- .use(withScopedPermission('session:create'))
+ .use(withScopedPermission('agent:create'))
.input(
z.object({
- config: insertAgentSchema
- .omit({
- chatConfig: true,
- openingMessage: true,
- openingQuestions: true,
- plugins: true,
- tags: true,
- tts: true,
- })
- .passthrough()
- .partial(),
- session: insertSessionSchema.omit({ createdAt: true, updatedAt: true }).partial(),
+ // Zod strips redundant fields in full default Session configs. This is
+ // a user-configurable whitelist, never a database insert permission.
+ config: CreateAgentSchema.extend({
+ examples: z.unknown().optional(),
+ identifier: z.string().optional(),
+ }),
+ session: z.object({
+ groupId: z.string().nullish(),
+ pinned: z.boolean().optional(),
+ }),
type: z.enum(['agent', 'group']),
}),
)
.mutation(async ({ input, ctx }) => {
- const data = await ctx.sessionModel.create(input);
-
- return data.id;
+ if (input.type !== 'agent') {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Use agentGroup to create a group' });
+ }
+ const { examples, identifier, ...config } = input.config;
+ const groupId = input.session.groupId ?? config.sessionGroupId;
+ const { agentId } = await ctx.agentService.createAgent({
+ config: {
+ ...config,
+ fewShots: config.fewShots ?? examples,
+ marketIdentifier: config.marketIdentifier ?? identifier,
+ pinned: input.session.pinned,
+ },
+ groupId: groupId && groupId !== 'default' ? groupId : undefined,
+ visibility: config.visibility,
+ });
+ return agentId;
}),
+ /** Native activity signal. Payload dates are accepted but never trusted. */
updateSession: sessionProcedure
.use(withScopedPermission('session:update'))
.input(
z.object({
id: z.string(),
- value: insertSessionSchema.partial(),
+ value: z
+ .object({
+ groupId: z.undefined().optional(),
+ pinned: z.undefined().optional(),
+ updatedAt: z.union([z.date(), z.number(), z.string()]).optional(),
+ })
+ .strict(),
}),
)
.mutation(async ({ input, ctx }) => {
- const session = await ctx.sessionModel.findByIdOrSlug(input.id);
- if (session) assertWorkspaceRowManageable(ctx, session.userId, 'session');
-
- return ctx.sessionModel.update(input.id, input.value);
+ const { agentId } = await resolveAgentReference(
+ input.id,
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+ await assertCanUseConversationTargets(
+ { db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId },
+ [{ agentId }],
+ );
+ return ctx.agentModel.touchUpdatedAt(agentId);
}),
});
diff --git a/apps/server/src/routers/lambda/topic/queries.ts b/apps/server/src/routers/lambda/topic/queries.ts
index 2fed485af18..2d05f6b56ff 100644
--- a/apps/server/src/routers/lambda/topic/queries.ts
+++ b/apps/server/src/routers/lambda/topic/queries.ts
@@ -1,3 +1,4 @@
+import { INBOX_SESSION_ID } from '@lobechat/const';
import {
type RecentTopic,
type RecentTopicGroup,
@@ -5,23 +6,21 @@ import {
} from '@lobechat/types';
import { cleanObject } from '@lobechat/utils';
import { TRPCError } from '@trpc/server';
-import { and, inArray } from 'drizzle-orm';
+import { and, eq, inArray } from 'drizzle-orm';
import { z } from 'zod';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
import { MessageModel } from '@/database/models/message';
-import { chatGroups } from '@/database/schemas';
+import { agents, chatGroups } from '@/database/schemas';
import { notTrashed } from '@/database/utils/softDelete';
+import { buildWorkspaceWhere } from '@/database/utils/workspace';
import { router } from '@/libs/trpc/lambda';
import { TopicReferenceService } from '@/server/services/topicReference';
import { after } from '@/server/utils/scheduleAfterResponse';
-import {
- batchResolveAgentIdFromSessions,
- resolveAgentIdFromSession,
- resolveContext,
-} from '../_helpers/resolveContext';
-import { topicProcedure, topicSearchProcedure } from './procedures';
+import { assertCanUseConversationTargets } from '../_helpers/conversationResourceGuard';
+import { batchResolveAgentIdFromSessions, resolveContext } from '../_helpers/resolveContext';
+import { guardCtx, topicProcedure, topicSearchProcedure } from './procedures';
export const queryRouter = router({
getTopicDetail: topicProcedure
@@ -153,7 +152,7 @@ export const queryRouter = router({
.query(async ({ input, ctx }) => {
const {
sessionId,
- isInbox,
+ isInbox: _isInbox,
groupId,
excludeStatuses,
excludeTriggers,
@@ -175,20 +174,36 @@ export const queryRouter = router({
return { items: result.items, total: result.total };
}
- // If sessionId is provided but no agentId, need to reverse lookup agentId
- let effectiveAgentId = rest.agentId;
- if (!effectiveAgentId && sessionId) {
- effectiveAgentId = await resolveAgentIdFromSession(
- sessionId,
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- );
- }
+ const resolvedContext = await resolveContext(
+ { agentId: rest.agentId ?? undefined, sessionId },
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+ const effectiveAgentId = resolvedContext.agentId ?? undefined;
+ await assertCanUseConversationTargets(guardCtx(ctx), [resolvedContext]);
+
+ // Inbox semantics come from the authorized canonical Agent, never an
+ // optional client flag (released native clients may omit or cache it).
+ const inboxAgent = effectiveAgentId
+ ? await ctx.serverDB.query.agents.findFirst({
+ columns: { id: true },
+ where: and(
+ eq(agents.id, effectiveAgentId),
+ eq(agents.slug, INBOX_SESSION_ID),
+ buildWorkspaceWhere(
+ { userId: ctx.userId, workspaceId: ctx.workspaceId ?? undefined },
+ agents,
+ ),
+ ),
+ })
+ : undefined;
+ const isInbox = !!inboxAgent;
const result = await ctx.topicModel.query({
...rest,
agentId: effectiveAgentId,
+ legacySessionId: resolvedContext.sessionId,
excludeStatuses,
excludeTriggers,
includeTriggers,
@@ -395,16 +410,29 @@ export const queryRouter = router({
ctx.workspaceId ?? undefined,
);
- // Scope the search exactly like the topics list (`query`): by agentId
- // directly (the new agent system stamps every topic with an agentId).
- // Passing only the resolved sessionId used to miss every agentId-scoped
- // topic β€” the cause of "no topics match" in the per-agent Topics search.
- // `containerId` is only the fallback for legacy callers that pass no
- // agentId/groupId.
- return ctx.topicModel.queryByKeyword(input.keywords, {
- agentId: input.agentId,
+ await assertCanUseConversationTargets(guardCtx(ctx), [resolved]);
+
+ const byAgent = ctx.topicModel.queryByKeyword(input.keywords, {
+ agentId: resolved.agentId ?? undefined,
containerId: resolved.sessionId,
groupId: input.groupId,
});
+ if (!resolved.agentId || !resolved.sessionId || input.groupId) return byAgent;
+
+ // Legacy topics can still lack agentId before the existing on-read
+ // migration finishes. Search both scopes through the same search backend;
+ // only unassigned legacy rows may supplement the canonical Agent result.
+ const [current, legacy] = await Promise.all([
+ byAgent,
+ ctx.topicModel.queryByKeyword(input.keywords, { containerId: resolved.sessionId }),
+ ]);
+ return [
+ ...new Map(
+ [...current, ...legacy.filter((topic) => !topic.agentId)].map((topic) => [
+ topic.id,
+ topic,
+ ]),
+ ).values(),
+ ];
}),
});
diff --git a/apps/server/src/routers/lambda/topic/remove.ts b/apps/server/src/routers/lambda/topic/remove.ts
index 3c90eff2098..f08946bdf18 100644
--- a/apps/server/src/routers/lambda/topic/remove.ts
+++ b/apps/server/src/routers/lambda/topic/remove.ts
@@ -7,10 +7,7 @@ import {
assertWorkspaceRowManageable,
shouldRestrictBulkDeleteToCreator,
} from '../_helpers/assertWorkspaceRowManageable';
-import {
- assertCanUseConversationTargets,
- assertCanUseSessionTargets,
-} from '../_helpers/conversationResourceGuard';
+import { assertCanUseConversationTargets } from '../_helpers/conversationResourceGuard';
import { resolveContext } from '../_helpers/resolveContext';
import { guardCtx, topicProcedure } from './procedures';
@@ -62,15 +59,16 @@ export const removeRouter = router({
ctx.workspaceId ?? undefined,
);
- if (input.agentId) {
- await assertCanUseConversationTargets(guardCtx(ctx), [{ agentId: input.agentId }]);
- } else if (resolved.sessionId) {
- await assertCanUseSessionTargets(guardCtx(ctx), [resolved.sessionId]);
- }
-
+ await assertCanUseConversationTargets(guardCtx(ctx), [resolved]);
const restrictToCreator = shouldRestrictBulkDeleteToCreator(ctx, input.scope);
-
- await ctx.trashService.trashTopicsBySession(resolved.sessionId, { restrictToCreator });
+ if (resolved.agentId) {
+ await ctx.trashService.trashTopicsByAgent(resolved.agentId, {
+ legacySessionId: resolved.sessionId,
+ restrictToCreator,
+ });
+ } else {
+ await ctx.trashService.trashTopicsBySession(resolved.sessionId, { restrictToCreator });
+ }
}),
removeAllTopics: topicProcedure
.use(withScopedPermission('topic:delete'))
diff --git a/apps/server/src/routers/lambda/topic/update.ts b/apps/server/src/routers/lambda/topic/update.ts
index 616c4a25d36..e1efc8bc6a5 100644
--- a/apps/server/src/routers/lambda/topic/update.ts
+++ b/apps/server/src/routers/lambda/topic/update.ts
@@ -48,22 +48,20 @@ export const updateRouter = router({
// view-only members are read-only.
await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);
await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);
- const { agentId, ...restValue } = input.value;
- if (agentId) await assertCanUseConversationTargets(guardCtx(ctx), [{ agentId }]);
-
- // If agentId is provided, resolve to sessionId
- let resolvedSessionId = restValue.sessionId;
- if (agentId && !resolvedSessionId) {
- const resolved = await resolveContext(
- { agentId },
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- );
- resolvedSessionId = resolved.sessionId ?? undefined;
- }
-
- return ctx.topicModel.update(input.id, { ...restValue, sessionId: resolvedSessionId });
+ const { agentId, sessionId, ...restValue } = input.value;
+ if (!agentId && !sessionId) return ctx.topicModel.update(input.id, restValue);
+ const resolved = await resolveContext(
+ { agentId, sessionId },
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+ await assertCanUseConversationTargets(guardCtx(ctx), [resolved]);
+ return ctx.topicModel.update(input.id, {
+ ...restValue,
+ agentId: resolved.agentId,
+ sessionId: resolved.sessionId,
+ });
}),
/**
* Switch the topic's pinned model and its effort pin atomically β€” see
diff --git a/apps/server/src/services/agent/index.ts b/apps/server/src/services/agent/index.ts
index 08d59428d7a..80e554dfcf3 100644
--- a/apps/server/src/services/agent/index.ts
+++ b/apps/server/src/services/agent/index.ts
@@ -3,7 +3,12 @@ import { BUILTIN_AGENTS } from '@lobechat/builtin-agents';
import { DEFAULT_PROVIDER } from '@lobechat/business-const';
import { DEFAULT_AGENT_CONFIG, DEFAULT_MODEL } from '@lobechat/const';
import { type LobeChatDatabase } from '@lobechat/database';
-import { type AgentItem, type LobeAgentChatConfig, type LobeAgentConfig } from '@lobechat/types';
+import {
+ type AgentItem,
+ type CreateAgentConfig,
+ type LobeAgentChatConfig,
+ type LobeAgentConfig,
+} from '@lobechat/types';
import { cleanObject, merge } from '@lobechat/utils';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
@@ -12,8 +17,10 @@ import { type PartialDeep } from 'type-fest';
import { AGENT_SHARE_ALLOWED_PROVIDERS } from '@/business/agent-share';
import { AgentModel } from '@/database/models/agent';
import { AgentShareModel } from '@/database/models/agentShare';
+import { ResourcePermissionModel } from '@/database/models/resourcePermission';
import { SessionModel } from '@/database/models/session';
import { UserModel } from '@/database/models/user';
+import { DEFAULT_RESOURCE_ACCESS_LEVELS } from '@/database/schemas';
import { normalizeInboxAgentAvatar, normalizeInboxAgentTitle } from '@/database/utils/inboxAgent';
import { getRedisConfig } from '@/envs/redis';
import { getServerDefaultAgentConfig } from '@/server/globalConfig';
@@ -70,6 +77,41 @@ export class AgentService {
this.userModel = new UserModel(db, userId);
}
+ /** Shared creation policy for Agent clients and the native Session adapter. */
+ async createAgent(input: {
+ config?: CreateAgentConfig & { pinned?: boolean };
+ groupId?: string;
+ visibility?: 'private' | 'public';
+ }) {
+ const folderVisibility = input.groupId
+ ? await this.agentModel.getAssignableSessionGroupVisibility(input.groupId)
+ : undefined;
+ const visibility = input.visibility;
+ if (folderVisibility && visibility && visibility !== folderVisibility) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `A ${visibility} agent cannot be created in a ${folderVisibility} folder`,
+ });
+ }
+
+ const agent = await this.agentModel.create({
+ ...input.config,
+ plugins: input.config?.plugins as unknown as string[] | undefined,
+ sessionGroupId: input.groupId,
+ ...(visibility || folderVisibility ? { visibility: visibility ?? folderVisibility } : {}),
+ });
+
+ if (this.workspaceId && agent.visibility !== 'private') {
+ await new ResourcePermissionModel(this.db, this.workspaceId).setAccessLevel(
+ 'agent',
+ agent.id,
+ DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
+ this.userId,
+ );
+ }
+ return { agentId: agent.id };
+ }
+
/** Validate the effective selection at configuration boundaries, including inherited defaults. */
async assertShareModelAllowed(agentId: string, patch: PartialDeep<AgentItem> = {}) {
if (!AGENT_SHARE_ALLOWED_PROVIDERS) return;
diff --git a/apps/server/src/services/agent/resolveReference.ts b/apps/server/src/services/agent/resolveReference.ts
new file mode 100644
index 00000000000..cbdc6df725c
--- /dev/null
+++ b/apps/server/src/services/agent/resolveReference.ts
@@ -0,0 +1,149 @@
+import { INBOX_SESSION_ID } from '@lobechat/const';
+import { TRPCError } from '@trpc/server';
+import { and, eq, inArray } from 'drizzle-orm';
+
+import { agents, agentsToSessions, sessions } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+import { buildWorkspaceWhere } from '@/database/utils/workspace';
+
+export interface AgentReference {
+ agentId: string;
+ sessionId: string | null;
+}
+
+/** Only an entirely unprovisioned Inbox may enter the builtin creation path. */
+export class InboxNotProvisionedError extends Error {}
+
+/** Resolves identity and scope only. Callers must still apply their operation's ACL. */
+export const resolveAgentReference = async (
+ id: string,
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId?: string,
+): Promise<AgentReference> => {
+ const scope = { userId, workspaceId };
+ const inbox = id === INBOX_SESSION_ID || id === 'ssn_inbox';
+ // Prefixes route known identities; imported/custom Agent ids still require
+ // the same scoped database lookup, never authorization by their spelling.
+ if (id.startsWith('agt_') || (!id.startsWith('ssn_') && !inbox)) {
+ const agent = await db.query.agents.findFirst({
+ columns: { id: true },
+ where: and(eq(agents.id, id), buildWorkspaceWhere(scope, agents)),
+ });
+ if (agent) return { agentId: agent.id, sessionId: null };
+ if (id.startsWith('agt_'))
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
+ }
+
+ // ssn_inbox is a historical alias, not a prefix substitution. Prefer its
+ // real relationship when present; otherwise resolve the scoped inbox slug.
+ const session =
+ (await db.query.sessions.findFirst({
+ columns: { id: true, type: true },
+ where: and(eq(sessions.id, id), buildWorkspaceWhere(scope, sessions)),
+ })) ??
+ (inbox
+ ? await db.query.sessions.findFirst({
+ columns: { id: true, type: true },
+ where: and(eq(sessions.slug, INBOX_SESSION_ID), buildWorkspaceWhere(scope, sessions)),
+ })
+ : undefined);
+
+ if (session) {
+ // Count every link before filtering agent visibility/trash. Filtering first
+ // would turn a multi-agent shell into an accidental single-agent alias.
+ const links = await db
+ .select({ agentId: agentsToSessions.agentId })
+ .from(agentsToSessions)
+ .where(
+ and(
+ eq(agentsToSessions.sessionId, session.id),
+ buildWorkspaceWhere(scope, agentsToSessions),
+ ),
+ );
+ if (session.type === 'group' || links.length > 1) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'A group or multi-agent session is not an agent context',
+ });
+ }
+ if (links.length === 1) {
+ const agent = await db.query.agents.findFirst({
+ columns: { id: true },
+ where: and(eq(agents.id, links[0].agentId), buildWorkspaceWhere(scope, agents)),
+ });
+ if (agent) return { agentId: agent.id, sessionId: session.id };
+ }
+ } else if (inbox) {
+ const agent = await db.query.agents.findFirst({
+ columns: { id: true },
+ where: and(eq(agents.slug, INBOX_SESSION_ID), buildWorkspaceWhere(scope, agents)),
+ });
+ if (agent) return { agentId: agent.id, sessionId: null };
+
+ // A hidden/trashed builtin still occupies the identity. Do not fall into
+ // builtin provisioning: its legacy adoption path is not a visibility read.
+ const occupied = await db.query.agents.findFirst({
+ columns: { id: true },
+ where: and(
+ eq(agents.slug, INBOX_SESSION_ID),
+ buildWorkspaceWhere(
+ { ...scope, includeTrashed: true },
+ {
+ userId: agents.userId,
+ workspaceId: agents.workspaceId,
+ },
+ ),
+ ),
+ });
+ if (!occupied) {
+ throw new TRPCError({
+ cause: new InboxNotProvisionedError(),
+ code: 'NOT_FOUND',
+ message: 'Inbox not provisioned',
+ });
+ }
+ }
+
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent context not found' });
+};
+
+/** Resolve database Session IDs in one scoped query, without choosing a group member. */
+export const batchResolveSessionAgentIds = async (
+ sessionIds: string[],
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId?: string,
+): Promise<Map<string, string>> => {
+ if (!sessionIds.length) return new Map();
+ const scope = { userId, workspaceId };
+ const rows = await db
+ .select({
+ agentId: agentsToSessions.agentId,
+ sessionId: sessions.id,
+ type: sessions.type,
+ visibleAgentId: agents.id,
+ })
+ .from(sessions)
+ .innerJoin(
+ agentsToSessions,
+ and(
+ eq(agentsToSessions.sessionId, sessions.id),
+ buildWorkspaceWhere(scope, agentsToSessions),
+ ),
+ )
+ .leftJoin(
+ agents,
+ and(eq(agents.id, agentsToSessions.agentId), buildWorkspaceWhere(scope, agents)),
+ )
+ .where(and(inArray(sessions.id, sessionIds), buildWorkspaceWhere(scope, sessions)));
+ const groups = new Map<string, typeof rows>();
+ for (const row of rows) groups.set(row.sessionId, [...(groups.get(row.sessionId) ?? []), row]);
+ const result = new Map<string, string>();
+ for (const [sessionId, links] of groups) {
+ if (links.length === 1 && links[0].type !== 'group' && links[0].visibleAgentId) {
+ result.set(sessionId, links[0].visibleAgentId);
+ }
+ }
+ return result;
+};
diff --git a/apps/server/src/services/trash/index.ts b/apps/server/src/services/trash/index.ts
index d9d08df73f0..326c91634e2 100644
--- a/apps/server/src/services/trash/index.ts
+++ b/apps/server/src/services/trash/index.ts
@@ -151,14 +151,17 @@ export class TrashService {
}, stamp.deletedAt);
};
- trashTopicsByAgent = async (agentId: string, options?: TrashOptions) => {
+ trashTopicsByAgent = async (
+ agentId: string,
+ options?: TrashOptions & { legacySessionId?: string | null },
+ ) => {
const stamp = this.stampOptions(options);
return this.commit(async (ctx) => {
const topics = await new TopicModel(
ctx.db,
this.userId,
this.workspaceId,
- ).softDeleteByAgentId(agentId, stamp);
+ ).softDeleteByAgentId(agentId, { ...stamp, legacySessionId: options?.legacySessionId });
return topicCascades(topics);
}, stamp.deletedAt);
};
diff --git a/packages/database/src/models/message/delete.ts b/packages/database/src/models/message/delete.ts
index 2ba93440a23..e320a0ad8d3 100644
--- a/packages/database/src/models/message/delete.ts
+++ b/packages/database/src/models/message/delete.ts
@@ -1,5 +1,5 @@
import type { ChatToolPayload } from '@lobechat/types';
-import { and, eq, inArray, not, or } from 'drizzle-orm';
+import { and, eq, inArray, isNull, not, or } from 'drizzle-orm';
import { agentsToSessions, messagePlugins, messages } from '../../schemas';
import { notShareVisitorMessage } from '../../utils/shareVisitor';
@@ -195,21 +195,31 @@ export class MessageDeleteMutations extends MessageScope {
sessionId?: string | null,
topicId?: string | null,
groupId?: string | null,
- options?: ShareVisitorWriteOptions,
+ options?: ShareVisitorWriteOptions & { agentId?: string },
) => {
const includeVisitor = options?.includeShareVisitor || this.includeShareVisitor;
const scope = includeVisitor ? this.workspaceScope() : this.ownership();
- return this.db
- .delete(messages)
- .where(
- and(
- scope,
- this.matchSession(sessionId),
- this.matchTopic(topicId),
- this.matchGroup(groupId),
- ),
- );
+ return this.db.delete(messages).where(
+ and(
+ scope,
+ // Concrete topics are authorized by the caller and may contain
+ // delegated replies from several Agents, just like topic reads.
+ topicId
+ ? undefined
+ : options?.agentId
+ ? or(
+ eq(messages.agentId, options.agentId),
+ sessionId
+ ? and(isNull(messages.agentId), eq(messages.sessionId, sessionId))
+ : undefined,
+ this.matchLegacyInbox(options.agentId),
+ )
+ : this.matchSession(sessionId),
+ this.matchTopic(topicId),
+ this.matchGroup(groupId),
+ ),
+ );
};
/**
diff --git a/packages/database/src/models/message/lookup.ts b/packages/database/src/models/message/lookup.ts
index add87317a3d..5d362353ce3 100644
--- a/packages/database/src/models/message/lookup.ts
+++ b/packages/database/src/models/message/lookup.ts
@@ -69,9 +69,10 @@ export class MessageLookupQueries extends MessageScope {
const associatedSessionId = agentSession[0]?.sessionId;
// Build condition to match both new (agentId) and legacy (sessionId) data
- return associatedSessionId
+ const agentCondition = associatedSessionId
? or(eq(messages.agentId, agentId), eq(messages.sessionId, associatedSessionId))
: eq(messages.agentId, agentId);
+ return or(agentCondition, this.matchLegacyInbox(agentId));
};
findById = async (id: string) => {
diff --git a/packages/database/src/models/message/scope.ts b/packages/database/src/models/message/scope.ts
index 30a5078a82b..c6add225426 100644
--- a/packages/database/src/models/message/scope.ts
+++ b/packages/database/src/models/message/scope.ts
@@ -1,8 +1,9 @@
import { INBOX_SESSION_ID } from '@lobechat/const';
-import { and, eq, inArray, isNull, or } from 'drizzle-orm';
+import { and, eq, exists, inArray, isNull, or } from 'drizzle-orm';
import type { FtsSearchCandidateSource } from '../../repositories/ftsSearch';
import {
+ agents,
agentsToSessions,
messagePlugins,
messages,
@@ -150,6 +151,27 @@ export class MessageScope {
// collision odds negligible at that volume.
protected genId = () => idGenerator('messages', 18);
+ /** Read and clear the same orphan history, only for the actual scoped Inbox. */
+ protected matchLegacyInbox = (agentId: string) => {
+ const inbox = this.db
+ .select({ id: agents.id })
+ .from(agents)
+ .where(
+ and(
+ eq(agents.id, agentId),
+ eq(agents.slug, INBOX_SESSION_ID),
+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agents),
+ ),
+ );
+ return and(
+ isNull(messages.agentId),
+ isNull(messages.sessionId),
+ isNull(messages.groupId),
+ isNull(messages.topicId),
+ exists(inbox),
+ );
+ };
+
protected matchSession = (sessionId?: string | null) => {
if (sessionId === INBOX_SESSION_ID) return isNull(messages.sessionId);
diff --git a/packages/database/src/models/topic/list.ts b/packages/database/src/models/topic/list.ts
index e840a4754a7..7e71079c75f 100644
--- a/packages/database/src/models/topic/list.ts
+++ b/packages/database/src/models/topic/list.ts
@@ -75,6 +75,7 @@ export const query = async (
pageSize = 9999,
groupId,
isInbox,
+ legacySessionId,
sortBy,
timing,
triggers,
@@ -270,12 +271,15 @@ export const query = async (
// inbox agent additionally adopts very old orphan rows where every owner
// column (session / group / agent) is null.
if (agentId) {
- const agentCondition = isInbox
- ? or(
- eq(topics.agentId, agentId),
- and(isNull(topics.sessionId), isNull(topics.groupId), isNull(topics.agentId)),
- )
- : eq(topics.agentId, agentId);
+ const agentCondition = or(
+ eq(topics.agentId, agentId),
+ legacySessionId
+ ? and(isNull(topics.agentId), eq(topics.sessionId, legacySessionId))
+ : undefined,
+ isInbox
+ ? and(isNull(topics.sessionId), isNull(topics.groupId), isNull(topics.agentId))
+ : undefined,
+ );
const agentWhere = and(
ctx.ownership(),
diff --git a/packages/database/src/models/topic/trash.ts b/packages/database/src/models/topic/trash.ts
index bdafc9652c0..aab66ed544e 100644
--- a/packages/database/src/models/topic/trash.ts
+++ b/packages/database/src/models/topic/trash.ts
@@ -1,12 +1,14 @@
-import { and, eq, inArray, or, type SQL } from 'drizzle-orm';
+import { INBOX_SESSION_ID } from '@lobechat/const';
+import { and, eq, exists, inArray, isNull, or, type SQL } from 'drizzle-orm';
-import { type TopicItem, topics } from '../../schemas';
+import { agents, type TopicItem, topics } from '../../schemas';
import {
isTrashed,
restoreStamp,
type SoftDeleteOptions,
trashStamp,
} from '../../utils/softDelete';
+import { buildWorkspaceWhere } from '../../utils/workspace';
import type { TopicModelContext } from './context';
/**
@@ -74,14 +76,41 @@ export const softDeleteByGroupId = async (
export const softDeleteByAgentId = async (
ctx: TopicModelContext,
agentId: string,
- options: SoftDeleteOptions,
+ options: SoftDeleteOptions & { legacySessionId?: string | null },
): Promise<TopicItem[]> => {
return ctx.db
.update(topics)
.set(trashStamp(options.deletedAt))
.where(
and(
- eq(topics.agentId, agentId),
+ or(
+ eq(topics.agentId, agentId),
+ options.legacySessionId
+ ? and(isNull(topics.agentId), eq(topics.sessionId, options.legacySessionId))
+ : undefined,
+ // Include unassigned Inbox history immediately; bulk deletion must
+ // not rely on a successful prior list-triggered migration.
+ and(
+ isNull(topics.agentId),
+ isNull(topics.sessionId),
+ isNull(topics.groupId),
+ exists(
+ ctx.db
+ .select({ id: agents.id })
+ .from(agents)
+ .where(
+ and(
+ eq(agents.id, agentId),
+ eq(agents.slug, INBOX_SESSION_ID),
+ buildWorkspaceWhere(
+ { userId: ctx.userId, workspaceId: ctx.workspaceId },
+ agents,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
options.restrictToCreator ? ctx.mine() : ctx.ownership(),
ctx.notShareVisitor(),
),
diff --git a/packages/database/src/models/topic/types.ts b/packages/database/src/models/topic/types.ts
index 27592c35080..92c4b753a38 100644
--- a/packages/database/src/models/topic/types.ts
+++ b/packages/database/src/models/topic/types.ts
@@ -161,6 +161,8 @@ export interface QueryTopicParams {
* When true, also includes legacy inbox topics (sessionId IS NULL AND groupId IS NULL AND agentId IS NULL)
*/
isInbox?: boolean;
+ /** Include unassigned legacy topics only after the caller resolves this Session to the Agent. */
+ legacySessionId?: string | null;
pageSize?: number;
/**
* Server-side ordering. Defaults to `updatedAt`. `status` orders by status
diff --git a/packages/types/src/agent/item.ts b/packages/types/src/agent/item.ts
index 130bc372fff..d70924379c0 100644
--- a/packages/types/src/agent/item.ts
+++ b/packages/types/src/agent/item.ts
@@ -141,6 +141,7 @@ export const CreateAgentSchema = z.object({
editorData: z.unknown().optional(),
fewShots: z.unknown().optional(),
marketIdentifier: z.string().nullish(),
+ metadata: z.record(z.string(), z.unknown()).nullish(),
model: z.string().nullish(),
name: z.string().nullish(),
openingMessage: z.string().nullish(),