🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor: remove unused legacy session APIs (#21360)
Bryane164162a6654
diff --git a/.agents/acceptance/references/probe-field-notes.md b/.agents/acceptance/references/probe-field-notes.mdindex 27ed4732fd7..aa973801700 100644--- a/.agents/acceptance/references/probe-field-notes.md+++ b/.agents/acceptance/references/probe-field-notes.md@@ -603,9 +603,15 @@ executionTarget: 'local'` in `agencyConfig`) + one message per case asking CC to});await d.updateDeviceCwd(did, entry, { setDefault: false }); // so the entry exists → sourcePath resolves```- Create a throwaway agent with `agent().createAgent({ title })` and delete it afterwards with- `session().removeSession(agentId)` (there is no `deleteAgent` on the agent store) plus- `device().removeDeviceWorkingDir(did, path)` — otherwise the fixture cwd lingers in the real account.+ Create a throwaway agent with `agent().createAgent({ title })`. Afterwards, clean up both the agent+ and its device working directory:+ ```js+ await window.__LOBE_STORES.home().removeAgent(agentId);+ await window.__LOBE_STORES.device().removeDeviceWorkingDir(did, path);+ ```+ Agent deletion lives on the home store and refreshes the agent list and evicts its message cache.+ Removing the device working directory separately prevents the fixture cwd from lingering in the real+ account.- **Identify icons precisely**: lucide renders `svg.lucide.lucide-git-fork`. Several git icons live in thesame bar (the dir picker's `DirIcon` is `git-branch`, the review toggle is `git-compare`), so scope theassertion to the trigger: `document.querySelector('[role=button][aria-label="Worktrees"]') svg`, anddiff --git a/apps/server/src/routers/lambda/__tests__/session.test.ts b/apps/server/src/routers/lambda/__tests__/session.test.tsdeleted file mode 100644index 896b2eae01a..00000000000--- a/apps/server/src/routers/lambda/__tests__/session.test.ts+++ /dev/null@@ -1,106 +0,0 @@-// @vitest-environment node-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { SessionModel } from '@/database/models/session';-import { SessionGroupModel } from '@/database/models/sessionGroup';--import { sessionRouter } from '../session';--vi.mock('@/database/core/db-adaptor', () => ({- getServerDB: vi.fn(async () => ({})),-}));--vi.mock('@/database/models/session', () => ({- SessionModel: vi.fn(),-}));--vi.mock('@/database/models/sessionGroup', () => ({- SessionGroupModel: vi.fn(),-}));--const mockInvalidateForResources = vi.hoisted(() => vi.fn());-vi.mock('@/database/models/resourceTransferRequest', () => ({- ResourceTransferRequestModel: vi.fn(function () {- return { invalidateForResources: mockInvalidateForResources };- }),-}));--const mockTrashAgent = vi.hoisted(() => vi.fn());-vi.mock('@/server/services/trash', () => ({- TrashService: vi.fn(function () {- return { trashAgent: mockTrashAgent };- }),-}));--describe('sessionRouter', () => {- const userId = 'testUserId';- let sessionModelMock: any;- let mockCtx: any;-- beforeEach(() => {- vi.clearAllMocks();-- sessionModelMock = {- findByIdOrSlug: vi.fn(),- };- vi.mocked(SessionModel).mockImplementation(function () {- return sessionModelMock;- });- vi.mocked(SessionGroupModel).mockImplementation(function () {- return {} as any;- });-- mockCtx = {- jwtPayload: { userId },- userId,- };- });-- describe('removeSession', () => {- beforeEach(() => {- sessionModelMock.findByIdOrSlug.mockResolvedValue({- agent: { id: 'agent-1' },- id: 'session-1',- userId,- });- sessionModelMock.delete = vi- .fn()- .mockResolvedValue({ orphanedAgentIds: [], result: { count: 1 } });- sessionModelMock.isSoleShellOfAgent = vi.fn();- });-- it("sends the agent to the recycle bin when this is the agent's only session", async () => {- sessionModelMock.isSoleShellOfAgent.mockResolvedValue(true);-- const caller = sessionRouter.createCaller(mockCtx);- await caller.removeSession({ id: 'session-1' });-- expect(sessionModelMock.isSoleShellOfAgent).toHaveBeenCalledWith('session-1', 'agent-1');- expect(mockTrashAgent).toHaveBeenCalledWith('agent-1');- expect(sessionModelMock.delete).not.toHaveBeenCalled();- });-- // The session-delete path trashes the agent too, so it must void a pending- // handover exactly like `agent.removeAgent` — otherwise the recipient could- // still accept ownership of recycle-bin content.- it('voids pending transfers of the agent it sends to the recycle bin', async () => {- sessionModelMock.isSoleShellOfAgent.mockResolvedValue(true);-- const caller = sessionRouter.createCaller({ ...mockCtx, workspaceId: 'ws-1' });- await caller.removeSession({ id: 'session-1' });-- expect(mockTrashAgent).toHaveBeenCalledWith('agent-1');- expect(mockInvalidateForResources).toHaveBeenCalledWith('agent', ['agent-1']);- });-- it('removes only this session when the agent is linked to other sessions', async () => {- sessionModelMock.isSoleShellOfAgent.mockResolvedValue(false);-- const caller = sessionRouter.createCaller(mockCtx);- await caller.removeSession({ id: 'session-1' });-- expect(mockTrashAgent).not.toHaveBeenCalled();- expect(sessionModelMock.delete).toHaveBeenCalledWith('session-1');- });- });-});diff --git a/apps/server/src/routers/lambda/session.ts b/apps/server/src/routers/lambda/session.tsindex 6bc3b3b1073..7fed993fc92 100644--- a/apps/server/src/routers/lambda/session.ts+++ b/apps/server/src/routers/lambda/session.ts@@ -1,25 +1,13 @@-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 { AgentModel } from '@/database/models/agent';-import { ChatGroupModel } from '@/database/models/chatGroup';-import { ResourcePermissionModel } from '@/database/models/resourcePermission';-import { ResourceTransferRequestModel } from '@/database/models/resourceTransferRequest';import { SessionModel } from '@/database/models/session';-import { SessionGroupModel } from '@/database/models/sessionGroup';import { insertAgentSchema, insertSessionSchema } from '@/database/schemas';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';-import { TrashService } from '@/server/services/trash';-import { type ChatSessionList, type LobeGroupSession } from '@/types/session';-import { TransferErrorCode } from '@/types/transferError';-import {- assertWorkspaceRowManageable,- isWorkspaceNonOwner,-} from './_helpers/assertWorkspaceRowManageable';+import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';const sessionProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;@@ -27,7 +15,6 @@ const sessionProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts)return opts.next({ctx: {- sessionGroupModel: new SessionGroupModel(ctx.serverDB, ctx.userId, wsId),sessionModel: new SessionModel(ctx.serverDB, ctx.userId, wsId),},});@@ -37,18 +24,9 @@ const sessionProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts)* @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.- * Session query/update methods are still used by mobile but should be migrated.+ * Retains legacy session creation and session-shell updates for compatibility.*/export const sessionRouter = router({- cloneSession: sessionProcedure- .use(withScopedPermission('session:create'))- .input(z.object({ id: z.string(), newTitle: z.string() }))- .mutation(async ({ input, ctx }) => {- const data = await ctx.sessionModel.duplicate(input.id, input.newTitle);-- return data?.id;- }),-/** @deprecated Use agent.createAgent instead */createSession: sessionProcedure.use(withScopedPermission('session:create'))@@ -75,104 +53,6 @@ export const sessionRouter = router({return data.id;}),- getGroupedSessions: wsCompatProcedure- .use(serverDatabase)- .query(async ({ ctx }): Promise<ChatSessionList> => {- const userId = ctx.userId;- const serverDB = ctx.serverDB;- const wsId = ctx.workspaceId ?? undefined;- const sessionModel = new SessionModel(serverDB, userId, wsId);- const chatGroupModel = new ChatGroupModel(serverDB, userId, wsId);-- const [{ sessions, sessionGroups }, chatGroups] = await Promise.all([- sessionModel.queryWithGroups(),- chatGroupModel.queryWithMemberDetails(),- ]);-- const groupSessions: LobeGroupSession[] = chatGroups.map((group) => {- const { title, description, avatar, backgroundColor, groupId, ...rest } = group;- return {- ...rest,- group: groupId, // Map groupId to group for consistent API- meta: { avatar, backgroundColor, description, title },- type: 'group',- };- });-- const allSessions = [...sessions, ...groupSessions].sort(- (a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime(),- );-- return { sessionGroups, sessions: allSessions };- }),-- removeSession: sessionProcedure- .use(withScopedPermission('session:delete'))- .input(z.object({ id: z.string() }))- .mutation(async ({ input, ctx }) => {- const session = await ctx.sessionModel.findByIdOrSlug(input.id);- if (session) assertWorkspaceRowManageable(ctx, session.userId, 'session');-- // Deleting the last session of a workspace-shared agent orphan-deletes- // the agent itself, and the session cascade erases every member's- // topics/messages on it — the same blast radius as `agent.removeAgent`,- // so apply the same foreign-rows owner gate here.- if (- ctx.workspaceId &&- session?.agent &&- session.agent.visibility === 'public' &&- isWorkspaceNonOwner(ctx)- ) {- const agentModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- if (await agentModel.transferHasForeignRows(session.agent.id)) {- throw new TRPCError({- cause: { data: { code: TransferErrorCode.OwnerOnly } },- code: 'FORBIDDEN',- message:- "Only workspace owners can delete a session whose shared agent carries others' conversations",- });- }- }-- // A session is normally the legacy 1:1 shell of an agent: removing it- // means removing the agent, so route through the agent's recycle-bin- // cascade (agent + session + topics all stamped, restorable as one unit).- // When the agent has other shells (or this shell holds other agents),- // only this session goes — the agent must stay with its other sessions.- if (- session?.agent &&- (await ctx.sessionModel.isSoleShellOfAgent(session.id, session.agent.id))- ) {- const trashService = new TrashService(- ctx.serverDB,- ctx.userId,- ctx.workspaceId ?? undefined,- );- const trashed = await trashService.trashAgent(session.agent.id);- // Same as `agent.removeAgent`: the trashed agent is invisible to a- // pending handover's recipient too, so an acceptance would move- // ownership of recycle-bin content — void it now.- if (ctx.workspaceId) {- await new ResourceTransferRequestModel(- ctx.serverDB,- ctx.workspaceId,- ).invalidateForResources('agent', [session.agent.id]);- }- return trashed;- }-- // No linked agent (a stray legacy row) or a shell the agent does not- // depend on: hard delete this session only, as before. An agent left- // without any shell is orphan-deleted by the model.- const { orphanedAgentIds, result } = await ctx.sessionModel.delete(input.id);- if (ctx.workspaceId && orphanedAgentIds.length > 0) {- const permissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);- await Promise.all(orphanedAgentIds.map((id) => permissionModel.removeAll('agent', id)));- }-- return result;- }),-updateSession: sessionProcedure.use(withScopedPermission('session:update')).input(diff --git a/docs/development/soft-delete-recycle-bin-design.md b/docs/development/soft-delete-recycle-bin-design.mdindex e9e709423b1..6145c596561 100644--- a/docs/development/soft-delete-recycle-bin-design.md+++ b/docs/development/soft-delete-recycle-bin-design.md@@ -173,7 +173,7 @@ delete stopped:| Root | Stamped + registered as children | Stamped, not registered (restored by parent key) | Hidden by parent only (no stamp) || ----------------- | ------------------------------------------------------------------------------------- | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |-| `topic` | — (phase 2: attachments only this topic references, when `removeFiles`) | — | messages, threads, comments, topic\_documents |+| `topic` | — (phase 2: attachments only this topic references, when `removeFiles`) | — | messages, threads, comments, topic_documents || `agent` | topics (via `agent_id` and via legacy `session_id`) | — | everything under topics; the legacy `sessions` shell (hidden through the agent join, hard-deleted at purge) || `message` | tool-result companions of a trashed assistant turn | — | plugins / tts / translate rows || `chatGroup` | topics (group + owned virtual member agents) | owned virtual member agents | — |@@ -214,9 +214,9 @@ session groups …) were given an `isDeleted` entry. Raw-SQL scopes (`TaskModel.Restore / purge internals pass `includeTrashed: true`. Each trash-aware model exposes a `scope()`(no filter) next to its `ownership()` (filter) so those internals are explicit and greppable.-Consequence to keep in mind: a relational query that reuses another table's predicate-(`db.query.sessionGroups.findMany({ where: sessionsPredicate })`) now fails loudly instead of-silently rebinding — one such case in `SessionModel.queryWithGroups` was fixed.+Relational queries must use predicates built for the table being queried. A `sessionGroups`+query must use a predicate built from `sessionGroups`, rather than one built from `sessions`;+cross-table predicate reuse now fails instead of silently rebinding.### 2.5 Server architecture@@ -232,7 +232,7 @@ packages/database/src/models/trash.ts TrashModel — registry reads/wri- `TrashService.trashXxx` runs the handler's stamping and the registry insert **in onetransaction**, so rows can never end up hidden but unlisted.- Every user-facing delete procedure in scope (phase 1: `topic.removeTopic`/`batchDelete*`/- `removeAllTopics`, `agent.removeAgent`, `session.removeSession`, `message.removeMessage(s)` via+ `removeAllTopics`, `agent.removeAgent`, `message.removeMessage(s)` via`MessageService`; phase 2 adds `group.deleteGroup`, `document.deleteDocument(s)`,`notebook.deleteDocument`, `file.removeFile(s)`, `knowledgeBase.removeKnowledgeBase`,`project.delete`, `task.delete`/`deleteGoal`, `generationTopic.deleteTopic`) keeps its permissiondiff --git a/docs/development/state-management/state-management-intro.mdx b/docs/development/state-management/state-management-intro.mdxindex 2186470996b..2988262d90c 100644--- a/docs/development/state-management/state-management-intro.mdx+++ b/docs/development/state-management/state-management-intro.mdx@@ -155,7 +155,7 @@ src/store/session## Implementation of SessionStore-In LobeHub, the SessionStore is designed as the core module for managing session state and logic. It consists of multiple Slices, with each Slice managing a relevant portion of state and logic. Below is a simplified example of the SessionStore implementation:+The legacy SessionStore retains selection/UI state and compatibility actions. Its slices group related behavior. The following simplified example shows how action classes are composed into the store:### store.ts@@ -195,32 +195,41 @@ export const useSessionStore = createWithEqualityFn<SessionStore>()();```-In this `store.ts` file, we create a `useSessionStore` hook that uses the `zustand` library to create a global state manager. We merge the initialState with the actions from each Slice — via the shared `flattenActions` helper — to create a complete SessionStore. Note there is no `persist` middleware here: SessionStore data is fetched from the server via SWR, not persisted to local storage.+In this `store.ts` file, we create a `useSessionStore` hook that uses the `zustand` library to create a global state manager. We merge the initialState with the actions from each Slice — via the shared `flattenActions` helper — to create a complete SessionStore. The legacy SessionStore manages session selection and UI state. Agent/sidebar lists are loaded and cached by [HomeStore’s replica-backed Agent list](https://github.com/lobehub/lobehub/blob/canary/src/store/home/slices/agentList/action.ts).### slices/session/action.ts-```ts-import { type SWRResponse } from 'swr';+The action slice below shows the existing `switchSession` action. It checks the active Agent ID and updates `activeAgentId` through a labeled state write.+```tsimport { type SessionStore } from '@/store/session';import { type StoreSetter } from '@/store/types';+import { setNamespace } from '@/utils/storeDebug';-export interface SessionAction {- /**- * A custom hook that uses SWR to fetch sessions data.- */- useFetchSessions: () => SWRResponse<any>;-}+const n = setNamespace('session');type Setter = StoreSetter<SessionStore>;-export const createSessionSlice = (set: Setter, get: () => SessionStore): SessionAction => ({- useFetchSessions: () => {- // ...logic for initializing sessions- },- // ...implementation of other actions-});-```+export const createSessionSlice = (set: Setter, get: () => SessionStore, _api?: unknown) =>+ new SessionActionImpl(set, get, _api);++export class SessionActionImpl {+ readonly #get: () => SessionStore;+ readonly #set: Setter;-In the `action.ts` file, we define a `SessionAction` interface to describe session-related actions and implement a `useFetchSessions` function to create these actions. Then, we merge these actions with the initial state to form the session-related Slice.+ constructor(set: Setter, get: () => SessionStore, _api?: unknown) {+ void _api;+ this.#set = set;+ this.#get = get;+ }++ switchSession = (sessionId: string): void => {+ if (this.#get().activeAgentId === sessionId) return;++ this.#set({ activeAgentId: sessionId }, false, n(`activeSession/${sessionId}`));+ };+}++export type SessionAction = Pick<SessionActionImpl, keyof SessionActionImpl>;+```-Through this layered and modular approach, we can ensure that LobeHub's SessionStore is clear, maintainable, and easy to extend and test.+`createSessionSlice` returns an action-class instance. `flattenActions` exposes its public methods on the legacy store, and `SessionAction` is inferred from those methods. List loading and persistence belong to the owning list resource; this selection action only changes UI state.diff --git a/docs/development/state-management/state-management-intro.zh-CN.mdx b/docs/development/state-management/state-management-intro.zh-CN.mdxindex 14acdfe9055..d08c0652757 100644--- a/docs/development/state-management/state-management-intro.zh-CN.mdx+++ b/docs/development/state-management/state-management-intro.zh-CN.mdx@@ -153,7 +153,7 @@ src/store/session## SessionStore 的实现-在 LobeHub 中,SessionStore 被设计为管理会话状态和逻辑的核心模块。它由多个 Slices 组成,每个 Slice 管理一部分相关的状态和逻辑。下面是一个简化的 SessionStore 的实现示例:+旧 SessionStore 保留会话选择、界面状态和兼容动作,各个 Slice 负责相关的一组行为。下面用简化示例说明如何将动作类组合进 store:### store.ts@@ -193,32 +193,41 @@ export const useSessionStore = createWithEqualityFn<SessionStore>()();```-在这个 `store.ts` 文件中,我们创建了一个 `useSessionStore` 钩子,它使用 `zustand` 库来创建一个全局状态管理器。我们通过共享的 `flattenActions` 工具函数,将 initialState 和每个 Slice 的动作合并,以创建完整的 SessionStore。这里没有使用 `persist` 中间件:SessionStore 的数据通过 SWR 从服务端获取,而不是持久化到本地存储。+在这个 `store.ts` 文件中,我们创建了一个 `useSessionStore` 钩子,它使用 `zustand` 库来创建一个全局状态管理器。我们通过共享的 `flattenActions` 工具函数,将 initialState 和每个 Slice 的动作合并,以创建完整的 SessionStore。旧 SessionStore 管理会话选择和界面状态。Agent 与侧边栏列表由 [HomeStore 中基于 replica 的 Agent 列表](https://github.com/lobehub/lobehub/blob/canary/src/store/home/slices/agentList/action.ts)负责加载和缓存。### slices/session/action.ts-```ts-import { type SWRResponse } from 'swr';+下面的动作切片展示现有的 `switchSession` 动作:检查当前 Agent ID,然后通过带调试标签的状态写入更新 `activeAgentId`。+```tsimport { type SessionStore } from '@/store/session';import { type StoreSetter } from '@/store/types';+import { setNamespace } from '@/utils/storeDebug';-export interface SessionAction {- /**- * A custom hook that uses SWR to fetch sessions data.- */- useFetchSessions: () => SWRResponse<any>;-}+const n = setNamespace('session');type Setter = StoreSetter<SessionStore>;-export const createSessionSlice = (set: Setter, get: () => SessionStore): SessionAction => ({- useFetchSessions: () => {- // ...初始化会话的逻辑- },- // ...其他动作的实现-});-```+export const createSessionSlice = (set: Setter, get: () => SessionStore, _api?: unknown) =>+ new SessionActionImpl(set, get, _api);++export class SessionActionImpl {+ readonly #get: () => SessionStore;+ readonly #set: Setter;-在 `action.ts` 文件中,我们定义了一个 `SessionAction` 接口来描述会话相关的动作,并且实现了一个 `useFetchSessions` 函数来创建这些动作。然后,我们将这些动作与初始状态合并,以形成会话相关的 Slice。+ constructor(set: Setter, get: () => SessionStore, _api?: unknown) {+ void _api;+ this.#set = set;+ this.#get = get;+ }++ switchSession = (sessionId: string): void => {+ if (this.#get().activeAgentId === sessionId) return;++ this.#set({ activeAgentId: sessionId }, false, n(`activeSession/${sessionId}`));+ };+}++export type SessionAction = Pick<SessionActionImpl, keyof SessionActionImpl>;+```-通过这种结构分层和模块化的方法,我们可以确保 LobeHub 的 SessionStore 是清晰、可维护的,同时也便于扩展和测试。+`createSessionSlice` 返回动作类实例,`flattenActions` 将它的公开方法暴露到旧 store 上,`SessionAction` 则由这些方法推导。列表加载和持久化由对应的列表资源负责;这个选择动作只更新界面状态。diff --git a/docs/development/tests/integration-testing.mdx b/docs/development/tests/integration-testing.mdxindex d8668dbbb59..f74097c735b 100644--- a/docs/development/tests/integration-testing.mdx+++ b/docs/development/tests/integration-testing.mdx@@ -164,27 +164,38 @@ it('should create message with correct associations', async () => {#### 2. Test Cascading Operations+Agent deletion moves the Agent and related content to the recycle bin. Verify the soft-delete state+instead of expecting database rows to disappear; physical cascading deletion happens during purge.+This example uses a message without a Topic, which receives its own soft-delete stamp.++Use the shared database/user setup above and mock `getServerDB` to return that database, as in+[the Message Router integration suite](https://github.com/lobehub/lobehub/blob/canary/apps/server/src/routers/lambda/__tests__/integration/message.integration.test.ts).+```typescript-it('should cascade delete messages when session is deleted', async () => {- const sessionCaller = sessionRouter.createCaller(createTestContext(userId));+import { agents } from '@lobechat/database/schemas';++import { agentRouter } from '../../agent';++it('should trash an agent with its topicless messages', async () => {+ const agentCaller = agentRouter.createCaller(createTestContext(userId));const messageCaller = messageRouter.createCaller(createTestContext(userId));- // Create session and messages- const sessionId = await sessionCaller.createSession({- /* ... */+ // Create an Agent and a message without a Topic+ const { agentId } = await agentCaller.createAgent({ config: { title: 'Cascade test' } });+ const { id: messageId } = await messageCaller.createMessage({+ agentId,+ content: 'Test message',+ role: 'user',});- await messageCaller.createMessage({ sessionId /* ... */ });- // Delete session- await sessionCaller.removeSession({ id: sessionId });+ await agentCaller.removeAgent({ agentId });- // ✅ Verify related messages are also deleted- const remainingMessages = await serverDB- .select()- .from(messages)- .where(eq(messages.sessionId, sessionId));+ // Verify both rows remain in the database with soft-delete stamps+ const [agent] = await serverDB.select().from(agents).where(eq(agents.id, agentId));+ const [message] = await serverDB.select().from(messages).where(eq(messages.id, messageId));- expect(remainingMessages).toHaveLength(0);+ expect(agent).toMatchObject({ id: agentId, isDeleted: true });+ expect(message).toMatchObject({ agentId, isDeleted: true, topicId: null });});```@@ -287,7 +298,7 @@ Use clear names to describe the test's intent:```typescript// ✅ Good namingit('should create message with correct sessionId and topicId');-it('should cascade delete messages when session is deleted');+it('should trash an agent with its topicless messages');it('should prevent cross-user access to messages');// ❌ Poor naming@@ -324,7 +335,7 @@ it('test delete');- ✅ Cross-layer ID propagation (sessionId, topicId, containerId, threadId)- ✅ Permission checks (users can only access their own resources)-- ✅ Cascading deletes (deleting a session also deletes related data)+- ✅ Cascading operations (trashing an Agent also hides related content; purge deletes it)- ✅ Foreign key constraints (cannot create associations to non-existent records)### Priority P1 (Should Cover)diff --git a/docs/development/tests/integration-testing.zh-CN.mdx b/docs/development/tests/integration-testing.zh-CN.mdxindex 38fd462a361..00f11286a42 100644--- a/docs/development/tests/integration-testing.zh-CN.mdx+++ b/docs/development/tests/integration-testing.zh-CN.mdx@@ -163,27 +163,36 @@ it('should create message with correct associations', async () => {#### 2. 测试级联操作+删除 Agent 会将 Agent 和关联内容移入回收站。应验证软删除状态,而不是断言数据库行已经消失;物理级联删除发生在永久清除时。此示例使用不属于任何 Topic 的消息,因为这类消息会直接标记为软删除。++使用上面的共享数据库和用户初始化步骤,并 mock `getServerDB`,使其返回该测试数据库,具体方式参见+[Message Router 集成测试](https://github.com/lobehub/lobehub/blob/canary/apps/server/src/routers/lambda/__tests__/integration/message.integration.test.ts)。+```typescript-it('should cascade delete messages when session is deleted', async () => {- const sessionCaller = sessionRouter.createCaller(createTestContext(userId));+import { agents } from '@lobechat/database/schemas';++import { agentRouter } from '../../agent';++it('should trash an agent with its topicless messages', async () => {+ const agentCaller = agentRouter.createCaller(createTestContext(userId));const messageCaller = messageRouter.createCaller(createTestContext(userId));- // 创建 session 和 messages- const sessionId = await sessionCaller.createSession({- /* ... */+ // 创建 Agent 和不属于任何 Topic 的消息+ const { agentId } = await agentCaller.createAgent({ config: { title: 'Cascade test' } });+ const { id: messageId } = await messageCaller.createMessage({+ agentId,+ content: 'Test message',+ role: 'user',});- await messageCaller.createMessage({ sessionId /* ... */ });- // 删除 session- await sessionCaller.removeSession({ id: sessionId });+ await agentCaller.removeAgent({ agentId });- // ✅ 验证相关消息也被删除- const remainingMessages = await serverDB- .select()- .from(messages)- .where(eq(messages.sessionId, sessionId));+ // 验证两行数据仍在数据库中,并已标记为软删除+ const [agent] = await serverDB.select().from(agents).where(eq(agents.id, agentId));+ const [message] = await serverDB.select().from(messages).where(eq(messages.id, messageId));- expect(remainingMessages).toHaveLength(0);+ expect(agent).toMatchObject({ id: agentId, isDeleted: true });+ expect(message).toMatchObject({ agentId, isDeleted: true, topicId: null });});```@@ -286,7 +295,7 @@ afterEach(async () => {```typescript// ✅ 好的命名it('should create message with correct sessionId and topicId');-it('should cascade delete messages when session is deleted');+it('should trash an agent with its topicless messages');it('should prevent cross-user access to messages');// ❌ 不好的命名@@ -323,7 +332,7 @@ it('test delete');- ✅ 跨层级的 ID 传递(sessionId、topicId、containerId、threadId)- ✅ 权限验证(用户只能访问自己的资源)-- ✅ 级联删除(删除 session 时相关数据也删除)+- ✅ 级联操作(删除 Agent 时隐藏关联内容,永久清除时删除数据)- ✅ 外键约束(不能创建不存在的关联)### 优先级 P1(应该覆盖)diff --git a/packages/database/src/models/__tests__/session.test.ts b/packages/database/src/models/__tests__/session.test.tsindex 44cd8660a8f..96e22407e09 100644--- a/packages/database/src/models/__tests__/session.test.ts+++ b/packages/database/src/models/__tests__/session.test.ts@@ -3,7 +3,6 @@ import { eq, inArray } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';-import type { SessionItem } from '../../schemas';import {agents,agentsToSessions,@@ -73,123 +72,6 @@ describe('SessionModel', () => {});});- describe('queryWithGroups', () => {- it('should return sessions grouped by group', async () => {- // Create test data- await serverDB.transaction(async (trx) => {- await trx.insert(users).values([{ id: '456' }]);- await trx.insert(sessionGroups).values([- { userId, name: 'Group 1', id: 'group1' },- { userId, name: 'Group 2', id: 'group2' },- ]);- await trx.insert(sessions).values([- { id: '1', userId, groupId: 'group1' },- { id: '2', userId, groupId: 'group1' },- { id: '23', userId, groupId: 'group1', pinned: true },- { id: '3', userId, groupId: 'group2' },- { id: '4', userId },- { id: '5', userId, pinned: true },- { id: '7', userId: '456' },- ]);- });-- // Call the queryWithGroups method- const result = await sessionModel.queryWithGroups();-- // Assert results- expect(result.sessions).toHaveLength(6);- expect(result.sessionGroups).toHaveLength(2);- expect(result.sessionGroups[0].id).toBe('group1');- expect(result.sessionGroups[0].name).toBe('Group 1');-- expect(result.sessionGroups[1].id).toBe('group2');- });-- it('should return empty groups if no sessions', async () => {- // Call the queryWithGroups method- const result = await sessionModel.queryWithGroups();-- // Assert results- expect(result.sessions).toHaveLength(0);- expect(result.sessionGroups).toHaveLength(0);- });-- it('should map group sessions with members correctly', async () => {- // Create a group session with multiple agents- await serverDB.transaction(async (trx) => {- // Create a group session- await trx.insert(sessions).values({- id: 'group-session-1',- userId,- type: 'group',- title: 'Test Group',- description: 'A test group session',- avatar: 'group-avatar',- backgroundColor: 'blue',- });-- // Create agents- await trx.insert(agents).values([- { id: 'agent-1', userId, title: 'Agent 1', model: 'gpt-4' },- { id: 'agent-2', userId, title: 'Agent 2', model: 'gpt-3.5-turbo' },- { id: 'agent-3', userId, title: 'Agent 3', model: 'claude-2' },- ]);-- // Link agents to the group session- await trx.insert(agentsToSessions).values([- { sessionId: 'group-session-1', agentId: 'agent-1', userId },- { sessionId: 'group-session-1', agentId: 'agent-2', userId },- { sessionId: 'group-session-1', agentId: 'agent-3', userId },- ]);- });-- const result = await sessionModel.queryWithGroups();-- // Verify group session mapping- expect(result.sessions).toHaveLength(1);- const groupSession = result.sessions[0] as any;-- expect(groupSession.type).toBe('group');- expect(groupSession.meta).toEqual({- avatar: 'group-avatar',- backgroundColor: 'blue',- description: 'A test group session',- tags: undefined,- title: 'Test Group',- });-- // Verify members are mapped correctly- expect(groupSession.members).toHaveLength(3);- expect(groupSession.members[0]).toMatchObject({- agentId: 'agent-1',- chatGroupId: 'group-session-1',- enabled: true,- order: 0,- role: 'participant',- title: 'Agent 1',- model: 'gpt-4',- });- expect(groupSession.members[1]).toMatchObject({- agentId: 'agent-2',- chatGroupId: 'group-session-1',- enabled: true,- order: 1,- role: 'participant',- title: 'Agent 2',- model: 'gpt-3.5-turbo',- });- expect(groupSession.members[2]).toMatchObject({- agentId: 'agent-3',- chatGroupId: 'group-session-1',- enabled: true,- order: 2,- role: 'participant',- title: 'Agent 3',- model: 'claude-2',- });- });- });-describe('findById', () => {it('should find session by ID', async () => {await serverDB.insert(sessions).values([@@ -338,42 +220,6 @@ describe('SessionModel', () => {});});- describe('duplicate', () => {- it('should duplicate a session', async () => {- // Create a user and a session- await serverDB.transaction(async (trx) => {- await trx- .insert(sessions)- .values({ id: '1', userId, type: 'agent', title: 'Original Session', pinned: true });- await trx.insert(agents).values({ id: 'agent-1', userId, model: 'gpt-3.5-turbo' });- await trx.insert(agentsToSessions).values({ agentId: 'agent-1', sessionId: '1', userId });- });-- // Call the duplicate method- const result = (await sessionModel.duplicate('1', 'Duplicated Session')) as SessionItem;-- // Assert results- expect(result.id).not.toBe('1');- expect(result.userId).toBe(userId);- expect(result.type).toBe('agent');-- const session = await sessionModel.findByIdOrSlug(result.id);-- expect(session).toBeDefined();- expect(session?.title).toEqual('Duplicated Session');- expect(session?.pinned).toBe(true);- expect(session?.agent?.model).toEqual('gpt-3.5-turbo');- });-- it('should return undefined if session does not exist', async () => {- // Call the duplicate method with a non-existent session ID- const result = await sessionModel.duplicate('non-existent-id');-- // Assert results- expect(result).toBeUndefined();- });- });-describe('update', () => {it('should update a session', async () => {// Create a test session@@ -411,47 +257,6 @@ describe('SessionModel', () => {});});- describe('isSoleShellOfAgent', () => {- beforeEach(async () => {- await serverDB.insert(sessions).values([- { id: 's1', userId },- { id: 's2', userId },- ]);- await serverDB.insert(agents).values([- { id: 'a1', userId },- { id: 'a2', userId },- ]);- });-- it("is true for the agent's one and only shell", async () => {- await serverDB.insert(agentsToSessions).values([{ agentId: 'a1', sessionId: 's1', userId }]);-- expect(await sessionModel.isSoleShellOfAgent('s1', 'a1')).toBe(true);- });-- it('is false when the agent is linked to another session too', async () => {- await serverDB.insert(agentsToSessions).values([- { agentId: 'a1', sessionId: 's1', userId },- { agentId: 'a1', sessionId: 's2', userId },- ]);-- expect(await sessionModel.isSoleShellOfAgent('s1', 'a1')).toBe(false);- });-- it('is false when the session also holds another agent', async () => {- await serverDB.insert(agentsToSessions).values([- { agentId: 'a1', sessionId: 's1', userId },- { agentId: 'a2', sessionId: 's1', userId },- ]);-- expect(await sessionModel.isSoleShellOfAgent('s1', 'a1')).toBe(false);- });-- it('is false when the session is not linked to the agent at all', async () => {- expect(await sessionModel.isSoleShellOfAgent('s1', 'a1')).toBe(false);- });- });-describe('delete', () => {it('should handle deleting a session with no associated messages or topics', async () => {// Create test datadiff --git a/packages/database/src/models/session.ts b/packages/database/src/models/session.tsindex 71b81aed66f..3098f4a2125 100644--- a/packages/database/src/models/session.ts+++ b/packages/database/src/models/session.ts@@ -1,11 +1,6 @@import { DEFAULT_AGENT_CONFIG, INBOX_SESSION_ID } from '@lobechat/const';-import type {- ChatSessionList,- LobeAgentConfig,- LobeAgentSession,- LobeGroupSession,-} from '@lobechat/types';-import { and, asc, desc, eq, exists, inArray, not, notExists, or } from 'drizzle-orm';+import type { LobeAgentConfig } from '@lobechat/types';+import { and, desc, eq, exists, inArray, not, notExists, or } from 'drizzle-orm';import type { PartialDeep } from 'type-fest';import { merge } from '@/utils/merge';@@ -19,8 +14,8 @@ import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';/*** @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- * data; write paths should go through `AgentModel` / `TopicModel`.+ * schema note. Reads here still support legacy data and recycle-bin behavior;+ * write paths should go through `AgentModel` / `TopicModel`.*/export class SessionModel {private userId: string;@@ -133,26 +128,6 @@ export class SessionModel {return Array.from(groupedResults.values());};- queryWithGroups = async (): Promise<ChatSessionList> => {- // Query all sessions- const result = await this.query();-- const groups = await this.db.query.sessionGroups.findMany({- orderBy: [asc(sessionGroups.sort), desc(sessionGroups.createdAt)],- where: buildWorkspaceWhere(- { userId: this.userId, workspaceId: this.workspaceId },- sessionGroups,- ),- });-- const mappedSessions = result.map((item) => this.mapSessionItem(item as any));-- return {- sessionGroups: groups as unknown as ChatSessionList['sessionGroups'],- sessions: mappedSessions,- };- };-findByIdOrSlug = async (idOrSlug: string,): Promise<(SessionItem & { agent: AgentItem }) | undefined> => {@@ -348,27 +323,6 @@ export class SessionModel {});};- duplicate = async (id: string, newTitle?: string) => {- const result = await this.findByIdOrSlug(id);-- if (!result) return;-- const { agent, clientId: _clientId, ...session } = result;- const sessionId = this.genId();-- const { id: _, slug: __, ...config } = agent;-- return this.create({- config,- id: sessionId,- session: {- ...session,- title: newTitle || session.title,- },- type: 'agent',- });- };-// **************** Delete *************** ///**@@ -473,34 +427,6 @@ export class SessionModel {});};- /** Agents linked to a session — lets `removeSession` route through the agent trash handler. */- findLinkedAgentIds = async (sessionId: string): Promise<string[]> => {- const links = await this.db- .select({ agentId: agentsToSessions.agentId })- .from(agentsToSessions)- .where(and(eq(agentsToSessions.sessionId, sessionId), this.agentsToSessionsOwnership()));- return links.map((link) => link.agentId);- };-- /**- * Whether `sessionId` is the agent's one and only shell and carries no other- * agent — i.e. removing the session means removing the agent. The schema- * allows an agent to be linked to several sessions (and a group shell to- * several agents); in either case only the selected shell may go. Link- * counting mirrors {@link clearOrphanAgent}: every link counts, so an agent- * is never treated as orphaned while anything still points at it.- */- isSoleShellOfAgent = async (sessionId: string, agentId: string): Promise<boolean> => {- const links = await this.db- .select({ agentId: agentsToSessions.agentId, sessionId: agentsToSessions.sessionId })- .from(agentsToSessions)- .where(or(eq(agentsToSessions.agentId, agentId), eq(agentsToSessions.sessionId, sessionId)));- return (- links.length > 0 &&- links.every((link) => link.agentId === agentId && link.sessionId === sessionId)- );- };-clearOrphanAgent = async (agentIds: string[], trx: any): Promise<string[]> => {if (agentIds.length === 0) return [];@@ -545,76 +471,4 @@ export class SessionModel {.where(and(eq(sessions.id, id), this.ownership())).returning();};-- // **************** Helper *************** //-- private genId = () => idGenerator('sessions');-- private mapSessionItem = ({- agentsToSessions,- title,- backgroundColor,- description,- avatar,- groupId,- type,- ...res- }: SessionItem & { agentsToSessions?: { agent: AgentItem }[] }):- LobeAgentSession | LobeGroupSession => {- const meta = {- avatar: avatar ?? undefined,- backgroundColor: backgroundColor ?? undefined,- description: description ?? undefined,- tags: undefined,- title: title ?? undefined,- };-- if (type === 'group') {- // For group sessions, return without agent-specific fields- // Transform agentsToSessions to include both relationship and agent data- const members =- agentsToSessions?.map((item, index) => {- const member = {- // Start with agent properties for compatibility- ...item.agent,- // Override with ChatGroupAgentItem properties- agentId: item.agent.id,- chatGroupId: res.id,- enabled: true,- order: index,- role: 'participant',- // Keep agent timestamps for now (could be overridden if needed)- };- return member;- }) || [];-- return {- ...res,- group: groupId,- members,- meta,- type: 'group',- } as LobeGroupSession;- }-- // For agent sessions, include agent-specific fields- // TODO: Need a better implementation in the future, currently only taking the first one- const agent = agentsToSessions?.[0]?.agent;- return {- ...res,- config: agent ? (agent as any) : { model: '', plugins: [] }, // Ensure config exists for agent sessions- group: groupId,- meta: {- avatar: agent?.avatar ?? avatar ?? undefined,- backgroundColor: agent?.backgroundColor ?? backgroundColor ?? undefined,- description: agent?.description ?? description ?? undefined,-- marketIdentifier: agent?.marketIdentifier ?? undefined,- tags: agent?.tags ?? undefined,- title: agent?.title ?? title ?? undefined,- },- model: agent?.model || '',- type: 'agent',- } as LobeAgentSession;- };}diff --git a/packages/trpc/src/utils/errorLogger.test.ts b/packages/trpc/src/utils/errorLogger.test.tsindex da8eb55d6e2..0e779b2f672 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.getGroupedSessions', type: 'query' });+ onError({ error, path: 'agent.getAgentConfig', type: 'query' });expect(console.info).not.toHaveBeenCalled();expect(console.error).not.toHaveBeenCalled();diff --git a/packages/types/src/session/index.ts b/packages/types/src/session/index.tsindex 673a51be98b..04972cf2785 100644--- a/packages/types/src/session/index.ts+++ b/packages/types/src/session/index.ts@@ -1,14 +1,8 @@-import type { LobeSessions } from './agentSession';-import type { LobeSessionGroups, SessionGroupId } from './sessionGroup';+import type { SessionGroupId } from './sessionGroup';export * from './agentSession';export * from './sessionGroup';-export interface ChatSessionList {- sessionGroups: LobeSessionGroups;- sessions: LobeSessions;-}-export interface UpdateSessionParams {group?: SessionGroupId;meta?: any;diff --git a/src/hooks/useFetchSessions.ts b/src/hooks/useFetchSessions.tsdeleted file mode 100644index eb2b545b88a..00000000000--- a/src/hooks/useFetchSessions.ts+++ /dev/null@@ -1,10 +0,0 @@-import { useSessionStore } from '@/store/session';-import { useUserStore } from '@/store/user';-import { authSelectors } from '@/store/user/slices/auth/selectors';--export const useFetchSessions = () => {- const isLogin = useUserStore(authSelectors.isLogin);- const useFetchSessions = useSessionStore((s) => s.useFetchSessions);-- useFetchSessions(true, isLogin);-};diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex a3add050389..33e0e527ecf 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -236,15 +236,6 @@ export const groupKeys = {queryAgentsForCreate: def('group:queryAgentsForCreate', () => ['group:queryAgentsForCreate']),};-// ---- session -------------------------------------------------------------export const sessionKeys = {- createSession: def('session:createSession', (groupId: string | undefined) => [- 'session:createSession',- groupId,- ]),- list: def('session:list', (isLogin: boolean | undefined) => ['session:list', isLogin]),-};-// ---- thread -------------------------------------------------------------export const threadKeys = {list: def('thread:list', (topicId: string) => ['thread:list', topicId]),@@ -1031,7 +1022,6 @@ export const swrKeys = {recommendations: recommendationsKeys,resource: resourceKeys,serverConfig: serverConfigKeys,- session: sessionKeys,share: shareKeys,stats: statsKeys,taskTemplate: taskTemplateKeys,diff --git a/src/libs/swr/useClientDataSWRWithSync.ts b/src/libs/swr/useClientDataSWRWithSync.tsindex 7349a81ce49..f41194c621d 100644--- a/src/libs/swr/useClientDataSWRWithSync.ts+++ b/src/libs/swr/useClientDataSWRWithSync.ts@@ -38,12 +38,12 @@ interface UseClientDataSWRWithSyncOptions<T> extends SWRConfiguration<T> {* @example* ```ts* useClientDataSWRWithSync(- * isLogin ? sessionKeys.list(scope) : null,- * () => sessionService.getGroupedSessions(),+ * agentConfigKeys.search(keyword),+ * () => agentService.queryAgents({ keyword }),* {* onData: (data) => {* // Auto sync to store, whether cached or fresh data- * set({ sessions: data.sessions, isInit: true });+ * set({ agents: data, isInit: true });* },* skipSync: state.isInit, // Optional: skip after initialized* }diff --git a/src/services/session/index.ts b/src/services/session/index.tsindex 8036e9f1fbf..c3c6b1d8410 100644--- a/src/services/session/index.ts+++ b/src/services/session/index.ts@@ -1,7 +1,6 @@import { lambdaClient } from '@/libs/trpc/client';import { type LobeAgentConfig } from '@/types/agent';import {- type ChatSessionList,type LobeAgentSession,type LobeSessionType,type SessionGroupItem,@@ -10,7 +9,7 @@ import {/*** @deprecated Session service is legacy. Use agentService for agent CRUD operations.- * Mobile still uses this, but should migrate to agentService.+ * Retains session-shell compatibility and independent session-group operations.*/export class SessionService {/** @deprecated Use agentService.createAgent instead */@@ -26,14 +25,6 @@ export class SessionService {});};- cloneSession = (id: string, newTitle: string): Promise<string | undefined> => {- return lambdaClient.session.cloneSession.mutate({ id, newTitle });- };-- getGroupedSessions = (): Promise<ChatSessionList> => {- return lambdaClient.session.getGroupedSessions.query();- };-updateSession = (id: string, data: Partial<UpdateSessionParams>) => {const { group, pinned, meta, updatedAt } = data;return lambdaClient.session.updateSession.mutate({@@ -48,10 +39,6 @@ export class SessionService {return lambdaClient.agent.getAgentConfig.query({ sessionId: id });};- removeSession = (id: string) => {- return lambdaClient.session.removeSession.mutate({ id });- };-// ************************************** //// *********** SessionGroup *********** //// ************************************** //diff --git a/src/store/agent/slices/agent/action.test.ts b/src/store/agent/slices/agent/action.test.tsindex a8e4d17a16d..b8f926c4938 100644--- a/src/store/agent/slices/agent/action.test.ts+++ b/src/store/agent/slices/agent/action.test.ts@@ -41,15 +41,6 @@ vi.mock('@lobehub/ui', async (importOriginal) => ({...(await import('~base-ui-stubs')).baseUiStubs,}));-// Mock sessionStore-vi.mock('@/store/session', () => ({- useSessionStore: {- getState: vi.fn(() => ({- refreshSessions: vi.fn(),- })),- },-}));-// Mock SWR mutatevi.mock('swr', async (importOriginal) => {const modules = await importOriginal();@@ -1128,9 +1119,6 @@ describe('AgentSlice Actions', () => {);});- // Note: refreshSessions is no longer called after optimistic update- // as the implementation now uses API returned data directly-it('confirms the saved response in the replica without another request', async () => {const { result } = renderHook(() => useAgentStore());const scopedMutate = vi.fn().mockResolvedValue(undefined);@@ -1293,9 +1281,6 @@ describe('AgentSlice Actions', () => {expect(result.current.agentMap['agent-1']?.title).toBe('Original');});-- // Note: refreshSessions is no longer called after optimistic update- // as the implementation now uses API returned data directly});describe('useFetchAgentConfig', () => {diff --git a/src/store/agent/slices/plugin/action.test.ts b/src/store/agent/slices/plugin/action.test.tsindex fc139279742..4427f46dd1b 100644--- a/src/store/agent/slices/plugin/action.test.ts+++ b/src/store/agent/slices/plugin/action.test.ts@@ -13,15 +13,6 @@ vi.mock('@/services/agent', () => ({},}));-// Mock sessionStore-vi.mock('@/store/session', () => ({- useSessionStore: {- getState: vi.fn(() => ({- refreshSessions: vi.fn(),- })),- },-}));-beforeEach(() => {vi.clearAllMocks();useAgentStore.setState({diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.tsindex ba891190bd3..475d4e24a99 100644--- a/src/store/chat/slices/topic/action.test.ts+++ b/src/store/chat/slices/topic/action.test.ts@@ -120,7 +120,6 @@ beforeEach(() => {defaultSessions: [],pinnedSessions: [],sessions: [],- isSessionsFirstFetchFinished: false,},false,);diff --git a/src/store/electron/actions/sync.ts b/src/store/electron/actions/sync.tsindex c4021df3790..25944ecfe92 100644--- a/src/store/electron/actions/sync.ts+++ b/src/store/electron/actions/sync.ts@@ -98,12 +98,7 @@ export class ElectronRemoteServerActionImpl {const { stores } = await import('@/store/utils/userDataStores');stores.reset();- const [{ useSessionStore }, { useChatStore }] = await Promise.all([- import('@/store/session'),- import('@/store/chat'),- ]);-- await useSessionStore.getState().refreshSessions();+ const { useChatStore } = await import('@/store/chat');await useChatStore.getState().refreshMessages();await useChatStore.getState().refreshTopic();await useUserStore.getState().refreshUserState();diff --git a/src/store/home/slices/sidebarUI/action.test.ts b/src/store/home/slices/sidebarUI/action.test.tsindex d74aca36bb4..58cb15d9b3d 100644--- a/src/store/home/slices/sidebarUI/action.test.ts+++ b/src/store/home/slices/sidebarUI/action.test.ts@@ -202,7 +202,6 @@ describe('createSidebarUISlice', () => {await result.current.removeAgent(mockAgentId);});- // removeAgent only removes and refreshes the agent list; session switching is handled in SessionStore.removeSessionexpect(mockSwitchSession).not.toHaveBeenCalledWith(INBOX_SESSION_ID);});});diff --git a/src/store/session/slices/session/action.test.ts b/src/store/session/slices/session/action.test.tsindex fad85ecc0f4..85566b0d8b8 100644--- a/src/store/session/slices/session/action.test.ts+++ b/src/store/session/slices/session/action.test.ts@@ -1,4 +1,3 @@-import { toast } from '@lobehub/ui';import { act, renderHook } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -13,9 +12,7 @@ import { sessionSelectors } from './selectors';vi.mock('@/services/session', () => ({sessionService: {createSession: vi.fn(),- cloneSession: vi.fn(),updateSessionGroup: vi.fn(),- removeSession: vi.fn(),updateSession: vi.fn(),updateSessionGroupId: vi.fn(),updateSessionPinned: vi.fn(),@@ -28,21 +25,8 @@ vi.mock('@/services/chatGroup', () => ({},}));-vi.mock('@lobehub/ui', async (importOriginal) => ({- ...(await importOriginal<object>()),- toast: {- error: vi.fn(),- loading: vi.fn(() => ({ close: vi.fn() })),- success: vi.fn(),- },-}));--const mockRefresh = vi.fn();beforeEach(() => {vi.clearAllMocks();- useSessionStore.setState({- refreshSessions: mockRefresh,- });});afterEach(() => {@@ -93,35 +77,6 @@ describe('SessionAction', () => {});});- describe('cloneSession', () => {- it('should duplicate a session and switch to the new one', async () => {- const { result } = renderHook(() => useSessionStore());- const sessionId = 'session-id';- const duplicatedSessionId = 'duplicated-session-id';- vi.mocked(sessionService.cloneSession).mockResolvedValue(duplicatedSessionId);- await act(async () => {- await result.current.duplicateSession(sessionId);- });-- expect(toast.loading).toHaveBeenCalled();- expect(sessionService.cloneSession).toHaveBeenCalledWith(sessionId, expect.any(String));- });- });-- describe('removeSession', () => {- it('should remove a session and refresh the list', async () => {- const { result } = renderHook(() => useSessionStore());- const sessionId = 'session-id';-- await act(async () => {- await result.current.removeSession(sessionId);- });-- expect(sessionService.removeSession).toHaveBeenCalledWith(sessionId);- expect(mockRefresh).toHaveBeenCalled();- });- });-describe('activeSession', () => {it('should set the provided session id as active', async () => {const { result } = renderHook(() => useSessionStore());@@ -145,7 +100,6 @@ describe('SessionAction', () => {});expect(sessionService.updateSession).toHaveBeenCalledWith(sessionId, { pinned: true });- expect(mockRefresh).toHaveBeenCalled();});it('should unpin a session when pinned is false', async () => {@@ -157,12 +111,11 @@ describe('SessionAction', () => {});expect(sessionService.updateSession).toHaveBeenCalledWith(sessionId, { pinned: false });- expect(mockRefresh).toHaveBeenCalled();});});describe('updateSessionGroupId', () => {- it('should update regular session group and refresh the list', async () => {+ it('should update regular session group', async () => {const { result } = renderHook(() => useSessionStore());const sessionId = 'session-id';const groupId = 'new-group-id';@@ -181,10 +134,9 @@ describe('SessionAction', () => {});expect(sessionService.updateSession).toHaveBeenCalledWith(sessionId, { group: groupId });- expect(mockRefresh).toHaveBeenCalled();});- it('should update chat group session and refresh the list', async () => {+ it('should update chat group session', async () => {const { result } = renderHook(() => useSessionStore());const sessionId = 'group-session-id';const groupId = 'new-group-id';@@ -203,7 +155,6 @@ describe('SessionAction', () => {});expect(chatGroupService.updateGroup).toHaveBeenCalledWith(sessionId, { groupId });- expect(mockRefresh).toHaveBeenCalled();});it('should handle default group for chat group sessions', async () => {@@ -225,7 +176,6 @@ describe('SessionAction', () => {});expect(chatGroupService.updateGroup).toHaveBeenCalledWith(sessionId, { groupId: null });- expect(mockRefresh).toHaveBeenCalled();});});});diff --git a/src/store/session/slices/session/action.ts b/src/store/session/slices/session/action.tsindex 4abeec69309..9ad84b98ebd 100644--- a/src/store/session/slices/session/action.ts+++ b/src/store/session/slices/session/action.ts@@ -1,23 +1,14 @@-import { toast } from '@lobehub/ui';-import isEqual from 'fast-deep-equal';-import { t } from 'i18next';-import { type SWRResponse } from 'swr';import { type PartialDeep } from 'type-fest';-import { DEFAULT_AGENT_LOBE_SESSION, INBOX_SESSION_ID } from '@/const/session';+import { DEFAULT_AGENT_LOBE_SESSION } from '@/const/session';import { analyticsClient } from '@/libs/analytics/client';-import { mutate, useClientDataSWR } from '@/libs/swr';-import { sessionKeys } from '@/libs/swr/keys';import { chatGroupService } from '@/services/chatGroup';import { sessionService } from '@/services/session';-import { getChatGroupStoreState } from '@/store/agentGroup';-import { evictMessageCache } from '@/store/chat/utils/evictMessageCache';import { type SessionStore } from '@/store/session';import { type StoreSetter } from '@/store/types';import { getUserStoreState, useUserStore } from '@/store/user';import { settingsSelectors, userProfileSelectors } from '@/store/user/selectors';import {- type ChatSessionList,type LobeAgentSession,type LobeSessionGroups,type LobeSessions,@@ -30,7 +21,6 @@ import { setNamespace } from '@/utils/storeDebug';import { type SessionDispatch } from './reducers';import { sessionsReducer } from './reducers';import { sessionSelectors } from './selectors';-import { sessionMetaSelectors } from './selectors/meta';const n = setNamespace('session');@@ -57,7 +47,7 @@ export class SessionActionImpl {agent?: PartialDeep<LobeAgentSession>,isSwitchSession: boolean = true,): Promise<string> => {- const { switchSession, refreshSessions } = this.#get();+ const { switchSession } = this.#get();// merge the defaultAgent in settingsconst defaultAgent = merge(@@ -68,7 +58,6 @@ export class SessionActionImpl {const newSession: LobeAgentSession = merge(defaultAgent, agent);const id = await sessionService.createSession(LobeSessionType.Agent, newSession);- await refreshSessions();const userId = userProfileSelectors.userId(getUserStoreState());@@ -88,33 +77,6 @@ export class SessionActionImpl {return id;};- duplicateSession = async (id: string): Promise<void> => {- const { switchSession, refreshSessions } = this.#get();- const session = sessionSelectors.getSessionById(id)(this.#get());-- if (!session) return;- const title = sessionMetaSelectors.getTitle(session.meta);-- const newTitle = t('duplicateSession.title', { ns: 'chat', title });-- const loadingToast = toast.loading(t('duplicateSession.loading', { ns: 'chat' }));-- const newId = await sessionService.cloneSession(id, newTitle);-- // duplicate Session Error- if (!newId) {- loadingToast.close();- toast.error(t('copyFail', { ns: 'common' }));- return;- }-- await refreshSessions();- loadingToast.close();- toast.success(t('duplicateSession.success', { ns: 'chat' }));-- switchSession(newId);- };-openAllAgentsDrawer = (): void => {this.#set({ allAgentsDrawerOpen: true }, false, n('openAllAgentsDrawer'));};@@ -123,28 +85,6 @@ export class SessionActionImpl {await this.#get().internal_updateSession(id, { pinned });};- /**- * @deprecated Legacy session-store delete path, kept only for the mobile- * session list (`(mobile)/.../SessionListContent/List/Item/Actions.tsx`).- * Desktop already deletes via `HomeStore.removeAgent`. New call sites must use- * `HomeStore.removeAgent` (agents) / `HomeStore.removeAgentGroup` (groups) —- * all three evict the message cache, so behaviour is equivalent apart from this- * path also switching to the inbox when the active session is removed. Remove- * once the mobile session list migrates to the agent store.- */- removeSession = async (sessionId: string): Promise<void> => {- await sessionService.removeSession(sessionId);- await this.#get().refreshSessions();- // deleting an agent cascade-deletes its topics + messages on the server; drop- // their message cache too so it doesn't orphan in IndexedDB (never expires)- void evictMessageCache((ctx) => ctx.agentId === sessionId);-- // If the active session deleted, switch to the inbox session- if (sessionId === this.#get().activeId) {- this.#get().switchSession(INBOX_SESSION_ID);- }- };-setAgentPinned = (value: boolean | ((prev: boolean) => boolean)): void => {this.#set((state) => ({@@ -185,87 +125,12 @@ export class SessionActionImpl {await chatGroupService.updateGroup(sessionId, {groupId: group === 'default' ? null : group,});- await this.#get().refreshSessions();} else {// For regular agent sessions, use the existing session serviceawait this.#get().internal_updateSession(sessionId, { group });}};- useFetchSessions = (- enabled: boolean,- isLogin: boolean | undefined,- ): SWRResponse<ChatSessionList> => {- return useClientDataSWR<ChatSessionList>(- enabled ? sessionKeys.list(isLogin) : null,- () => sessionService.getGroupedSessions(),- {- fallbackData: {- sessionGroups: [],- sessions: [],- },- onSuccess: (data) => {- if (- this.#get().isSessionsFirstFetchFinished &&- isEqual(this.#get().sessions, data.sessions) &&- isEqual(this.#get().sessionGroups, data.sessionGroups)- )- return;-- this.#get().internal_processSessions(data.sessions, data.sessionGroups);-- // Sync chat groups from group sessions to chat store- const groupSessions = data.sessions.filter((session) => session.type === 'group');- if (groupSessions.length > 0) {- // For group sessions, we need to transform them to ChatGroupItem format- // The session ID is the chat group ID, and we can extract basic group info- const chatGroupStore = getChatGroupStoreState();- const chatGroups = groupSessions.map((session) => ({- accessedAt: session.updatedAt,- avatar: null,- backgroundColor: null,- clientId: null,- config: null,- content: null,- createdAt: session.createdAt,- deletedAt: null,- isDeleted: null,- description: session.meta?.description || '',- editorData: null,-- groupId: session.group || null,- id: session.id, // Add the missing groupId property-- marketIdentifier: null,-- // Will be set by the backend- pinned: session.pinned || false,-- // Session ID is the chat group ID- slug: null,-- title: session.meta?.title || 'Untitled Group',- updatedAt: session.updatedAt,- userId: '', // Use updatedAt as accessedAt fallback- visibility: 'public' as const,- workspaceId: null,- }));-- // Session rows are synthesized: only their real fields may seed a- // group detail (see `GroupSeedSource`).- chatGroupStore.internal_updateGroupMaps(chatGroups, 'session');- }-- this.#set(- { isSessionsFirstFetchFinished: true },- false,- n('useFetchSessions/onSuccess', data),- );- },- },- );- };-internal_dispatchSessions = (payload: SessionDispatch): void => {const nextSessions = sessionsReducer(this.#get().sessions, payload);this.#get().internal_processSessions(nextSessions, this.#get().sessionGroups);@@ -278,7 +143,6 @@ export class SessionActionImpl {this.#get().internal_dispatchSessions({ id, type: 'updateSession', value: data });await sessionService.updateSession(id, data);- await this.#get().refreshSessions();};internal_processSessions = (sessions: LobeSessions, sessionGroups: LobeSessionGroups): void => {@@ -304,10 +168,6 @@ export class SessionActionImpl {n('processSessions'),);};-- refreshSessions = async (): Promise<void> => {- await mutate(sessionKeys.list(true));- };}export type SessionAction = Pick<SessionActionImpl, keyof SessionActionImpl>;diff --git a/src/store/session/slices/session/initialState.ts b/src/store/session/slices/session/initialState.tsindex b61f632530a..130662963e5 100644--- a/src/store/session/slices/session/initialState.ts+++ b/src/store/session/slices/session/initialState.ts@@ -18,7 +18,6 @@ export interface SessionState {*/isAgentPinned: boolean;isSearching: boolean;- isSessionsFirstFetchFinished: boolean;pinnedSessions: LobeSessions;/*** @title Session ID being renamed@@ -43,7 +42,6 @@ export const initialSessionState: SessionState = {defaultSessions: [],isAgentPinned: false,isSearching: false,- isSessionsFirstFetchFinished: false,pinnedSessions: [],sessionRenamingId: null,sessionUpdatingId: null,diff --git a/src/store/session/slices/session/reducers.test.ts b/src/store/session/slices/session/reducers.test.tsindex 899ce904a34..326b5febe30 100644--- a/src/store/session/slices/session/reducers.test.ts+++ b/src/store/session/slices/session/reducers.test.ts@@ -37,18 +37,6 @@ describe('sessionsReducer', () => {});});- it('should remove an existing session', () => {- const state: LobeSessions = [mockSession];- const removeAction: SessionDispatch = {- id: mockSession.id,- type: 'removeSession',- };-- const newState = sessionsReducer(state, removeAction);-- expect(newState).toHaveLength(0);- });-it('should update an existing session', () => {const state: LobeSessions = [mockSession];const updateAction: SessionDispatch = {diff --git a/src/store/session/slices/session/reducers.ts b/src/store/session/slices/session/reducers.tsindex 139bcf0920e..c8f4c940df0 100644--- a/src/store/session/slices/session/reducers.ts+++ b/src/store/session/slices/session/reducers.ts@@ -7,18 +7,13 @@ interface AddSession {type: 'addSession';}-interface RemoveSession {- id: string;- type: 'removeSession';-}-interface UpdateSession {id: string;type: 'updateSession';value: Partial<LobeSession>;}-export type SessionDispatch = AddSession | RemoveSession | UpdateSession;+export type SessionDispatch = AddSession | UpdateSession;export const sessionsReducer = (state: LobeSessions, payload: SessionDispatch): LobeSessions => {switch (payload.type) {@@ -33,15 +28,6 @@ export const sessionsReducer = (state: LobeSessions, payload: SessionDispatch):});}- case 'removeSession': {- return produce(state, (draftState) => {- const index = draftState.findIndex((item) => item.id === payload.id);- if (index !== -1) {- draftState.splice(index, 1);- }- });- }-case 'updateSession': {return produce(state, (draftState) => {const { value, id } = payload;diff --git a/src/store/session/slices/session/selectors/list.ts b/src/store/session/slices/session/selectors/list.tsindex 23ad06d392b..ad65af9c16f 100644--- a/src/store/session/slices/session/selectors/list.ts+++ b/src/store/session/slices/session/selectors/list.ts@@ -43,10 +43,6 @@ const currentGroupAgents = (s: SessionStore): GroupMemberWithAgent[] => {return session ? (session.members ?? []) : [];};-const isSessionListInit = (s: SessionStore) => s.isSessionsFirstFetchFinished;--const isSomeSessionActive = (s: SessionStore) => !!s.activeId && isSessionListInit(s);-export const sessionSelectors = {currentGroupAgents,currentSession,@@ -55,7 +51,5 @@ export const sessionSelectors = {getSessionById,isCurrentSessionGroupSession,isInboxSession,- isSessionListInit,- isSomeSessionActive,pinnedSessions,};diff --git a/src/store/session/slices/sessionGroup/action.test.ts b/src/store/session/slices/sessionGroup/action.test.tsindex 6a098a3752e..050ae6a18ba 100644--- a/src/store/session/slices/sessionGroup/action.test.ts+++ b/src/store/session/slices/sessionGroup/action.test.ts@@ -10,11 +10,10 @@ afterEach(() => {describe('createSessionGroupSlice', () => {describe('addSessionGroup', () => {- it('should add a session group and refresh sessions', async () => {+ it('should add a session group', async () => {const mockId = 'mock-id';const mockName = 'Test Group';vi.spyOn(sessionService, 'createSessionGroup').mockResolvedValue(mockId);- const spyOnRefreshSessions = vi.spyOn(useSessionStore.getState(), 'refreshSessions');const { result } = renderHook(() => useSessionStore());@@ -24,16 +23,14 @@ describe('createSessionGroupSlice', () => {});expect(sessionService.createSessionGroup).toHaveBeenCalledWith(mockName);- expect(spyOnRefreshSessions).toHaveBeenCalled();expect(returnedId).toBe(mockId);});});describe('removeSessionGroup', () => {- it('should remove a session group and refresh sessions', async () => {+ it('should remove a session group', async () => {const mockId = 'mock-id';vi.spyOn(sessionService, 'removeSessionGroup').mockResolvedValueOnce(undefined as any);- const spyOnRefreshSessions = vi.spyOn(useSessionStore.getState(), 'refreshSessions');const { result } = renderHook(() => useSessionStore());@@ -42,16 +39,14 @@ describe('createSessionGroupSlice', () => {});expect(sessionService.removeSessionGroup).toHaveBeenCalledWith(mockId);- expect(spyOnRefreshSessions).toHaveBeenCalled();});});describe('updateSessionGroupId', () => {- it('should update a session group id and refresh sessions', async () => {+ it('should update a session group id', async () => {const mockSessionId = 'session-id';const mockGroupId = 'group-id';vi.spyOn(sessionService, 'updateSession').mockResolvedValueOnce(undefined as any);- const spyOnRefreshSessions = vi.spyOn(useSessionStore.getState(), 'refreshSessions');const { result } = renderHook(() => useSessionStore());@@ -62,15 +57,13 @@ describe('createSessionGroupSlice', () => {expect(sessionService.updateSession).toHaveBeenCalledWith(mockSessionId, {group: mockGroupId,});- expect(spyOnRefreshSessions).toHaveBeenCalled();});});describe('updateSessionGroupName', () => {- it('should update a session group name and refresh sessions', async () => {+ it('should update a session group name', async () => {const mockId = 'mock-id';const mockName = 'New Name';- const spyOnRefreshSessions = vi.spyOn(useSessionStore.getState(), 'refreshSessions');vi.spyOn(sessionService, 'updateSessionGroup').mockResolvedValueOnce(undefined as any);const { result } = renderHook(() => useSessionStore());@@ -80,18 +73,16 @@ describe('createSessionGroupSlice', () => {});expect(sessionService.updateSessionGroup).toHaveBeenCalledWith(mockId, { name: mockName });- expect(spyOnRefreshSessions).toHaveBeenCalled();});});describe('updateSessionGroupSort', () => {- it('should update session group sort order and refresh sessions', async () => {+ it('should update session group sort order', async () => {const mockItems: any[] = [{ id: 'id1', sort: 0 },{ id: 'id2', sort: 1 },];vi.spyOn(sessionService, 'updateSessionGroupOrder').mockResolvedValueOnce(undefined as any);- const spyOnRefreshSessions = vi.spyOn(useSessionStore.getState(), 'refreshSessions');const { result } = renderHook(() => useSessionStore());@@ -102,7 +93,6 @@ describe('createSessionGroupSlice', () => {expect(sessionService.updateSessionGroupOrder).toHaveBeenCalledWith(mockItems.map((item) => ({ id: item.id, sort: item.sort })),);- expect(spyOnRefreshSessions).toHaveBeenCalled();});});});diff --git a/src/store/session/slices/sessionGroup/action.ts b/src/store/session/slices/sessionGroup/action.tsindex 2d22cadf382..ffee3417b2f 100644--- a/src/store/session/slices/sessionGroup/action.ts+++ b/src/store/session/slices/sessionGroup/action.ts@@ -25,19 +25,15 @@ export class SessionGroupActionImpl {addSessionGroup = async (name: string): Promise<string> => {const id = await sessionService.createSessionGroup(name);- await this.#get().refreshSessions();-return id;};removeSessionGroup = async (id: string): Promise<void> => {await sessionService.removeSessionGroup(id);- await this.#get().refreshSessions();};updateSessionGroupName = async (id: string, name: string): Promise<void> => {await sessionService.updateSessionGroup(id, { name });- await this.#get().refreshSessions();};updateSessionGroupSort = async (items: SessionGroupItem[]): Promise<void> => {@@ -50,8 +46,6 @@ export class SessionGroupActionImpl {await sessionService.updateSessionGroupOrder(sortMap);loadingToast.close();toast.success(t('sessionGroup.sortSuccess', { ns: 'chat' }));-- await this.#get().refreshSessions();};internal_dispatchSessionGroups = (payload: SessionGroupsDispatch): void => {