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.

♻️ refactor(session): remove six unused legacy APIs (#21246)

Bryana810c2439a4b
diff --git a/apps/server/src/routers/lambda/__tests__/session.test.ts b/apps/server/src/routers/lambda/__tests__/session.test.ts
index 110d3669814..896b2eae01a 100644
--- a/apps/server/src/routers/lambda/__tests__/session.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/session.test.ts
@@ -1,10 +1,8 @@
// @vitest-environment node
-import { TRPCError } from '@trpc/server';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { SessionModel } from '@/database/models/session';
import { SessionGroupModel } from '@/database/models/sessionGroup';
-import { assertCanEditResource } from '@/server/services/resourcePermission';
import { sessionRouter } from '../session';
@@ -20,10 +18,6 @@ vi.mock('@/database/models/sessionGroup', () => ({
SessionGroupModel: vi.fn(),
}));
-vi.mock('@/server/services/resourcePermission', () => ({
- assertCanEditResource: vi.fn(),
-}));
-
const mockInvalidateForResources = vi.hoisted(() => vi.fn());
vi.mock('@/database/models/resourceTransferRequest', () => ({
ResourceTransferRequestModel: vi.fn(function () {
@@ -45,11 +39,9 @@ describe('sessionRouter', () => {
beforeEach(() => {
vi.clearAllMocks();
- vi.mocked(assertCanEditResource).mockResolvedValue();
sessionModelMock = {
findByIdOrSlug: vi.fn(),
- updateConfig: vi.fn().mockResolvedValue(undefined),
};
vi.mocked(SessionModel).mockImplementation(function () {
return sessionModelMock;
@@ -64,82 +56,6 @@ describe('sessionRouter', () => {
};
});
- describe('updateSessionConfig workspace edit guard', () => {
- it('requires edit on the linked agent in workspace mode', async () => {
- sessionModelMock.findByIdOrSlug.mockResolvedValue({
- agent: { id: 'agent-1' },
- id: 'session-1',
- });
-
- const caller = sessionRouter.createCaller({ ...mockCtx, workspaceId: 'ws-1' });
- await caller.updateSessionConfig({ id: 'session-1', value: { model: 'gpt-4o-mini' } });
-
- expect(assertCanEditResource).toHaveBeenCalledWith(
- expect.objectContaining({
- resourceId: 'agent-1',
- resourceType: 'agent',
- userId,
- workspaceId: 'ws-1',
- }),
- );
- expect(sessionModelMock.updateConfig).toHaveBeenCalledWith('session-1', {
- model: 'gpt-4o-mini',
- });
- });
-
- it('blocks the write when the guard denies edit', async () => {
- sessionModelMock.findByIdOrSlug.mockResolvedValue({
- agent: { id: 'agent-1' },
- id: 'session-1',
- });
- vi.mocked(assertCanEditResource).mockRejectedValue(
- new TRPCError({ code: 'FORBIDDEN', message: 'denied' }),
- );
-
- const caller = sessionRouter.createCaller({ ...mockCtx, workspaceId: 'ws-1' });
-
- await expect(
- caller.updateSessionConfig({ id: 'session-1', value: { model: 'gpt-4o-mini' } }),
- ).rejects.toMatchObject({ code: 'FORBIDDEN' });
-
- expect(sessionModelMock.updateConfig).not.toHaveBeenCalled();
- });
-
- it('skips the guard in personal mode', async () => {
- const caller = sessionRouter.createCaller(mockCtx);
- await caller.updateSessionConfig({ id: 'session-1', value: { model: 'gpt-4o-mini' } });
-
- expect(sessionModelMock.findByIdOrSlug).not.toHaveBeenCalled();
- expect(assertCanEditResource).not.toHaveBeenCalled();
- expect(sessionModelMock.updateConfig).toHaveBeenCalled();
- });
- });
-
- describe('updateSessionChatConfig workspace edit guard', () => {
- it('requires edit on the linked agent in workspace mode', async () => {
- sessionModelMock.findByIdOrSlug.mockResolvedValue({
- agent: { id: 'agent-1' },
- id: 'session-1',
- });
-
- const caller = sessionRouter.createCaller({ ...mockCtx, workspaceId: 'ws-1' });
- await caller.updateSessionChatConfig({ id: 'session-1', value: { historyCount: 4 } });
-
- expect(assertCanEditResource).toHaveBeenCalledWith(
- expect.objectContaining({
- resourceId: 'agent-1',
- resourceType: 'agent',
- userId,
- workspaceId: 'ws-1',
- }),
- );
- // The input schema fills other chatConfig defaults; only assert ours.
- expect(sessionModelMock.updateConfig).toHaveBeenCalledWith('session-1', {
- chatConfig: expect.objectContaining({ historyCount: 4 }),
- });
- });
- });
-
describe('removeSession', () => {
beforeEach(() => {
sessionModelMock.findByIdOrSlug.mockResolvedValue({
diff --git a/apps/server/src/routers/lambda/session.ts b/apps/server/src/routers/lambda/session.ts
index 21b0556b95b..6bc3b3b1073 100644
--- a/apps/server/src/routers/lambda/session.ts
+++ b/apps/server/src/routers/lambda/session.ts
@@ -10,15 +10,9 @@ import { ResourceTransferRequestModel } from '@/database/models/resourceTransfer
import { SessionModel } from '@/database/models/session';
import { SessionGroupModel } from '@/database/models/sessionGroup';
import { insertAgentSchema, insertSessionSchema } from '@/database/schemas';
-import type { LobeChatDatabase } from '@/database/type';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-import { createFtsSearchRepo } from '@/server/services/ftsSearch';
-import { assertCanEditResource } from '@/server/services/resourcePermission';
import { TrashService } from '@/server/services/trash';
-import { AgentChatConfigSchema } from '@/types/agent';
-import { LobeMetaDataSchema } from '@/types/meta';
-import { type BatchTaskResult } from '@/types/service';
import { type ChatSessionList, type LobeGroupSession } from '@/types/session';
import { TransferErrorCode } from '@/types/transferError';
@@ -27,35 +21,6 @@ import {
isWorkspaceNonOwner,
} from './_helpers/assertWorkspaceRowManageable';
-/**
- * Session config updates write through to the linked agent's config, so a
- * workspace member with view/use access must not use them as an edit
- * escalation. Resolves the session's linked agent and runs the edit guard.
- * No-op in personal mode (no workspaceId).
- */
-const assertCanEditSessionAgent = async (
- ctx: {
- serverDB: LobeChatDatabase;
- sessionModel: SessionModel;
- userId: string;
- workspaceId?: string | null;
- },
- sessionId: string,
-) => {
- if (!ctx.workspaceId) return;
-
- const session = await ctx.sessionModel.findByIdOrSlug(sessionId);
- if (!session?.agent?.id) return;
-
- await assertCanEditResource({
- db: ctx.serverDB,
- resourceId: session.agent.id,
- resourceType: 'agent',
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- });
-};
-
const sessionProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
const wsId = ctx.workspaceId ?? undefined;
@@ -68,58 +33,13 @@ const sessionProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts)
});
});
-const sessionSearchProcedure = sessionProcedure.use(async (opts) => {
- const { ctx } = opts;
- const workspaceId = ctx.workspaceId ?? undefined;
- const ftsSearchRepo = await createFtsSearchRepo({
- db: ctx.serverDB,
- userId: ctx.userId,
- usage: 'session_search',
- workspaceId,
- });
-
- return opts.next({
- ctx: {
- sessionModel: new SessionModel(ctx.serverDB, ctx.userId, workspaceId, ftsSearchRepo),
- },
- });
-});
-
/**
* @deprecated Session router is legacy. Use agent router for agent CRUD operations.
- * Session-based agent creation (createSession, batchCreateSessions) should migrate
+ * Session-based agent creation (createSession) should migrate
* to agent.createAgent which uses agentModel.create directly.
* Session query/update methods are still used by mobile but should be migrated.
*/
export const sessionRouter = router({
- /** @deprecated Use agent.createAgent instead */
- batchCreateSessions: sessionProcedure
- .use(withScopedPermission('session:create'))
- .input(
- z.array(
- z
- .object({
- config: z.object({}).passthrough(),
- group: z.string().optional(),
- id: z.string(),
- meta: LobeMetaDataSchema,
- pinned: z.boolean().optional(),
- type: z.string(),
- })
- .partial(),
- ),
- )
- .mutation(async ({ input, ctx }): Promise<BatchTaskResult> => {
- const data = await ctx.sessionModel.batchCreate(
- input.map((item) => ({
- ...item,
- ...item.meta,
- })) as any,
- );
-
- return { added: data.rowCount as number, ids: [], skips: [], success: true };
- }),
-
cloneSession: sessionProcedure
.use(withScopedPermission('session:create'))
.input(z.object({ id: z.string(), newTitle: z.string() }))
@@ -129,20 +49,6 @@ export const sessionRouter = router({
return data?.id;
}),
- countSessions: sessionProcedure
- .input(
- z
- .object({
- endDate: z.string().optional(),
- range: z.tuple([z.string(), z.string()]).optional(),
- startDate: z.string().optional(),
- })
- .optional(),
- )
- .query(async ({ ctx, input }) => {
- return ctx.sessionModel.count(input);
- }),
-
/** @deprecated Use agent.createAgent instead */
createSession: sessionProcedure
.use(withScopedPermission('session:create'))
@@ -200,19 +106,6 @@ export const sessionRouter = router({
return { sessionGroups, sessions: allSessions };
}),
- getSessions: sessionProcedure
- .input(
- z.object({
- current: z.number().optional(),
- pageSize: z.number().max(100).optional(),
- }),
- )
- .query(async ({ input, ctx }) => {
- const { current, pageSize } = input;
-
- return ctx.sessionModel.query({ current, pageSize });
- }),
-
removeSession: sessionProcedure
.use(withScopedPermission('session:delete'))
.input(z.object({ id: z.string() }))
@@ -280,12 +173,6 @@ export const sessionRouter = router({
return result;
}),
- searchSessions: sessionSearchProcedure
- .input(z.object({ keywords: z.string() }))
- .query(async ({ input, ctx }) => {
- return ctx.sessionModel.queryByKeyword(input.keywords);
- }),
-
updateSession: sessionProcedure
.use(withScopedPermission('session:update'))
.input(
@@ -300,34 +187,6 @@ export const sessionRouter = router({
return ctx.sessionModel.update(input.id, input.value);
}),
- updateSessionChatConfig: sessionProcedure
- .use(withScopedPermission('session:update'))
- .input(
- z.object({
- id: z.string(),
- value: AgentChatConfigSchema.partial(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- await assertCanEditSessionAgent(ctx, input.id);
-
- return ctx.sessionModel.updateConfig(input.id, {
- chatConfig: input.value,
- });
- }),
- updateSessionConfig: sessionProcedure
- .use(withScopedPermission('session:update'))
- .input(
- z.object({
- id: z.string(),
- value: z.object({}).passthrough().partial(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- await assertCanEditSessionAgent(ctx, input.id);
-
- return ctx.sessionModel.updateConfig(input.id, input.value);
- }),
});
export type SessionRouter = typeof sessionRouter;
diff --git a/apps/server/src/services/ftsSearch/observability.ts b/apps/server/src/services/ftsSearch/observability.ts
index 9183c3a58e3..e20bfcf233c 100644
--- a/apps/server/src/services/ftsSearch/observability.ts
+++ b/apps/server/src/services/ftsSearch/observability.ts
@@ -39,7 +39,6 @@ export type FtsSearchUsage =
| 'memory_tool'
| 'message_search'
| 'message_search_mobile'
- | 'session_search'
| 'topic_search'
| 'unattributed'
| 'unified_search';
diff --git a/docs/development/basic/feature-development.mdx b/docs/development/basic/feature-development.mdx
index 698f9039511..d9c29c860d3 100644
--- a/docs/development/basic/feature-development.mdx
+++ b/docs/development/basic/feature-development.mdx
@@ -106,37 +106,27 @@ The project is divided into multiple frontend and backend layers by responsibili
+-------------------+--------------------------------------+------------------------------------------------------+
```
-**Client Service** is frontend code that encapsulates reusable business logic, calling the backend via tRPC client. For example, `src/services/session/index.ts`:
+**Client Service** is frontend code that encapsulates reusable business logic, calling the backend via tRPC client. For agent configuration updates, see `src/services/agent.ts`:
```typescript
-export class SessionService {
- updateSessionConfig = (id: string, config: PartialDeep<LobeAgentConfig>, signal?: AbortSignal) => {
- return lambdaClient.session.updateSessionConfig.mutate({ id, value: config }, { signal });
+export class AgentService {
+ updateAgentConfig = async (
+ agentId: string,
+ config: PartialDeep<LobeAgentConfig>,
+ signal?: AbortSignal,
+ replaceWorkingDirDeviceIds: string[] = [],
+ ) => {
+ return lambdaClient.agent.updateAgentConfig.mutate(
+ { agentId, replaceWorkingDirDeviceIds, value: config },
+ { context: { showNotification: false }, signal },
+ );
};
}
```
-**tRPC Router** is the backend entry point (`apps/server/src/routers/lambda/`), validates input and calls Server Service for business logic:
+**tRPC Router** is the backend entry point. The `agent.updateAgentConfig` procedure in `apps/server/src/routers/lambda/agent/config.ts` validates the input, enforces edit permissions and workspace policies, checks collaborative edit locks, and calls `ctx.agentService.updateAgentConfig`.
-```typescript
-export const sessionRouter = router({
- updateSessionConfig: sessionProcedure
- .input(
- z.object({
- id: z.string(),
- value: z.object({}).passthrough().partial(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- const session = await ctx.sessionModel.findByIdOrSlug(input.id);
- // ...
- const mergedValue = merge(session.agent, input.value);
- return ctx.sessionModel.updateConfig(session.agent.id, mergedValue);
- }),
-});
-```
-
-For this feature, `updateSessionConfig` simply merges config without field-level granularity, so none of the layers need modification.
+Configuration changes go through the agent service using an agent ID. Check the current agent service and model implementation when adding fields; do not introduce a session-based configuration update path.
## 4. Frontend Implementation
diff --git a/docs/development/basic/feature-development.zh-CN.mdx b/docs/development/basic/feature-development.zh-CN.mdx
index 96bc27a109d..0f49e364e12 100644
--- a/docs/development/basic/feature-development.zh-CN.mdx
+++ b/docs/development/basic/feature-development.zh-CN.mdx
@@ -105,37 +105,27 @@ export interface LobeAgentConfig {
+-------------------+--------------------------------------+------------------------------------------------------+
```
-**Client Service** 是前端代码,封装可复用的业务逻辑,通过 tRPC 客户端调用后端。例如 `src/services/session/index.ts`:
+**Client Service** 是前端代码,封装可复用的业务逻辑,通过 tRPC 客户端调用后端。Agent 配置更新的实现见 `src/services/agent.ts`:
```typescript
-export class SessionService {
- updateSessionConfig = (id: string, config: PartialDeep<LobeAgentConfig>, signal?: AbortSignal) => {
- return lambdaClient.session.updateSessionConfig.mutate({ id, value: config }, { signal });
+export class AgentService {
+ updateAgentConfig = async (
+ agentId: string,
+ config: PartialDeep<LobeAgentConfig>,
+ signal?: AbortSignal,
+ replaceWorkingDirDeviceIds: string[] = [],
+ ) => {
+ return lambdaClient.agent.updateAgentConfig.mutate(
+ { agentId, replaceWorkingDirDeviceIds, value: config },
+ { context: { showNotification: false }, signal },
+ );
};
}
```
-**tRPC Router** 是后端入口(`apps/server/src/routers/lambda/`),校验输入后调用 Server Service 处理业务逻辑:
+**tRPC Router** 是后端入口。`apps/server/src/routers/lambda/agent/config.ts` 中的 `agent.updateAgentConfig` 会校验输入,执行编辑权限和工作区策略检查,检查协作编辑锁,再调用 `ctx.agentService.updateAgentConfig`。
-```typescript
-export const sessionRouter = router({
- updateSessionConfig: sessionProcedure
- .input(
- z.object({
- id: z.string(),
- value: z.object({}).passthrough().partial(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- const session = await ctx.sessionModel.findByIdOrSlug(input.id);
- // ...
- const mergedValue = merge(session.agent, input.value);
- return ctx.sessionModel.updateConfig(session.agent.id, mergedValue);
- }),
-});
-```
-
-对于本次需求,`updateSessionConfig` 只是简单 merge config,并没有细粒度到具体字段,因此各层都不需要修改。
+配置更新通过 agent service 使用 agent ID 完成。新增字段时应核对当前 agent service 和 model 的实现,不要新增基于 session 的配置更新路径。
## 四、前端实现
diff --git a/packages/database/src/models/__tests__/session.test.ts b/packages/database/src/models/__tests__/session.test.ts
index 4b3368c4332..44cd8660a8f 100644
--- a/packages/database/src/models/__tests__/session.test.ts
+++ b/packages/database/src/models/__tests__/session.test.ts
@@ -1,10 +1,9 @@
import { DEFAULT_AGENT_CONFIG } from '@lobechat/const';
-import { and, eq, inArray } from 'drizzle-orm';
-import type { LLMParams } from 'model-bank';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
-import type { NewSession, SessionItem } from '../../schemas';
+import type { SessionItem } from '../../schemas';
import {
agents,
agentsToSessions,
@@ -234,242 +233,6 @@ describe('SessionModel', () => {
});
});
- describe('count', () => {
- it('should return the count of sessions for the user', async () => {
- // Create test data
- await serverDB.insert(users).values([{ id: '456' }]);
- await serverDB.insert(sessions).values([
- { id: '1', userId },
- { id: '2', userId },
- { id: '3', userId: '456' },
- ]);
-
- // Call the count method
- const result = await sessionModel.count();
-
- // Assert results
- expect(result).toBe(2);
- });
-
- it('should return 0 if no sessions exist for the user', async () => {
- // Create test data
- await serverDB.insert(users).values([{ id: '456' }]);
- await serverDB.insert(sessions).values([{ id: '3', userId: '456' }]);
-
- // Call the count method
- const result = await sessionModel.count();
-
- // Assert results
- expect(result).toBe(0);
- });
-
- it('should count sessions with date range filter', async () => {
- await serverDB.insert(sessions).values([
- { id: 's1', userId, createdAt: new Date('2024-01-01') },
- { id: 's2', userId, createdAt: new Date('2024-06-01') },
- { id: 's3', userId, createdAt: new Date('2024-12-01') },
- ]);
-
- const rangeResult = await sessionModel.count({
- range: ['2024-03-01', '2024-09-01'],
- });
- expect(rangeResult).toBe(1);
-
- const startResult = await sessionModel.count({ startDate: '2024-05-01' });
- expect(startResult).toBe(2);
-
- const endResult = await sessionModel.count({ endDate: '2024-07-01' });
- expect(endResult).toBe(2);
- });
- });
-
- // BM25 search requires pg_search extension (ParadeDB), not available in PGlite
- const isServerDB = process.env.TEST_SERVER_DB === '1';
- describe.skipIf(!isServerDB)('queryByKeyword', () => {
- it('should return an empty array if keyword is empty', async () => {
- const result = await sessionModel.queryByKeyword('');
- expect(result).toEqual([]);
- });
-
- it('should return sessions with matching title', async () => {
- await serverDB.insert(sessions).values([
- { id: '1', userId },
- { id: '2', userId },
- ]);
-
- await serverDB.insert(agents).values([
- { id: 'agent-1', userId, model: 'gpt-3.5-turbo', title: 'Hello, Agent 1' },
- { id: 'agent-2', userId, model: 'gpt-4', title: 'Agent 2' },
- ]);
-
- await serverDB.insert(agentsToSessions).values([
- { agentId: 'agent-1', sessionId: '1', userId },
- { agentId: 'agent-2', sessionId: '2', userId },
- ]);
-
- const result = await sessionModel.queryByKeyword('hello');
- expect(result).toHaveLength(1);
- expect(result[0].id).toBe('1');
- });
-
- it('should return sessions with matching description', async () => {
- // The sessions has no title and desc,
- // see: https://github.com/lobehub/lobe-chat/pull/4725
- await serverDB.insert(sessions).values([
- { id: '1', userId },
- { id: '2', userId },
- ]);
-
- await serverDB.insert(agents).values([
- {
- id: 'agent-1',
- userId,
- model: 'gpt-3.5-turbo',
- title: 'Agent 1',
- description: 'Description with Keyword',
- },
- { id: 'agent-2', userId, model: 'gpt-4', title: 'Agent 2' },
- ]);
-
- await serverDB.insert(agentsToSessions).values([
- { agentId: 'agent-1', sessionId: '1', userId },
- { agentId: 'agent-2', sessionId: '2', userId },
- ]);
-
- const result = await sessionModel.queryByKeyword('keyword');
- expect(result).toHaveLength(1);
- expect(result[0].id).toBe('1');
- });
-
- it('should return sessions with matching title or description', async () => {
- await serverDB.insert(sessions).values([
- { id: '1', userId },
- { id: '2', userId },
- { id: '3', userId },
- ]);
-
- await serverDB.insert(agents).values([
- { id: '1', userId, title: 'Title with keyword', description: 'Some description' },
- { id: '2', userId, title: 'Another Session', description: 'Description with keyword' },
- { id: '3', userId, title: 'Third Session', description: 'Third description' },
- ]);
-
- await serverDB.insert(agentsToSessions).values([
- { agentId: '1', sessionId: '1', userId },
- { agentId: '2', sessionId: '2', userId },
- { agentId: '3', sessionId: '3', userId },
- ]);
-
- const result = await sessionModel.queryByKeyword('keyword');
- expect(result).toHaveLength(2);
- expect(result.map((s) => s.id)).toEqual(['1', '2']);
- });
- });
-
- describe('findSessionsByKeywords BM25 limit', () => {
- it('clamps the page size to the ParadeDB BM25 ceiling', async () => {
- // ParadeDB rejects `LIMIT > 8192` for BM25 (`@@@`) ordering with
- // `error: min > max. min = 9999, max = 8192`, and the error is swallowed
- // one frame below — so an over-limit "no pagination" page size returned
- // *no* matches at all instead of the top hits.
- const findMany = vi.fn().mockResolvedValue([]);
- const model = new SessionModel(
- { query: { agents: { findMany } } } as unknown as LobeChatDatabase,
- userId,
- );
-
- await model.findSessionsByKeywords({ keyword: 'hello' });
-
- expect(findMany).toHaveBeenCalledWith(expect.objectContaining({ limit: 8192 }));
- });
-
- it('keeps an explicit page size below the ceiling', async () => {
- const findMany = vi.fn().mockResolvedValue([]);
- const model = new SessionModel(
- { query: { agents: { findMany } } } as unknown as LobeChatDatabase,
- userId,
- );
-
- await model.findSessionsByKeywords({ keyword: 'hello', pageSize: 20 });
-
- expect(findMany).toHaveBeenCalledWith(expect.objectContaining({ limit: 20 }));
- });
- });
-
- describe('queryByKeyword with external candidates', () => {
- it('hydrates only current-scope sessions and surfaces candidate failures', async () => {
- await serverDB.insert(users).values({ id: 'candidate-other-user' });
- await serverDB.insert(sessions).values([
- { id: 'candidate-session-own-a', userId },
- { id: 'candidate-session-own-a-secondary', userId },
- { id: 'candidate-session-own-b', userId },
- { id: 'candidate-session-other', userId: 'candidate-other-user' },
- ]);
- await serverDB.insert(agents).values([
- { id: 'candidate-agent-own-a', title: 'Own A', userId },
- { id: 'candidate-agent-own-b', title: 'Own B', userId },
- { id: 'candidate-agent-own-unlinked', title: 'Own Unlinked', userId },
- { id: 'candidate-agent-other', title: 'Other', userId: 'candidate-other-user' },
- ]);
- await serverDB.insert(agentsToSessions).values([
- { agentId: 'candidate-agent-own-a', sessionId: 'candidate-session-own-a', userId },
- {
- agentId: 'candidate-agent-own-a',
- sessionId: 'candidate-session-own-a-secondary',
- userId,
- },
- { agentId: 'candidate-agent-own-b', sessionId: 'candidate-session-own-b', userId },
- {
- agentId: 'candidate-agent-other',
- sessionId: 'candidate-session-other',
- userId: 'candidate-other-user',
- },
- ]);
- const ftsSearchCandidates = vi.fn().mockResolvedValue({
- candidates: [
- { id: 'candidate-agent-other', score: 10 },
- { id: 'candidate-agent-deleted', score: 9 },
- { id: 'candidate-agent-own-b', score: 8 },
- { id: 'candidate-agent-own-unlinked', score: 7 },
- { id: 'candidate-agent-own-a', score: 6 },
- ],
- total: 5,
- });
- const model = new SessionModel(serverDB, userId, undefined, {
- ftsSearchCandidateEnabled: true,
- ftsSearchCandidates,
- });
-
- const result = await model.queryByKeyword('candidate');
- expect(result).toHaveLength(2);
- expect(['candidate-session-own-a', 'candidate-session-own-a-secondary']).toContain(
- result[0]?.id,
- );
- expect(result[1]?.id).toBe('candidate-session-own-b');
- await expect(
- model.findSessionsByKeywords({ current: 0, keyword: 'candidate', pageSize: 1 }),
- ).resolves.toMatchObject([
- { id: expect.stringMatching(/^candidate-session-own-a(?:-secondary)?$/) },
- ]);
- await expect(
- model.findSessionsByKeywords({ current: 1, keyword: 'candidate', pageSize: 1 }),
- ).resolves.toMatchObject([{ id: 'candidate-session-own-b' }]);
- await expect(
- model.findSessionsByKeywords({ current: 2, keyword: 'candidate', pageSize: 1 }),
- ).resolves.toEqual([]);
- expect(ftsSearchCandidates).toHaveBeenCalledWith({
- entity: 'agents',
- filters: {},
- pagination: {},
- query: { fields: ['title', 'description'], text: 'candidate' },
- });
-
- const providerError = new Error('candidate unavailable');
- ftsSearchCandidates.mockRejectedValueOnce(providerError);
- await expect(model.queryByKeyword('failure')).rejects.toBe(providerError);
- });
- });
-
describe('create', () => {
it('should create a new session', async () => {
// Call the create method
@@ -575,51 +338,6 @@ describe('SessionModel', () => {
});
});
- describe('batchCreate', () => {
- it('should batch create sessions', async () => {
- // Call the batchCreate method
- const sessions: NewSession[] = [
- {
- id: '1',
- userId,
- type: 'agent',
- // config: { model: 'gpt-3.5-turbo' },
- title: 'Session 1',
- },
- {
- id: '2',
- userId,
- type: 'agent',
- // config: { model: 'gpt-4' },
- title: 'Session 2',
- },
- ];
- const result = await sessionModel.batchCreate(sessions);
-
- // Assert results
- // pglite return affectedRows while postgres return rowCount
- expect((result as any).affectedRows || result.rowCount).toEqual(2);
- });
-
- it.skip('should set group to default if group does not exist', async () => {
- // Call the batchCreate method with a non-existent group
- const sessions: NewSession[] = [
- {
- id: '1',
- userId,
- type: 'agent',
- // config: { model: 'gpt-3.5-turbo' },
- title: 'Session 1',
- groupId: 'non-existent-group',
- },
- ];
- await sessionModel.batchCreate(sessions);
-
- // Assert results
- // expect(result[0].group).toBe('default');
- });
- });
-
describe('duplicate', () => {
it('should duplicate a session', async () => {
// Create a user and a session
@@ -864,12 +582,11 @@ describe('SessionModel', () => {
.values({ id: 'recoverable', sessionId: 'trashed-shell', userId });
};
- it('hides the shell from list, lookup and count', async () => {
+ it('hides the shell from list and lookup', async () => {
await seedTrashedShell();
expect((await sessionModel.query()).map((s) => s.id)).toEqual(['live-shell']);
expect(await sessionModel.findByIdOrSlug('trashed-shell')).toBeUndefined();
expect(await sessionModel.findByIdOrSlug('live-shell')).toBeTruthy();
- expect(await sessionModel.count()).toBe(1);
});
it('turns delete / batchDelete / update into no-ops so the recoverable topics survive', async () => {
@@ -917,7 +634,6 @@ describe('SessionModel', () => {
expect(group.id).toBe('group-shell');
expect(group.agentsToSessions.map((l: any) => l.agent.id)).toEqual(['live-member']);
expect((await sessionModel.findByIdOrSlug('group-shell'))?.agent.id).toBe('live-member');
- expect(await sessionModel.count()).toBe(1);
// still write-protected: hard-deleting it would cascade the trashed member's link away
await sessionModel.delete('group-shell');
@@ -1154,430 +870,6 @@ describe('SessionModel', () => {
});
});
- describe('updateConfig', () => {
- it('should update agent config via sessionId', async () => {
- // Create test session with agent
- const sessionId = 'test-session';
- const agentId = 'test-agent';
-
- await serverDB.transaction(async (trx) => {
- await trx.insert(sessions).values({
- id: sessionId,
- userId,
- type: 'agent',
- });
-
- await trx.insert(agents).values({
- id: agentId,
- userId,
- model: 'gpt-3.5-turbo',
- title: 'Original Title',
- description: 'Original description',
- });
-
- await trx.insert(agentsToSessions).values({
- sessionId,
- agentId,
- userId,
- });
- });
-
- // Update config using sessionId
- await sessionModel.updateConfig(sessionId, {
- model: 'gpt-4',
- title: 'Updated Title',
- description: 'New description',
- });
-
- // Verify update
- const updatedAgent = await serverDB
- .select()
- .from(agents)
- .where(and(eq(agents.id, agentId), eq(agents.userId, userId)));
-
- expect(updatedAgent[0]).toMatchObject({
- model: 'gpt-4',
- title: 'Updated Title',
- description: 'New description',
- });
- });
-
- it('should merge config with existing agent config', async () => {
- // Create test session with agent having existing config
- const sessionId = 'test-session-merge';
- const agentId = 'test-agent-merge';
-
- await serverDB.transaction(async (trx) => {
- await trx.insert(sessions).values({
- id: sessionId,
- userId,
- type: 'agent',
- });
-
- await trx.insert(agents).values({
- id: agentId,
- userId,
- model: 'gpt-3.5-turbo',
- title: 'Original Title',
- description: 'Original description',
- systemRole: 'Original role',
- });
-
- await trx.insert(agentsToSessions).values({
- sessionId,
- agentId,
- userId,
- });
- });
-
- // Update only some fields
- await sessionModel.updateConfig(sessionId, {
- model: 'gpt-4',
- title: 'Updated Title',
- // Don't update description and systemRole
- });
-
- // Verify merge behavior - updated fields changed, others preserved
- const updatedAgent = await serverDB
- .select()
- .from(agents)
- .where(and(eq(agents.id, agentId), eq(agents.userId, userId)));
-
- expect(updatedAgent[0]).toMatchObject({
- model: 'gpt-4',
- title: 'Updated Title',
- description: 'Original description', // Should be preserved
- systemRole: 'Original role', // Should be preserved
- });
- });
-
- it('should return early if session does not exist', async () => {
- // Try to update config for non-existent session
- const result = await sessionModel.updateConfig('non-existent-session', {
- model: 'gpt-4',
- title: 'Updated Title',
- });
-
- // Should return undefined/early without throwing
- expect(result).toBeUndefined();
- });
-
- it('should properly delete params when value is undefined', async () => {
- // Create test session with agent having params
- const sessionId = 'test-session-delete-params';
- const agentId = 'test-agent-delete-params';
-
- await serverDB.transaction(async (trx) => {
- await trx.insert(sessions).values({
- id: sessionId,
- userId,
- type: 'agent',
- });
-
- await trx.insert(agents).values({
- id: agentId,
- userId,
- model: 'gpt-3.5-turbo',
- title: 'Test Agent',
- params: {
- temperature: 0.7,
- top_p: 1,
- presence_penalty: 0,
- frequency_penalty: 0,
- },
- });
-
- await trx.insert(agentsToSessions).values({
- sessionId,
- agentId,
- userId,
- });
- });
-
- // Update config with temperature set to undefined (delete it)
- await sessionModel.updateConfig(sessionId, {
- params: {
- temperature: undefined,
- },
- });
-
- // Verify temperature was deleted while other params remain
- const updatedAgent = await serverDB
- .select()
- .from(agents)
- .where(and(eq(agents.id, agentId), eq(agents.userId, userId)));
-
- expect(updatedAgent[0].params).toMatchObject({
- top_p: 1,
- presence_penalty: 0,
- frequency_penalty: 0,
- });
- expect(updatedAgent[0].params).not.toHaveProperty('temperature');
- });
-
- it('should mark params as null when value is null', async () => {
- // Create test session with agent having params
- const sessionId = 'test-session-delete-params-null';
- const agentId = 'test-agent-delete-params-null';
-
- await serverDB.transaction(async (trx) => {
- await trx.insert(sessions).values({
- id: sessionId,
- userId,
- type: 'agent',
- });
-
- await trx.insert(agents).values({
- id: agentId,
- userId,
- model: 'gpt-3.5-turbo',
- title: 'Test Agent',
- params: {
- temperature: 0.7,
- top_p: 1,
- presence_penalty: 0,
- frequency_penalty: 0,
- },
- });
-
- await trx.insert(agentsToSessions).values({
- sessionId,
- agentId,
- userId,
- });
- });
-
- // Update config with temperature set to null (mark it as disabled)
- await sessionModel.updateConfig(sessionId, {
- params: {
- temperature: null,
- } as any,
- });
-
- // Verify temperature is marked as null while other params remain untouched
- const updatedAgent = await serverDB
- .select()
- .from(agents)
- .where(and(eq(agents.id, agentId), eq(agents.userId, userId)));
-
- expect(updatedAgent[0].params).toMatchObject({
- top_p: 1,
- presence_penalty: 0,
- frequency_penalty: 0,
- temperature: null,
- });
- expect((updatedAgent[0].params as LLMParams)?.temperature).toBeNull();
- });
-
- it('should throw error if session has no associated agent', async () => {
- // Create session without agent
- const sessionId = 'session-no-agent';
-
- await serverDB.insert(sessions).values({
- id: sessionId,
- userId,
- type: 'agent',
- });
-
- // Try to update config - should throw error
- await expect(
- sessionModel.updateConfig(sessionId, {
- model: 'gpt-4',
- title: 'Updated Title',
- }),
- ).rejects.toThrow(
- 'this session is not assign with agent, please contact with admin to fix this issue.',
- );
- });
-
- it('should return early if data is null or undefined', async () => {
- // Create test session with agent
- const sessionId = 'test-session-null';
- const agentId = 'test-agent-null';
-
- await serverDB.transaction(async (trx) => {
- await trx.insert(sessions).values({
- id: sessionId,
- userId,
- type: 'agent',
- });
-
- await trx.insert(agents).values({
- id: agentId,
- userId,
- model: 'gpt-3.5-turbo',
- title: 'Original Title',
- });
-
- await trx.insert(agentsToSessions).values({
- sessionId,
- agentId,
- userId,
- });
- });
-
- // Test with null data
- const result1 = await sessionModel.updateConfig(sessionId, null);
- expect(result1).toBeUndefined();
-
- // Test with undefined data
- const result2 = await sessionModel.updateConfig(sessionId, undefined);
- expect(result2).toBeUndefined();
-
- // Test with empty object
- const result3 = await sessionModel.updateConfig(sessionId, {});
- expect(result3).toBeUndefined();
- });
-
- it('should clean out undefined values from params during final cleanup', async () => {
- // This test covers the final cleanup logic that removes undefined values from params
- const sessionId = 'test-session-cleanup-undefined';
- const agentId = 'test-agent-cleanup-undefined';
-
- await serverDB.transaction(async (trx) => {
- await trx.insert(sessions).values({
- id: sessionId,
- userId,
- type: 'agent',
- });
-
- await trx.insert(agents).values({
- id: agentId,
- userId,
- model: 'gpt-3.5-turbo',
- title: 'Test Agent',
- params: {
- temperature: 0.7,
- top_p: 1,
- presence_penalty: 0,
- },
- });
-
- await trx.insert(agentsToSessions).values({
- sessionId,
- agentId,
- userId,
- });
- });
-
- // Update with some params set to undefined (delete them) and some set to new values
- await sessionModel.updateConfig(sessionId, {
- params: {
- temperature: undefined,
- presence_penalty: undefined,
- top_p: 0.9,
- },
- });
-
- // Verify: temperature and presence_penalty should be removed, top_p updated
- const updatedAgent = await serverDB
- .select()
- .from(agents)
- .where(and(eq(agents.id, agentId), eq(agents.userId, userId)));
-
- expect(updatedAgent[0].params).toEqual({ top_p: 0.9 });
- expect(updatedAgent[0].params).not.toHaveProperty('temperature');
- expect(updatedAgent[0].params).not.toHaveProperty('presence_penalty');
- });
-
- it('should set params to undefined when all param values are removed', async () => {
- // This test covers the branch where after cleanup, params object becomes empty
- // and mergedValue.params is set to undefined.
- // Note: when mergedValue.params is undefined, drizzle ORM does not update the column,
- // so the database retains the original params value.
- const sessionId = 'test-session-all-params-removed';
- const agentId = 'test-agent-all-params-removed';
-
- await serverDB.transaction(async (trx) => {
- await trx.insert(sessions).values({
- id: sessionId,
- userId,
- type: 'agent',
- });
-
- await trx.insert(agents).values({
- id: agentId,
- userId,
- model: 'gpt-3.5-turbo',
- title: 'Test Agent',
- params: {
- temperature: 0.7,
- top_p: 1,
- },
- });
-
- await trx.insert(agentsToSessions).values({
- sessionId,
- agentId,
- userId,
- });
- });
-
- // Delete ALL params by setting them to undefined
- await sessionModel.updateConfig(sessionId, {
- params: {
- temperature: undefined,
- top_p: undefined,
- },
- });
-
- // When all params are removed, mergedValue.params is set to undefined.
- // Drizzle ORM skips undefined fields in .set(), so the DB column is not modified.
- // The original params value is retained.
- const updatedAgent = await serverDB
- .select()
- .from(agents)
- .where(and(eq(agents.id, agentId), eq(agents.userId, userId)));
-
- expect(updatedAgent[0].params).toEqual({ temperature: 0.7, top_p: 1 });
- });
-
- it('should not update config for other users sessions', async () => {
- // Create agent for another user
- const sessionId = 'other-session';
- const agentId = 'other-agent';
- await serverDB.insert(users).values([{ id: 'other-user' }]);
-
- await serverDB.transaction(async (trx) => {
- await trx.insert(sessions).values({
- id: sessionId,
- userId: 'other-user',
- type: 'agent',
- });
-
- await trx.insert(agents).values({
- id: agentId,
- userId: 'other-user',
- model: 'gpt-3.5-turbo',
- title: 'Original Title',
- });
-
- await trx.insert(agentsToSessions).values({
- sessionId,
- agentId,
- userId: 'other-user',
- });
- });
-
- // Try to update other user's session - should return early
- const result = await sessionModel.updateConfig(sessionId, {
- model: 'gpt-4',
- title: 'Updated Title',
- });
-
- // Should return undefined as session doesn't belong to current user
- expect(result).toBeUndefined();
-
- // Verify no changes were made
- const agent = await serverDB.select().from(agents).where(eq(agents.id, agentId));
-
- expect(agent[0]).toMatchObject({
- model: 'gpt-3.5-turbo',
- title: 'Original Title',
- });
- });
- });
-
describe('hasMoreThanN', () => {
it('should return true when session count is more than N', async () => {
// Create test data
@@ -1631,33 +923,4 @@ describe('SessionModel', () => {
expect(result).toBe(false);
});
});
-
- describe('findSessionsByKeywords', () => {
- it('should handle errors gracefully and return empty array', async () => {
- // This test aims to cover the error-handling logic in findSessionsByKeywords
- const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
-
- // Mock the database query to throw an error
- const originalFindMany = serverDB.query.agents.findMany;
- serverDB.query.agents.findMany = vi.fn().mockRejectedValue(new Error('Database error'));
-
- const result = await sessionModel.findSessionsByKeywords({ keyword: 'test' });
-
- // Even when an error occurs, the method should return an empty array
- expect(Array.isArray(result)).toBe(true);
- expect(result).toEqual([]);
- expect(consoleSpy).toHaveBeenCalledWith('findSessionsByKeywords error:', expect.any(Error), {
- keyword: 'test',
- });
-
- // Restore original method
- serverDB.query.agents.findMany = originalFindMany;
- consoleSpy.mockRestore();
- });
-
- it('should return empty array for empty keyword', async () => {
- const result = await sessionModel.queryByKeyword('');
- expect(result).toEqual([]);
- });
- });
});
diff --git a/packages/database/src/models/agent/list.ts b/packages/database/src/models/agent/list.ts
index 77495da966b..eeff6b39ee9 100644
--- a/packages/database/src/models/agent/list.ts
+++ b/packages/database/src/models/agent/list.ts
@@ -221,9 +221,8 @@ export const queryAgents = async (
* virtual rows always excluded — so the count stays a faithful total for
* paginated callers and for the assistants stats.
* Used to report real totals (and pagination) when queryAgents is limited.
- * Accepts the same date filters as SessionModel.count so callers can compare
- * current vs. prior-period totals without falling back to the legacy
- * sessions table.
+ * Accepts date filters so callers can compare current vs. prior-period totals
+ * directly from the agents table.
*/
export const countAgents = async (
ctx: AgentModelContext,
diff --git a/packages/database/src/models/session.ts b/packages/database/src/models/session.ts
index a12d8a05572..71b81aed66f 100644
--- a/packages/database/src/models/session.ts
+++ b/packages/database/src/models/session.ts
@@ -5,33 +5,18 @@ import type {
LobeAgentSession,
LobeGroupSession,
} from '@lobechat/types';
-import { and, asc, count, desc, eq, exists, inArray, not, notExists, or, sql } from 'drizzle-orm';
+import { and, asc, desc, eq, exists, inArray, not, notExists, or } from 'drizzle-orm';
import type { PartialDeep } from 'type-fest';
import { merge } from '@/utils/merge';
-import type { FtsSearchCandidateSource } from '../repositories/ftsSearch';
import type { AgentItem, NewAgent, NewSession, SessionItem } from '../schemas';
import { agents, agentsToSessions, sessionGroups, sessions } from '../schemas';
import type { LobeChatDatabase } from '../type';
-import { sanitizeBm25Query } from '../utils/bm25';
-import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';
import { idGenerator } from '../utils/idGenerator';
-import { inJsonStringArray } from '../utils/inJsonStringArray';
import { isTrashed, notTrashed } from '../utils/softDelete';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
-/**
- * ParadeDB's BM25 (`@@@`) ordering rejects a `LIMIT` above 8192 with
- * `error: min > max. min = 9999, max = 8192`.
- *
- * A page size used as "no pagination" therefore has to be clamped instead of
- * passed through: `findSessionsByKeywords` swallows database errors, so an
- * over-limit page size does not degrade gracefully — it silently returns *no*
- * matches at all.
- */
-const BM25_MAX_LIMIT = 8192;
-
/**
* @deprecated Sessions are the legacy shell of an agent — see the `sessions`
* schema note. Reads here still exist for the mobile session list and legacy
@@ -40,19 +25,12 @@ const BM25_MAX_LIMIT = 8192;
export class SessionModel {
private userId: string;
private db: LobeChatDatabase;
- private ftsSearchCandidateSource?: FtsSearchCandidateSource;
private workspaceId?: string;
- constructor(
- db: LobeChatDatabase,
- userId: string,
- workspaceId?: string,
- ftsSearchCandidateSource?: FtsSearchCandidateSource,
- ) {
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
this.userId = userId;
this.db = db;
this.workspaceId = workspaceId;
- this.ftsSearchCandidateSource = ftsSearchCandidateSource;
}
/** Compat scope only — used for the slug-uniqueness probe in {@link create}. */
@@ -175,16 +153,6 @@ export class SessionModel {
};
};
- queryByKeyword = async (keyword: string) => {
- if (!keyword) return [];
-
- const keywordLowerCase = keyword.toLowerCase();
-
- const data = await this.findSessionsByKeywords({ keyword: keywordLowerCase });
-
- return data.map((item) => this.mapSessionItem(item as any));
- };
-
findByIdOrSlug = async (
idOrSlug: string,
): Promise<(SessionItem & { agent: AgentItem }) | undefined> => {
@@ -213,34 +181,6 @@ export class SessionModel {
return { ...result[0].session, agent: result[0].agent, group: result[0].group } as any;
};
- count = async (params?: {
- endDate?: string;
- range?: [string, string];
- startDate?: string;
- }): Promise<number> => {
- const result = await this.db
- .select({
- count: count(sessions.id),
- })
- .from(sessions)
- .where(
- genWhere([
- this.ownership(),
- params?.range
- ? genRangeWhere(params.range, sessions.createdAt, (date) => date.toDate())
- : undefined,
- params?.endDate
- ? genEndDateWhere(params.endDate, sessions.createdAt, (date) => date.toDate())
- : undefined,
- params?.startDate
- ? genStartDateWhere(params.startDate, sessions.createdAt, (date) => date.toDate())
- : undefined,
- ]),
- );
-
- return result[0].count;
- };
-
hasMoreThanN = async (n: number): Promise<boolean> => {
const result = await this.db
.select({ id: sessions.id })
@@ -408,20 +348,6 @@ export class SessionModel {
});
};
- batchCreate = async (newSessions: NewSession[]) => {
- const sessionsToInsert = newSessions.map((s) =>
- buildWorkspacePayload(
- { userId: this.userId, workspaceId: this.workspaceId },
- {
- ...s,
- id: this.genId(),
- },
- ),
- );
-
- return this.db.insert(sessions).values(sessionsToInsert);
- };
-
duplicate = async (id: string, newTitle?: string) => {
const result = await this.findByIdOrSlug(id);
@@ -620,65 +546,6 @@ export class SessionModel {
.returning();
};
- updateConfig = async (sessionId: string, data: PartialDeep<AgentItem> | undefined | null) => {
- if (!data || Object.keys(data).length === 0) return;
-
- const session = await this.findByIdOrSlug(sessionId);
- if (!session) return;
-
- if (!session.agent) {
- throw new Error(
- 'this session is not assign with agent, please contact with admin to fix this issue.',
- );
- }
-
- // First process the params field: undefined means delete, null means disable flag
- const existingParams = session.agent.params ?? {};
- const updatedParams: Record<string, any> = { ...existingParams };
-
- if (data.params) {
- const incomingParams = data.params as Record<string, any>;
- Object.keys(incomingParams).forEach((key) => {
- const incomingValue = incomingParams[key];
-
- // undefined means explicitly delete this field
- if (incomingValue === undefined) {
- delete updatedParams[key];
- return;
- }
-
- // All other values (including null) are directly overwritten, null means disable this param on the frontend
- updatedParams[key] = incomingValue;
- });
- }
-
- // Build data to be merged, excluding params (processed separately)
-
- const { params: _params, ...restData } = data;
- const mergedValue = merge(session.agent, restData);
-
- // Apply the processed parameters
- mergedValue.params = Object.keys(updatedParams).length > 0 ? updatedParams : undefined;
-
- // Final cleanup: ensure no undefined or null values enter the database
- if (mergedValue.params) {
- const params = mergedValue.params as Record<string, any>;
- Object.keys(params).forEach((key) => {
- if (params[key] === undefined) {
- delete params[key];
- }
- });
- if (Object.keys(params).length === 0) {
- mergedValue.params = undefined;
- }
- }
-
- return this.db
- .update(agents)
- .set(mergedValue)
- .where(and(eq(agents.id, session.agent.id), this.agentsOwnership()));
- };
-
// **************** Helper *************** //
private genId = () => idGenerator('sessions');
@@ -750,82 +617,4 @@ export class SessionModel {
type: 'agent',
} as LobeAgentSession;
};
-
- findSessionsByKeywords = async (params: {
- current?: number;
- keyword: string;
- pageSize?: number;
- }) => {
- const { keyword, current = 0 } = params;
- // "No pagination" must stay under ParadeDB's BM25 ceiling — see BM25_MAX_LIMIT.
- const pageSize = Math.min(params.pageSize ?? BM25_MAX_LIMIT, BM25_MAX_LIMIT);
- const offset = current * pageSize;
-
- if (this.ftsSearchCandidateSource?.ftsSearchCandidateEnabled) {
- const { candidates } = await this.ftsSearchCandidateSource.ftsSearchCandidates({
- entity: 'agents',
- filters: {},
- pagination: {},
- query: { fields: ['title', 'description'], text: keyword },
- });
- const candidateIds = candidates.map(({ id }) => id);
- if (candidateIds.length === 0) return [];
-
- const matchingAgents = await this.db
- .select({ id: agents.id })
- .from(agents)
- .where(and(this.agentsOwnership(), inJsonStringArray(agents.id, candidateIds)))
- .orderBy(asc(agents.id))
- .limit(pageSize)
- .offset(offset);
- const matchingAgentIds = matchingAgents.map(({ id }) => id);
- if (matchingAgentIds.length === 0) return [];
-
- const agentSessions = await this.db
- .select({ agentId: agentsToSessions.agentId, session: sessions })
- .from(agentsToSessions)
- .leftJoin(sessions, eq(agentsToSessions.sessionId, sessions.id))
- .where(inArray(agentsToSessions.agentId, matchingAgentIds));
- const firstSessionByAgentId = new Map<string, SessionItem>();
-
- for (const { agentId, session } of agentSessions) {
- if (session && !firstSessionByAgentId.has(agentId)) {
- firstSessionByAgentId.set(agentId, session as SessionItem);
- }
- }
-
- return matchingAgents
- .map(({ id }) => firstSessionByAgentId.get(id))
- .filter((session): session is SessionItem => session !== undefined);
- }
-
- try {
- const bm25Query = sanitizeBm25Query(keyword);
-
- const results = await this.db.query.agents.findMany({
- limit: pageSize,
- offset,
- // Keep deterministic ordering for keyword search results
- orderBy: [asc(agents.id)],
- where: and(
- this.agentsOwnership(),
- sql`(${agents.title} @@@ ${bm25Query} OR ${agents.description} @@@ ${bm25Query})`,
- ),
- with: { agentsToSessions: { columns: {}, with: { session: true } } },
- });
-
- // Filter and map results, ensuring valid session associations
- return results
- .filter((item) => item.agentsToSessions && item.agentsToSessions.length > 0)
- .map(
- (item) =>
- (item.agentsToSessions as Array<{ session: SessionItem | null | undefined }>)[0]
- ?.session,
- )
- .filter((session) => session !== null && session !== undefined);
- } catch (e) {
- console.error('findSessionsByKeywords error:', e, { keyword });
- return [];
- }
- };
}
diff --git a/packages/trpc/src/utils/errorLogger.test.ts b/packages/trpc/src/utils/errorLogger.test.ts
index 7ba03973541..da8eb55d6e2 100644
--- a/packages/trpc/src/utils/errorLogger.test.ts
+++ b/packages/trpc/src/utils/errorLogger.test.ts
@@ -29,7 +29,7 @@ describe('createTRPCErrorLogger', () => {
const onError = createTRPCErrorLogger('lambda');
const error = new TRPCError({ code: 'UNAUTHORIZED' });
- onError({ error, path: 'session.getSessions', type: 'query' });
+ onError({ error, path: 'session.getGroupedSessions', type: 'query' });
expect(console.info).not.toHaveBeenCalled();
expect(console.error).not.toHaveBeenCalled();
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 9ad90f9f458..f49eb556284 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -245,7 +245,6 @@ export const sessionKeys = {
groupId,
]),
list: def('session:list', (isLogin: boolean | undefined) => ['session:list', isLogin]),
- search: def('session:search', (keyword?: string) => ['session:search', keyword]),
};
// ---- thread -------------------------------------------------------------
@@ -612,7 +611,6 @@ export const statsKeys = {
agents: def('stats:agents', () => ['stats:agents']),
countAgents: def('stats:countAgents', () => ['stats:countAgents']),
countMessages: def('stats:countMessages', () => ['stats:countMessages']),
- countSessions: def('stats:countSessions', () => ['stats:countSessions']),
countTopics: def('stats:countTopics', () => ['stats:countTopics']),
heatmaps: def('stats:heatmaps', (type: string) => ['stats:heatmaps', type]),
maxTaskDuration: def('stats:maxTaskDuration', () => ['stats:maxTaskDuration']),
diff --git a/src/services/session/index.ts b/src/services/session/index.ts
index b832a51701a..8036e9f1fbf 100644
--- a/src/services/session/index.ts
+++ b/src/services/session/index.ts
@@ -1,12 +1,8 @@
-import { type PartialDeep } from 'type-fest';
-
import { lambdaClient } from '@/libs/trpc/client';
-import { type LobeAgentChatConfig, type LobeAgentConfig } from '@/types/agent';
-import { type MetaData } from '@/types/meta';
+import { type LobeAgentConfig } from '@/types/agent';
import {
type ChatSessionList,
type LobeAgentSession,
- type LobeSessions,
type LobeSessionType,
type SessionGroupItem,
type UpdateSessionParams,
@@ -17,11 +13,6 @@ import {
* Mobile still uses this, but should migrate to agentService.
*/
export class SessionService {
- hasSessions = async (): Promise<boolean> => {
- const result = await this.countSessions();
- return result === 0;
- };
-
/** @deprecated Use agentService.createAgent instead */
createSession = async (
type: LobeSessionType,
@@ -43,14 +34,6 @@ export class SessionService {
return lambdaClient.session.getGroupedSessions.query();
};
- countSessions = async (params?: {
- endDate?: string;
- range?: [string, string];
- startDate?: string;
- }): Promise<number> => {
- return lambdaClient.session.countSessions.query(params);
- };
-
updateSession = (id: string, data: Partial<UpdateSessionParams>) => {
const { group, pinned, meta, updatedAt } = data;
return lambdaClient.session.updateSession.mutate({
@@ -65,36 +48,6 @@ export class SessionService {
return lambdaClient.agent.getAgentConfig.query({ sessionId: id });
};
- updateSessionConfig = (
- id: string,
- config: PartialDeep<LobeAgentConfig>,
- signal?: AbortSignal,
- ) => {
- return lambdaClient.session.updateSessionConfig.mutate(
- { id, value: config },
- {
- context: { showNotification: false },
- signal,
- },
- );
- };
-
- updateSessionMeta = (id: string, meta: Partial<MetaData>, signal?: AbortSignal) => {
- return lambdaClient.session.updateSessionConfig.mutate({ id, value: meta }, { signal });
- };
-
- updateSessionChatConfig = (
- id: string,
- value: Partial<LobeAgentChatConfig>,
- signal?: AbortSignal,
- ) => {
- return lambdaClient.session.updateSessionChatConfig.mutate({ id, value }, { signal });
- };
-
- searchSessions = (keywords: string): Promise<LobeSessions> => {
- return lambdaClient.session.searchSessions.query({ keywords });
- };
-
removeSession = (id: string) => {
return lambdaClient.session.removeSession.mutate({ id });
};
diff --git a/src/store/session/slices/session/action.test.ts b/src/store/session/slices/session/action.test.ts
index bdf1c728e2f..fad85ecc0f4 100644
--- a/src/store/session/slices/session/action.test.ts
+++ b/src/store/session/slices/session/action.test.ts
@@ -16,10 +16,8 @@ vi.mock('@/services/session', () => ({
cloneSession: vi.fn(),
updateSessionGroup: vi.fn(),
removeSession: vi.fn(),
- getAllSessions: vi.fn(),
updateSession: vi.fn(),
updateSessionGroupId: vi.fn(),
- searchSessions: vi.fn(),
updateSessionPinned: vi.fn(),
},
}));
diff --git a/src/store/session/slices/session/action.ts b/src/store/session/slices/session/action.ts
index 8edd03b907c..4abeec69309 100644
--- a/src/store/session/slices/session/action.ts
+++ b/src/store/session/slices/session/action.ts
@@ -2,7 +2,6 @@ import { toast } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import { t } from 'i18next';
import { type SWRResponse } from 'swr';
-import useSWR from 'swr';
import { type PartialDeep } from 'type-fest';
import { DEFAULT_AGENT_LOBE_SESSION, INBOX_SESSION_ID } from '@/const/session';
@@ -267,18 +266,6 @@ export class SessionActionImpl {
);
};
- useSearchSessions = (keyword?: string): SWRResponse<any> => {
- return useSWR<LobeSessions>(
- sessionKeys.search(keyword),
- async () => {
- if (!keyword) return [];
-
- return sessionService.searchSessions(keyword);
- },
- { revalidateOnFocus: false, revalidateOnMount: false },
- );
- };
-
internal_dispatchSessions = (payload: SessionDispatch): void => {
const nextSessions = sessionsReducer(this.#get().sessions, payload);
this.#get().internal_processSessions(nextSessions, this.#get().sessionGroups);
diff --git a/src/store/session/slices/session/initialState.ts b/src/store/session/slices/session/initialState.ts
index 3b4a127fbb9..b61f632530a 100644
--- a/src/store/session/slices/session/initialState.ts
+++ b/src/store/session/slices/session/initialState.ts
@@ -20,7 +20,6 @@ export interface SessionState {
isSearching: boolean;
isSessionsFirstFetchFinished: boolean;
pinnedSessions: LobeSessions;
- searchKeywords: string;
/**
* @title Session ID being renamed
* @description Used to control the display state of the session rename modal
@@ -46,7 +45,6 @@ export const initialSessionState: SessionState = {
isSearching: false,
isSessionsFirstFetchFinished: false,
pinnedSessions: [],
- searchKeywords: '',
sessionRenamingId: null,
sessionUpdatingId: null,
sessions: [],