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.

:bug: fix: fix delete agent group bug

arvinxx0fe0d6f86f40
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 673d27e6a2e..4e4c334298e 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -32,7 +32,7 @@
"chatList.longMessageDetail": "View Details",
"clearCurrentMessages": "Clear current session messages",
"confirmClearCurrentMessages": "You are about to clear the current session messages. Once cleared, they cannot be retrieved. Please confirm your action.",
- "confirmRemoveChatGroupItemAlert": "This Group will be deleted. Members won’t be affected. Confirm to continue.",
+ "confirmRemoveChatGroupItemAlert": "This Group will be deleted. Group-specific assistants will also be deleted, while external assistants will not be affected.",
"confirmRemoveGroupItemAlert": "You are about to delete this group. After deletion, its agents will be moved to the default list. Please confirm your action.",
"confirmRemoveGroupSuccess": "Group deleted successfully",
"confirmRemoveSessionItemAlert": "You are about to delete this agent. Once deleted, it cannot be retrieved. Please confirm your action.",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 82878eaf7c3..c3e3f3835c2 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -32,7 +32,7 @@
"chatList.longMessageDetail": "查看详情",
"clearCurrentMessages": "清空当前会话消息",
"confirmClearCurrentMessages": "确认清空当前会话消息吗?清空后无法恢复",
- "confirmRemoveChatGroupItemAlert": "确认删除该群组吗?成员不会受影响",
+ "confirmRemoveChatGroupItemAlert": "确认删除该群组吗?群组专有助理将会被同样删除,外部助理不受影响",
"confirmRemoveGroupItemAlert": "确认删除该分组吗?分组内的助理会移回默认列表",
"confirmRemoveGroupSuccess": "群组已删除",
"confirmRemoveSessionItemAlert": "确认删除该助理吗?删除后无法恢复",
diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.ts
index 82180085bec..8984bbd5cd5 100644
--- a/packages/database/src/models/__tests__/agent.test.ts
+++ b/packages/database/src/models/__tests__/agent.test.ts
@@ -1170,6 +1170,139 @@ describe('AgentModel', () => {
});
});
+ describe('batchDelete', () => {
+ it('should batch delete multiple agents', async () => {
+ // Create multiple agents
+ const [agent1] = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'Agent 1' })
+ .returning();
+ const [agent2] = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'Agent 2' })
+ .returning();
+ const [agent3] = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'Agent 3' })
+ .returning();
+
+ // Batch delete agent1 and agent2
+ await agentModel.batchDelete([agent1.id, agent2.id]);
+
+ // Verify agent1 and agent2 are deleted
+ const deletedAgent1 = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent1.id),
+ });
+ const deletedAgent2 = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent2.id),
+ });
+ expect(deletedAgent1).toBeUndefined();
+ expect(deletedAgent2).toBeUndefined();
+
+ // Verify agent3 still exists
+ const remainingAgent = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent3.id),
+ });
+ expect(remainingAgent).toBeDefined();
+ expect(remainingAgent?.title).toBe('Agent 3');
+ });
+
+ it('should return early for empty array input', async () => {
+ // Create an agent to ensure the test has something to potentially delete
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'Test Agent' })
+ .returning();
+
+ // Call batchDelete with empty array
+ const result = await agentModel.batchDelete([]);
+
+ // Should return undefined (early return)
+ expect(result).toBeUndefined();
+
+ // Verify agent still exists
+ const existingAgent = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent.id),
+ });
+ expect(existingAgent).toBeDefined();
+ });
+
+ it('should not delete another user agents', async () => {
+ // Create agents for user1
+ const [agent1] = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'User1 Agent 1' })
+ .returning();
+ const [agent2] = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'User1 Agent 2' })
+ .returning();
+
+ // Try to batch delete with user2's model
+ await agentModel2.batchDelete([agent1.id, agent2.id]);
+
+ // Verify agents still exist
+ const existingAgent1 = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent1.id),
+ });
+ const existingAgent2 = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent2.id),
+ });
+ expect(existingAgent1).toBeDefined();
+ expect(existingAgent2).toBeDefined();
+ });
+
+ it('should handle mixed valid and invalid agent IDs', async () => {
+ // Create an agent
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'Valid Agent' })
+ .returning();
+
+ // Batch delete with one valid and one invalid ID
+ await agentModel.batchDelete([agent.id, 'non-existent-id']);
+
+ // Verify valid agent is deleted
+ const deletedAgent = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent.id),
+ });
+ expect(deletedAgent).toBeUndefined();
+ });
+
+ it('should delete agent along with associated files and knowledge bases (cascade)', async () => {
+ // Create agent with files and knowledge bases
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'Agent with knowledge' })
+ .returning();
+ await serverDB.insert(agentsFiles).values({ agentId: agent.id, fileId: '1', userId });
+ await serverDB
+ .insert(agentsKnowledgeBases)
+ .values({ agentId: agent.id, knowledgeBaseId: 'kb1', userId });
+
+ // Batch delete the agent
+ await agentModel.batchDelete([agent.id]);
+
+ // Verify agent is deleted
+ const deletedAgent = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent.id),
+ });
+ expect(deletedAgent).toBeUndefined();
+
+ // Verify agentsFiles are deleted (cascade)
+ const remainingFiles = await serverDB.query.agentsFiles.findMany({
+ where: eq(agentsFiles.agentId, agent.id),
+ });
+ expect(remainingFiles).toHaveLength(0);
+
+ // Verify agentsKnowledgeBases are deleted (cascade)
+ const remainingKBs = await serverDB.query.agentsKnowledgeBases.findMany({
+ where: eq(agentsKnowledgeBases.agentId, agent.id),
+ });
+ expect(remainingKBs).toHaveLength(0);
+ });
+ });
+
describe('queryAgents', () => {
it('should return non-virtual agents for the user', async () => {
// Create non-virtual agents
diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.ts
index 51a20110966..80478e08805 100644
--- a/packages/database/src/models/agent.ts
+++ b/packages/database/src/models/agent.ts
@@ -271,6 +271,19 @@ export class AgentModel {
});
};
+ /**
+ * Batch delete agents by IDs.
+ * This is a simpler delete that only removes the agent records.
+ * Use this for virtual agents that don't have associated sessions.
+ */
+ batchDelete = async (agentIds: string[]) => {
+ if (agentIds.length === 0) return;
+
+ return this.db
+ .delete(agents)
+ .where(and(eq(agents.userId, this.userId), inArray(agents.id, agentIds)));
+ };
+
toggleFile = async (agentId: string, fileId: string, enabled?: boolean) => {
return this.db
.update(agentsFiles)
diff --git a/src/app/[variants]/(main)/home/_layout/hooks/useSessionItemMenuItems.tsx b/src/app/[variants]/(main)/home/_layout/hooks/useSessionItemMenuItems.tsx
index 9c179639e07..a79a767c8b6 100644
--- a/src/app/[variants]/(main)/home/_layout/hooks/useSessionItemMenuItems.tsx
+++ b/src/app/[variants]/(main)/home/_layout/hooks/useSessionItemMenuItems.tsx
@@ -18,7 +18,6 @@ import {
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { useAgentGroupStore } from '@/store/agentGroup';
import { useGlobalStore } from '@/store/global';
import { useHomeStore } from '@/store/home';
import { homeAgentListSelectors } from '@/store/home/selectors';
@@ -40,11 +39,15 @@ export const useSessionItemMenuItems = () => {
const openAgentInNewWindow = useGlobalStore((s) => s.openAgentInNewWindow);
const sessionCustomGroups = useHomeStore(homeAgentListSelectors.agentGroups, isEqual);
- const [pinAgent, pinAgentGroup, duplicateAgent, updateAgentGroup, removeAgent] = useHomeStore(
- (s) => [s.pinAgent, s.pinAgentGroup, s.duplicateAgent, s.updateAgentGroup, s.removeAgent],
- );
-
- const deleteGroup = useAgentGroupStore((s) => s.deleteGroup);
+ const [pinAgent, pinAgentGroup, duplicateAgent, updateAgentGroup, removeAgent, removeAgentGroup] =
+ useHomeStore((s) => [
+ s.pinAgent,
+ s.pinAgentGroup,
+ s.duplicateAgent,
+ s.updateAgentGroup,
+ s.removeAgent,
+ s.removeAgentGroup,
+ ]);
/**
* Pin/Unpin menu item
@@ -206,7 +209,7 @@ export const useSessionItemMenuItems = () => {
okButtonProps: { danger: true },
onOk: async () => {
if (parentType === 'group') {
- await deleteGroup(id);
+ await removeAgentGroup(id);
message.success(t('confirmRemoveGroupSuccess'));
} else {
await removeAgent(id);
@@ -221,7 +224,7 @@ export const useSessionItemMenuItems = () => {
},
};
},
- [t, modal, styles.modalRoot, deleteGroup, message, removeAgent],
+ [t, modal, styles.modalRoot, removeAgentGroup, message, removeAgent],
);
return {
diff --git a/src/app/[variants]/(mobile)/(home)/features/SessionListContent/List/Item/Actions.tsx b/src/app/[variants]/(mobile)/(home)/features/SessionListContent/List/Item/Actions.tsx
index 931db160974..255165f1a74 100644
--- a/src/app/[variants]/(mobile)/(home)/features/SessionListContent/List/Item/Actions.tsx
+++ b/src/app/[variants]/(mobile)/(home)/features/SessionListContent/List/Item/Actions.tsx
@@ -18,7 +18,6 @@ import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { isDesktop } from '@/const/index';
-import { useAgentGroupStore } from '@/store/agentGroup';
import { useGlobalStore } from '@/store/global';
import { useHomeStore } from '@/store/home';
import { useSessionStore } from '@/store/session';
@@ -59,8 +58,10 @@ const Actions = memo<ActionProps>(({ group, id, openCreateGroupModal, parentType
];
});
- const deleteGroup = useAgentGroupStore((s) => s.deleteGroup);
- const pinAgentGroup = useHomeStore((s) => s.pinAgentGroup);
+ const [pinAgentGroup, removeAgentGroup] = useHomeStore((s) => [
+ s.pinAgentGroup,
+ s.removeAgentGroup,
+ ]);
const { modal, message } = App.useApp();
@@ -162,7 +163,7 @@ const Actions = memo<ActionProps>(({ group, id, openCreateGroupModal, parentType
okButtonProps: { danger: true },
onOk: async () => {
if (parentType === 'group') {
- await deleteGroup(id);
+ await removeAgentGroup(id);
message.success(t('confirmRemoveGroupSuccess'));
} else {
await removeSession(id);
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index c3aeb3afe8b..a71fe9a5b11 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -43,7 +43,7 @@ export default {
'confirmClearCurrentMessages':
'You are about to clear the current session messages. Once cleared, they cannot be retrieved. Please confirm your action.',
'confirmRemoveChatGroupItemAlert':
- 'This Group will be deleted. Members won’t be affected. Confirm to continue.',
+ 'This Group will be deleted. Group-specific assistants will also be deleted, while external assistants will not be affected.',
'confirmRemoveGroupItemAlert':
'You are about to delete this group. After deletion, its agents will be moved to the default list. Please confirm your action.',
'confirmRemoveGroupSuccess': 'Group deleted successfully',
diff --git a/src/server/routers/lambda/__tests__/agentGroup.test.ts b/src/server/routers/lambda/__tests__/agentGroup.test.ts
index e7ce200059e..111990f8219 100644
--- a/src/server/routers/lambda/__tests__/agentGroup.test.ts
+++ b/src/server/routers/lambda/__tests__/agentGroup.test.ts
@@ -6,7 +6,7 @@ import * as AgentModelModule from '@/database/models/agent';
import * as ChatGroupModelModule from '@/database/models/chatGroup';
import * as UserModelModule from '@/database/models/user';
import * as AgentGroupRepoModule from '@/database/repositories/agentGroup';
-import * as ChatGroupServiceModule from '@/server/services/chatGroup';
+import * as ChatGroupServiceModule from '@/server/services/agentGroup';
import { agentGroupRouter } from '../agentGroup';
@@ -67,7 +67,7 @@ describe('agentGroupRouter', () => {
() => agentGroupRepoMock as any,
);
vi.spyOn(UserModelModule, 'UserModel').mockImplementation(() => userModelMock as any);
- vi.spyOn(ChatGroupServiceModule, 'ChatGroupService').mockImplementation(
+ vi.spyOn(ChatGroupServiceModule, 'AgentGroupService').mockImplementation(
() => chatGroupServiceMock as any,
);
diff --git a/src/server/routers/lambda/__tests__/aiAgent.test.ts b/src/server/routers/lambda/__tests__/aiAgent.test.ts
index 7cd6cdf31eb..357a303520e 100644
--- a/src/server/routers/lambda/__tests__/aiAgent.test.ts
+++ b/src/server/routers/lambda/__tests__/aiAgent.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment node
import { LobeChatDatabase } from '@lobechat/database';
-import { agents, agentsToSessions, sessions, topics } from '@lobechat/database/schemas';
+import { agents, agentsToSessions, sessions, threads, topics } from '@lobechat/database/schemas';
import { getTestDB } from '@lobechat/database/test-utils';
import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -268,20 +268,43 @@ describe('AI Agent Router Integration Tests', () => {
}) as any,
);
+ // Create a topic first (required for thread)
+ const [topic] = await serverDB
+ .insert(topics)
+ .values({
+ title: 'Test Topic',
+ agentId: testAgentId,
+ sessionId: testSessionId,
+ userId,
+ })
+ .returning();
+
+ // Create a thread (required by foreign key constraint on messages)
+ const [thread] = await serverDB
+ .insert(threads)
+ .values({
+ topicId: topic.id,
+ agentId: testAgentId,
+ userId,
+ type: 'isolation',
+ })
+ .returning();
+
const caller = aiAgentRouter.createCaller(createTestContext());
await caller.execAgent({
agentId: testAgentId,
prompt: 'Test prompt',
appContext: {
- threadId: 'test-thread-id',
+ threadId: thread.id,
+ topicId: topic.id,
},
});
expect(mockCreateOperation).toHaveBeenCalledWith(
expect.objectContaining({
appContext: expect.objectContaining({
- threadId: 'test-thread-id',
+ threadId: thread.id,
}),
}),
);
diff --git a/src/server/routers/lambda/agentGroup.ts b/src/server/routers/lambda/agentGroup.ts
index 0dff46b4733..eb566297d08 100644
--- a/src/server/routers/lambda/agentGroup.ts
+++ b/src/server/routers/lambda/agentGroup.ts
@@ -9,7 +9,7 @@ import { insertChatGroupSchema } from '@/database/schemas/chatGroup';
import { type ChatGroupConfig } from '@/database/types/chatGroup';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-import { ChatGroupService } from '@/server/services/chatGroup';
+import { AgentGroupService } from '@/server/services/agentGroup';
const agentGroupProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
@@ -17,9 +17,9 @@ const agentGroupProcedure = authedProcedure.use(serverDatabase).use(async (opts)
return opts.next({
ctx: {
agentGroupRepo: new AgentGroupRepository(ctx.serverDB, ctx.userId),
+ agentGroupService: new AgentGroupService(ctx.serverDB, ctx.userId),
agentModel: new AgentModel(ctx.serverDB, ctx.userId),
chatGroupModel: new ChatGroupModel(ctx.serverDB, ctx.userId),
- chatGroupService: new ChatGroupService(ctx.serverDB, ctx.userId),
userModel: new UserModel(ctx.serverDB, ctx.userId),
},
});
@@ -62,7 +62,7 @@ export const agentGroupRouter = router({
.mutation(async ({ input, ctx }) => {
const { group, supervisorAgentId } = await ctx.agentGroupRepo.createGroupWithSupervisor({
...input,
- config: ctx.chatGroupService.normalizeGroupConfig(input.config as ChatGroupConfig | null),
+ config: ctx.agentGroupService.normalizeGroupConfig(input.config as ChatGroupConfig | null),
});
return { group, supervisorAgentId };
@@ -110,7 +110,7 @@ export const agentGroupRouter = router({
const { group, supervisorAgentId } = await ctx.agentGroupRepo.createGroupWithSupervisor(
{
...input.groupConfig,
- config: ctx.chatGroupService.normalizeGroupConfig(
+ config: ctx.agentGroupService.normalizeGroupConfig(
input.groupConfig.config as ChatGroupConfig | null,
),
},
@@ -123,7 +123,7 @@ export const agentGroupRouter = router({
deleteGroup: agentGroupProcedure
.input(z.object({ id: z.string() }))
.mutation(async ({ input, ctx }) => {
- return ctx.chatGroupModel.delete(input.id);
+ return ctx.agentGroupService.deleteGroup(input.id);
}),
getGroup: agentGroupProcedure
@@ -143,26 +143,26 @@ export const agentGroupRouter = router({
.query(async ({ input, ctx }) => {
const [defaultAgentConfig, detail] = await Promise.all([
ctx.userModel.getUserSettingsDefaultAgentConfig(),
- ctx.chatGroupService.getGroupDetail(input.id),
+ ctx.agentGroupService.getGroupDetail(input.id),
]);
if (!detail) return null;
return {
...detail,
- agents: ctx.chatGroupService.mergeAgentsDefaultConfig(defaultAgentConfig, detail.agents),
+ agents: ctx.agentGroupService.mergeAgentsDefaultConfig(defaultAgentConfig, detail.agents),
};
}),
getGroups: agentGroupProcedure.query(async ({ ctx }) => {
const [defaultAgentConfig, groups] = await Promise.all([
ctx.userModel.getUserSettingsDefaultAgentConfig(),
- ctx.chatGroupService.getGroups(),
+ ctx.agentGroupService.getGroups(),
]);
return groups.map((group) => ({
...group,
- agents: ctx.chatGroupService.mergeAgentsDefaultConfig(defaultAgentConfig, group.agents),
+ agents: ctx.agentGroupService.mergeAgentsDefaultConfig(defaultAgentConfig, group.agents),
}));
}),
@@ -217,7 +217,7 @@ export const agentGroupRouter = router({
.mutation(async ({ input, ctx }) => {
return ctx.chatGroupModel.update(input.id, {
...input.value,
- config: ctx.chatGroupService.normalizeGroupConfig(
+ config: ctx.agentGroupService.normalizeGroupConfig(
input.value.config as ChatGroupConfig | null,
),
});
diff --git a/src/server/services/chatGroup/index.ts b/src/server/services/agentGroup/index.ts
similarity index 66%
rename from src/server/services/chatGroup/index.ts
rename to src/server/services/agentGroup/index.ts
index 80c1af10592..ff305338b73 100644
--- a/src/server/services/chatGroup/index.ts
+++ b/src/server/services/agentGroup/index.ts
@@ -4,6 +4,7 @@ import { type LobeAgentConfig } from '@lobechat/types';
import { cleanObject, merge } from '@lobechat/utils';
import type { PartialDeep } from 'type-fest';
+import { AgentModel } from '@/database/models/agent';
import { ChatGroupModel } from '@/database/models/chatGroup';
import { type UserModel } from '@/database/models/user';
import { AgentGroupRepository } from '@/database/repositories/agentGroup';
@@ -18,11 +19,13 @@ type DefaultAgentConfig = Awaited<ReturnType<UserModel['getUserSettingsDefaultAg
* Encapsulates "mutation + query" logic for chat group operations.
* Handles agent config merging for group members.
*/
-export class ChatGroupService {
+export class AgentGroupService {
+ private readonly agentModel: AgentModel;
private readonly chatGroupModel: ChatGroupModel;
private readonly agentGroupRepo: AgentGroupRepository;
constructor(db: LobeChatDatabase, userId: string) {
+ this.agentModel = new AgentModel(db, userId);
this.chatGroupModel = new ChatGroupModel(db, userId);
this.agentGroupRepo = new AgentGroupRepository(db, userId);
}
@@ -41,6 +44,40 @@ export class ChatGroupService {
return this.chatGroupModel.queryWithMemberDetails();
}
+ /**
+ * Delete a group and its associated virtual agents.
+ *
+ * This method:
+ * 1. Gets all agents in the group to identify virtual ones
+ * 2. Deletes the group (CASCADE will delete chatGroupsAgents entries)
+ * 3. Deletes all virtual agents that were members of this group
+ *
+ * @param groupId - The group ID to delete
+ * @returns The deleted group and list of deleted virtual agent IDs
+ */
+ async deleteGroup(groupId: string) {
+ // 1. Get all agents in the group to identify virtual ones
+ const groupAgents = await this.chatGroupModel.getGroupAgents(groupId);
+ const agentIds = groupAgents.map((ga) => ga.agentId);
+
+ // 2. Check which agents are virtual
+ const { virtualAgents } = await this.agentGroupRepo.checkAgentsBeforeRemoval(groupId, agentIds);
+ const virtualAgentIds = virtualAgents.map((a) => a.id);
+
+ // 3. Delete the group (CASCADE will delete chatGroupsAgents entries)
+ const deletedGroup = await this.chatGroupModel.delete(groupId);
+
+ // 4. Delete virtual agents
+ if (virtualAgentIds.length > 0) {
+ await this.agentModel.batchDelete(virtualAgentIds);
+ }
+
+ return {
+ deletedVirtualAgentIds: virtualAgentIds,
+ group: deletedGroup,
+ };
+ }
+
/**
* Normalize ChatGroupConfig with defaults.
* Merges DEFAULT_CHAT_GROUP_CHAT_CONFIG with the provided config.
diff --git a/src/store/agentGroup/slices/lifecycle.test.ts b/src/store/agentGroup/slices/lifecycle.test.ts
index 2f564934745..02e79468345 100644
--- a/src/store/agentGroup/slices/lifecycle.test.ts
+++ b/src/store/agentGroup/slices/lifecycle.test.ts
@@ -1,7 +1,6 @@
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { INBOX_SESSION_ID } from '@/const/session';
import { chatGroupService } from '@/services/chatGroup';
import { useAgentGroupStore } from '../store';
@@ -11,8 +10,6 @@ vi.mock('@/services/chatGroup', () => ({
chatGroupService: {
addAgentsToGroup: vi.fn(),
createGroup: vi.fn(),
- deleteGroup: vi.fn(),
- getGroupAgents: vi.fn(),
getGroups: vi.fn(),
},
}));
@@ -21,7 +18,6 @@ vi.mock('@/store/session', () => ({
getSessionStoreState: vi.fn(() => ({
activeId: 'some-session-id',
refreshSessions: vi.fn().mockResolvedValue(undefined),
- removeSession: vi.fn().mockResolvedValue(undefined),
sessions: [],
switchSession: vi.fn(),
})),
@@ -126,76 +122,4 @@ describe('ChatGroupLifecycleSlice', () => {
expect(mockSwitchSession).not.toHaveBeenCalled();
});
});
-
- describe('deleteGroup', () => {
- it('should delete a group', async () => {
- vi.mocked(chatGroupService.getGroupAgents).mockResolvedValue([]);
- vi.mocked(chatGroupService.deleteGroup).mockResolvedValue({} as any);
- vi.mocked(chatGroupService.getGroups).mockResolvedValue([]);
-
- const { result } = renderHook(() => useAgentGroupStore());
-
- await act(async () => {
- await result.current.deleteGroup('group-to-delete');
- });
-
- expect(chatGroupService.deleteGroup).toHaveBeenCalledWith('group-to-delete');
- });
-
- it('should delete virtual agents when deleting group', async () => {
- const mockRemoveSession = vi.fn().mockResolvedValue(undefined);
- const { getSessionStoreState } = await import('@/store/session');
- vi.mocked(getSessionStoreState).mockReturnValue({
- activeId: 'other-session',
- refreshSessions: vi.fn().mockResolvedValue(undefined),
- removeSession: mockRemoveSession,
- sessions: [
- {
- config: { id: 'virtual-agent-id', virtual: true },
- id: 'virtual-session-id',
- type: 'agent',
- },
- ],
- switchSession: vi.fn(),
- } as any);
-
- vi.mocked(chatGroupService.getGroupAgents).mockResolvedValue([
- { agentId: 'virtual-agent-id', chatGroupId: 'group-id' },
- ] as any);
- vi.mocked(chatGroupService.deleteGroup).mockResolvedValue({} as any);
- vi.mocked(chatGroupService.getGroups).mockResolvedValue([]);
-
- const { result } = renderHook(() => useAgentGroupStore());
-
- await act(async () => {
- await result.current.deleteGroup('group-id');
- });
-
- expect(mockRemoveSession).toHaveBeenCalledWith('virtual-session-id');
- });
-
- it('should switch to inbox if deleted group is active', async () => {
- const mockSwitchSession = vi.fn();
- const { getSessionStoreState } = await import('@/store/session');
- vi.mocked(getSessionStoreState).mockReturnValue({
- activeId: 'group-to-delete',
- refreshSessions: vi.fn().mockResolvedValue(undefined),
- removeSession: vi.fn().mockResolvedValue(undefined),
- sessions: [],
- switchSession: mockSwitchSession,
- } as any);
-
- vi.mocked(chatGroupService.getGroupAgents).mockResolvedValue([]);
- vi.mocked(chatGroupService.deleteGroup).mockResolvedValue({} as any);
- vi.mocked(chatGroupService.getGroups).mockResolvedValue([]);
-
- const { result } = renderHook(() => useAgentGroupStore());
-
- await act(async () => {
- await result.current.deleteGroup('group-to-delete');
- });
-
- expect(mockSwitchSession).toHaveBeenCalledWith(INBOX_SESSION_ID);
- });
- });
});
diff --git a/src/store/agentGroup/slices/lifecycle.ts b/src/store/agentGroup/slices/lifecycle.ts
index 518b4c3e143..60a6e0815fa 100644
--- a/src/store/agentGroup/slices/lifecycle.ts
+++ b/src/store/agentGroup/slices/lifecycle.ts
@@ -1,7 +1,6 @@
import type { NewChatGroup } from '@lobechat/types';
import { type StateCreator } from 'zustand/vanilla';
-import { INBOX_SESSION_ID } from '@/const/session';
import { chatGroupService } from '@/services/chatGroup';
import { type ChatGroupStore } from '@/store/agentGroup/store';
import { getSessionStoreState } from '@/store/session';
@@ -12,7 +11,6 @@ export interface ChatGroupLifecycleAction {
agentIds?: string[],
silent?: boolean,
) => Promise<string>;
- deleteGroup: (id: string) => Promise<void>;
}
export const chatGroupLifecycleSlice: StateCreator<
@@ -50,53 +48,4 @@ export const chatGroupLifecycleSlice: StateCreator<
return group.id;
},
-
- deleteGroup: async (id) => {
- // First, get all group members to identify virtual members
- // Note: ChatGroupAgentItem type is incorrectly defined in schema as agents table type
- // but getGroupAgents actually returns chatGroupsAgents junction table entries
- const groupAgents = (await chatGroupService.getGroupAgents(id)) as unknown as Array<{
- agentId: string;
- chatGroupId: string;
- }>;
-
- // Delete the group first (this will cascade delete the chat_groups_agents entries)
- await chatGroupService.deleteGroup(id);
- get().internal_dispatchChatGroup({ payload: id, type: 'deleteGroup' });
-
- // Now delete virtual members (agents with virtual: true)
- const sessionStore = getSessionStoreState();
- const sessions = sessionStore.sessions || [];
-
- // Find and delete all virtual sessions that were members of this group
- const virtualMemberDeletions = groupAgents
- .map((groupAgent) => {
- // groupAgent has agentId property from the junction table
- const session = sessions.find((s) => {
- // Type guard: check if it's an agent session
- if (s.type === 'agent') {
- return s.config?.id === groupAgent.agentId;
- }
- return false;
- });
-
- // Only delete if the session exists and has virtual flag set to true
- if (session && session.type === 'agent' && session.config?.virtual) {
- return sessionStore.removeSession(session.id);
- }
- return null;
- })
- .filter(Boolean);
-
- // Wait for all virtual member deletions to complete
- await Promise.all(virtualMemberDeletions);
-
- await get().loadGroups();
- await getSessionStoreState().refreshSessions();
-
- // If the active session is the deleted group, switch to the inbox session
- if (sessionStore.activeId === id) {
- sessionStore.switchSession(INBOX_SESSION_ID);
- }
- },
});
diff --git a/src/store/home/slices/sidebarUI/action.ts b/src/store/home/slices/sidebarUI/action.ts
index 2cba9c221c1..56ca6396a12 100644
--- a/src/store/home/slices/sidebarUI/action.ts
+++ b/src/store/home/slices/sidebarUI/action.ts
@@ -32,6 +32,10 @@ export interface SidebarUIAction {
* Remove an agent
*/
removeAgent: (agentId: string) => Promise<void>;
+ /**
+ * Remove an agent group (group chat)
+ */
+ removeAgentGroup: (groupId: string) => Promise<void>;
/**
* Update agent's group
*/
@@ -124,6 +128,12 @@ export const createSidebarUISlice: StateCreator<
await get().refreshAgentList();
},
+ removeAgentGroup: async (groupId) => {
+ // Delete the group
+ await chatGroupService.deleteGroup(groupId);
+ await get().refreshAgentList();
+ },
+
updateAgentGroup: async (agentId, groupId) => {
await homeService.updateAgentSessionGroupId(agentId, groupId === 'default' ? null : groupId);
await get().refreshAgentList();