Skip to content

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

✨ feat(agent): let agent authors delete agents carrying teammates' topics, with an impact-aware confirm (#22313)

Lobehub Codere8ac56b1b30a
diff --git a/apps/server/src/routers/lambda/agent/index.procedures.test.ts b/apps/server/src/routers/lambda/agent/index.procedures.test.ts
index 067f2a43380..9586d400f4c 100644
--- a/apps/server/src/routers/lambda/agent/index.procedures.test.ts
+++ b/apps/server/src/routers/lambda/agent/index.procedures.test.ts
@@ -39,6 +39,7 @@ function expected(): Array<
['getAgentByMarketIdentifier', 'query', 12],
['getAgentConfig', 'query', 12],
['getAgentConfigById', 'query', 12],
+ ['getAgentDeleteImpact', 'query', 12],
['getAgentLock', 'query', 13],
['getBuiltinAgent', 'query', 12],
['getGroupMembershipImpact', 'query', 12],
diff --git a/apps/server/src/routers/lambda/agent/lifecycle.test.ts b/apps/server/src/routers/lambda/agent/lifecycle.test.ts
new file mode 100644
index 00000000000..69779ef5f9d
--- /dev/null
+++ b/apps/server/src/routers/lambda/agent/lifecycle.test.ts
@@ -0,0 +1,276 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentModel } from '@/database/models/agent';
+import { ResourceTransferRequestModel } from '@/database/models/resourceTransferRequest';
+import {
+ assertCanPerformResourceAction,
+ canPerformResourceAction,
+ getResourceMeta,
+} from '@/server/services/resourcePermission';
+import { TrashService } from '@/server/services/trash';
+import {
+ hasWorkspaceScopedPermission,
+ isWorkspacePrimaryOwner,
+} from '@/server/services/workspacePermission';
+import { TransferErrorCode } from '@/types/transferError';
+
+import { lifecycleRouter } from './lifecycle';
+
+// Only the creator-name lookup reads the db directly: select → from → where → limit.
+const creatorRows = vi.hoisted(() => ({
+ rows: [] as { fullName: string | null; username: string | null }[],
+}));
+vi.mock('@/database/core/db-adaptor', () => {
+ const chain: any = {
+ from: () => chain,
+ limit: () => Promise.resolve(creatorRows.rows),
+ where: () => chain,
+ };
+ return { getServerDB: vi.fn(() => ({ select: () => chain })) };
+});
+vi.mock('@/database/models/agent', async (importOriginal) => ({
+ ...((await importOriginal()) as object),
+ AgentModel: vi.fn(),
+}));
+vi.mock('@/database/models/chatGroup', () => ({ ChatGroupModel: vi.fn() }));
+vi.mock('@/database/models/file', () => ({ FileModel: vi.fn() }));
+vi.mock('@/database/models/knowledgeBase', () => ({ KnowledgeBaseModel: vi.fn() }));
+vi.mock('@/database/models/session', () => ({ SessionModel: vi.fn() }));
+vi.mock('@/server/services/agent', () => ({ AgentService: vi.fn() }));
+vi.mock('@/server/services/trash', () => ({ TrashService: vi.fn() }));
+vi.mock('@/database/models/resourceTransferRequest', async (importOriginal) => ({
+ ...((await importOriginal()) as object),
+ ResourceTransferRequestModel: vi.fn(),
+}));
+vi.mock('@/server/services/resourcePermission', () => ({
+ assertCanPerformResourceAction: vi.fn(),
+ canPerformResourceAction: vi.fn(),
+ getResourceMeta: vi.fn(),
+}));
+
+/** `delete` follows the resource rule (author / Owner); `manage` also admits Admins. */
+const grantActions = (actions: string[]) =>
+ vi
+ .mocked(canPerformResourceAction)
+ .mockImplementation(async ({ action }) => actions.includes(action));
+vi.mock('@/server/services/workspacePermission', () => ({
+ hasWorkspaceScopedPermission: vi.fn(),
+ isWorkspacePrimaryOwner: vi.fn(),
+}));
+
+const userId = 'user-1';
+const agentId = 'agent-1';
+const workspaceId = 'ws-1';
+
+describe('lifecycleRouter.removeAgent', () => {
+ let getDeleteImpact: ReturnType<typeof vi.fn>;
+ let trashAgent: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+
+ getDeleteImpact = vi.fn().mockResolvedValue({ foreignTopicCount: 2, hasForeignContent: true });
+ trashAgent = vi.fn().mockResolvedValue({ id: agentId });
+
+ vi.mocked(AgentModel).mockImplementation(function () {
+ return { getDeleteImpact } as any;
+ });
+ vi.mocked(TrashService).mockImplementation(function () {
+ return { trashAgent } as any;
+ });
+ vi.mocked(ResourceTransferRequestModel).mockImplementation(function () {
+ return { invalidateForResources: vi.fn() } as any;
+ });
+ vi.mocked(assertCanPerformResourceAction).mockResolvedValue(undefined);
+ grantActions(['delete', 'manage']);
+ vi.mocked(hasWorkspaceScopedPermission).mockResolvedValue(true);
+ vi.mocked(isWorkspacePrimaryOwner).mockResolvedValue(false);
+ });
+
+ const callRemove = (
+ workspaceRole: string,
+ acknowledgeForeignContent?: boolean,
+ acknowledgeOtherCreator?: boolean,
+ ) =>
+ lifecycleRouter
+ .createCaller({ userId, workspaceId, workspaceRole } as any)
+ .removeAgent({ acknowledgeForeignContent, acknowledgeOtherCreator, agentId });
+
+ it("lets the agent's author delete it with teammates' topics once the impact is acknowledged", async () => {
+ vi.mocked(getResourceMeta).mockResolvedValue({ userId, visibility: 'public', workspaceId });
+
+ await expect(callRemove('member', true)).resolves.toEqual({ id: agentId });
+ expect(trashAgent).toHaveBeenCalledWith(agentId);
+ expect(getDeleteImpact).not.toHaveBeenCalled();
+ });
+
+ it("refuses the author when the caller never acknowledged teammates' content (CLI, agent tools, older clients)", async () => {
+ vi.mocked(getResourceMeta).mockResolvedValue({ userId, visibility: 'public', workspaceId });
+
+ await expect(callRemove('member')).rejects.toMatchObject({
+ cause: { data: { code: TransferErrorCode.OwnerOnly } },
+ code: 'FORBIDDEN',
+ });
+ expect(trashAgent).not.toHaveBeenCalled();
+ });
+
+ it('lets the author delete without acknowledgment when nothing foreign rides along', async () => {
+ vi.mocked(getResourceMeta).mockResolvedValue({ userId, visibility: 'public', workspaceId });
+ getDeleteImpact.mockResolvedValue({ foreignTopicCount: 0, hasForeignContent: false });
+
+ await expect(callRemove('member')).resolves.toEqual({ id: agentId });
+ });
+
+ describe("a workspace Admin deleting another member's agent", () => {
+ beforeEach(() => {
+ vi.mocked(getResourceMeta).mockResolvedValue({
+ userId: 'user-2',
+ visibility: 'public',
+ workspaceId,
+ });
+ // AGENT_DELETE is `:owner`-scoped for Admins; `manage` comes from AGENT_UPDATE:all.
+ grantActions(['manage']);
+ });
+
+ it('deletes once both the other-creator and the foreign-content warnings were acknowledged', async () => {
+ await expect(callRemove('admin', true, true)).resolves.toEqual({ id: agentId });
+ expect(trashAgent).toHaveBeenCalledWith(agentId);
+ });
+
+ it('deletes an agent with no foreign content after acknowledging only the other creator', async () => {
+ getDeleteImpact.mockResolvedValue({ foreignTopicCount: 0, hasForeignContent: false });
+
+ await expect(callRemove('admin', false, true)).resolves.toEqual({ id: agentId });
+ });
+
+ it('refuses without the other-creator acknowledgment (CLI, agent tools, older clients)', async () => {
+ await expect(callRemove('admin', true)).rejects.toMatchObject({
+ cause: { data: { code: TransferErrorCode.OwnerOnly } },
+ code: 'FORBIDDEN',
+ });
+ expect(trashAgent).not.toHaveBeenCalled();
+ });
+
+ it("refuses when other members' content was not acknowledged", async () => {
+ await expect(callRemove('admin', false, true)).rejects.toMatchObject({
+ cause: { data: { code: TransferErrorCode.OwnerOnly } },
+ code: 'FORBIDDEN',
+ });
+ expect(trashAgent).not.toHaveBeenCalled();
+ });
+
+ it('refuses a private agent the Admin cannot manage', async () => {
+ grantActions([]);
+
+ await expect(callRemove('admin', true, true)).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(trashAgent).not.toHaveBeenCalled();
+ });
+ });
+
+ it("refuses a member deleting someone else's agent even with every acknowledgment", async () => {
+ vi.mocked(getResourceMeta).mockResolvedValue({
+ userId: 'user-2',
+ visibility: 'public',
+ workspaceId,
+ });
+ grantActions([]);
+
+ await expect(callRemove('member', true, true)).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(trashAgent).not.toHaveBeenCalled();
+ });
+
+ it("lets a workspace owner delete someone else's agent with teammates' content", async () => {
+ vi.mocked(getResourceMeta).mockResolvedValue({
+ userId: 'user-2',
+ visibility: 'public',
+ workspaceId,
+ });
+
+ await expect(callRemove('owner')).resolves.toEqual({ id: agentId });
+ expect(getDeleteImpact).not.toHaveBeenCalled();
+ });
+});
+
+describe('lifecycleRouter.getAgentDeleteImpact', () => {
+ let getDeleteImpact: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+
+ getDeleteImpact = vi.fn().mockResolvedValue({ foreignTopicCount: 3, hasForeignContent: true });
+ vi.mocked(AgentModel).mockImplementation(function () {
+ return { getDeleteImpact } as any;
+ });
+ vi.mocked(hasWorkspaceScopedPermission).mockResolvedValue(true);
+ });
+
+ it('is gated by the delete permission in a workspace', async () => {
+ vi.mocked(getResourceMeta).mockResolvedValue({ userId, visibility: 'public', workspaceId });
+ grantActions(['delete']);
+
+ const result = await lifecycleRouter
+ .createCaller({ userId, workspaceId, workspaceRole: 'member' } as any)
+ .getAgentDeleteImpact({ agentId });
+
+ expect(result).toEqual({
+ createdByOther: false,
+ creatorName: null,
+ foreignTopicCount: 3,
+ hasForeignContent: true,
+ });
+ expect(canPerformResourceAction).toHaveBeenCalledWith(
+ expect.objectContaining({ action: 'delete', resourceId: agentId, resourceType: 'agent' }),
+ );
+ });
+
+ it("names the creator when an Admin looks at another member's agent", async () => {
+ vi.mocked(getResourceMeta).mockResolvedValue({
+ userId: 'user-2',
+ visibility: 'public',
+ workspaceId,
+ });
+ grantActions(['manage']);
+ creatorRows.rows = [{ fullName: '速冻鱼', username: 'fish' }];
+
+ const result = await lifecycleRouter
+ .createCaller({ userId, workspaceId, workspaceRole: 'admin' } as any)
+ .getAgentDeleteImpact({ agentId });
+
+ expect(result).toEqual({
+ createdByOther: true,
+ creatorName: '速冻鱼',
+ foreignTopicCount: 3,
+ hasForeignContent: true,
+ });
+ });
+
+ it("refuses a member looking at someone else's agent", async () => {
+ vi.mocked(getResourceMeta).mockResolvedValue({
+ userId: 'user-2',
+ visibility: 'public',
+ workspaceId,
+ });
+ grantActions(['manage']);
+
+ await expect(
+ lifecycleRouter
+ .createCaller({ userId, workspaceId, workspaceRole: 'member' } as any)
+ .getAgentDeleteImpact({ agentId }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
+
+ it('reports nothing foreign in personal scope', async () => {
+ const result = await lifecycleRouter
+ .createCaller({ userId } as any)
+ .getAgentDeleteImpact({ agentId });
+
+ expect(result).toEqual({
+ createdByOther: false,
+ creatorName: null,
+ foreignTopicCount: 0,
+ hasForeignContent: false,
+ });
+ expect(getDeleteImpact).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/agent/lifecycle.ts b/apps/server/src/routers/lambda/agent/lifecycle.ts
index 359410dd66c..2803d2d71ba 100644
--- a/apps/server/src/routers/lambda/agent/lifecycle.ts
+++ b/apps/server/src/routers/lambda/agent/lifecycle.ts
@@ -1,5 +1,6 @@
-import { CreateAgentSchema } from '@lobechat/types';
+import { type AgentDeleteImpact, CreateAgentSchema } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
+import { eq } from 'drizzle-orm';
import { z } from 'zod';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
@@ -7,10 +8,14 @@ import { AGENT_COPY_IN_PROGRESS } from '@/database/models/agentCopyJob';
import { AGENT_TRANSFER_IN_PROGRESS } from '@/database/models/agentTransferJob';
import { ResourcePermissionModel } from '@/database/models/resourcePermission';
import { ResourceTransferRequestModel } from '@/database/models/resourceTransferRequest';
-import { DEFAULT_RESOURCE_ACCESS_LEVELS } from '@/database/schemas';
+import { DEFAULT_RESOURCE_ACCESS_LEVELS, users } from '@/database/schemas';
import { router } from '@/libs/trpc/lambda';
import { createAgentDirectChannel } from '@/server/services/channel/defaultChannel';
-import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';
+import {
+ assertCanPerformResourceAction,
+ canPerformResourceAction,
+ getResourceMeta,
+} from '@/server/services/resourcePermission';
import { TrashService } from '@/server/services/trash';
import { TransferErrorCode } from '@/types/transferError';
@@ -18,6 +23,66 @@ import { isWorkspaceNonOwner } from '../_helpers/assertWorkspaceRowManageable';
import { assertCanWriteTeamPin } from '../_helpers/sidebarPin';
import { agentProcedure } from './procedures';
+interface AgentDeleteCtx {
+ serverDB: Parameters<typeof getResourceMeta>[0];
+ userId: string;
+ workspaceId: string;
+ workspaceRole?: string;
+}
+
+/**
+ * Who may delete a workspace agent, and on what terms.
+ *
+ * - The resource `delete` rule: the agent's author, or the workspace Owner.
+ * - A workspace Admin may also delete another member's (non-private) agent —
+ * the same agents `manage` already lets them curate — but only as an
+ * *override*: the caller must have shown the strong warning (someone else
+ * created it, and what of other members' goes with it) and passed the
+ * acknowledgments back. CLI, agent tools and older clients never do, so they
+ * keep the old `:owner`-scoped rule; the RBAC matrix itself is unchanged.
+ */
+const resolveAgentDeleteAuthority = async (ctx: AgentDeleteCtx, agentId: string) => {
+ const meta = await getResourceMeta(ctx.serverDB, 'agent', agentId);
+ if (!meta || meta.workspaceId !== ctx.workspaceId) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Resource not found' });
+ }
+ const params = {
+ db: ctx.serverDB,
+ meta,
+ resourceId: agentId,
+ resourceType: 'agent' as const,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ };
+ if (await canPerformResourceAction({ ...params, action: 'delete' })) {
+ return { adminOverride: false, meta };
+ }
+ if (
+ ctx.workspaceRole === 'admin' &&
+ meta.userId !== ctx.userId &&
+ (await canPerformResourceAction({ ...params, action: 'manage' }))
+ ) {
+ return { adminOverride: true, meta };
+ }
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'You do not have permission to delete this resource',
+ });
+};
+
+const getCreatorName = async (
+ db: AgentDeleteCtx['serverDB'],
+ creatorId: string | null | undefined,
+): Promise<string | null> => {
+ if (!creatorId) return null;
+ const [row] = await db
+ .select({ fullName: users.fullName, username: users.username })
+ .from(users)
+ .where(eq(users.id, creatorId))
+ .limit(1);
+ return row?.fullName || row?.username || null;
+};
+
export const lifecycleRouter = router({
/**
* Check if an agent with the given marketIdentifier already exists
@@ -166,6 +231,33 @@ export const lifecycleRouter = router({
virtual: input.virtual,
});
}),
+ /**
+ * What deleting the agent would take down besides the caller's own work —
+ * feeds the delete confirmation, so it is gated like the delete itself.
+ * Personal scope has no other members, so it reports nothing foreign.
+ */
+ getAgentDeleteImpact: agentProcedure
+ .input(z.object({ agentId: z.string() }))
+ .query(async ({ input, ctx }): Promise<AgentDeleteImpact> => {
+ if (!ctx.workspaceId)
+ return {
+ createdByOther: false,
+ creatorName: null,
+ foreignTopicCount: 0,
+ hasForeignContent: false,
+ };
+
+ const { meta } = await resolveAgentDeleteAuthority(
+ { ...ctx, workspaceId: ctx.workspaceId },
+ input.agentId,
+ );
+ const createdByOther = !!meta.userId && meta.userId !== ctx.userId;
+ const [impact, creatorName] = await Promise.all([
+ ctx.agentModel.getDeleteImpact(input.agentId),
+ createdByOther ? getCreatorName(ctx.serverDB, meta.userId) : null,
+ ]);
+ return { ...impact, createdByOther, creatorName };
+ }),
/**
* Get an agent by marketIdentifier
* @returns agent id if exists, null otherwise
@@ -211,23 +303,47 @@ export const lifecycleRouter = router({
*/
removeAgent: agentProcedure
.use(withScopedPermission('agent:delete'))
- .input(z.object({ agentId: z.string() }))
+ .input(
+ z.object({
+ /**
+ * The caller showed the delete impact (`getAgentDeleteImpact`) and the
+ * user confirmed taking other members' content down with the agent.
+ * Only then may the agent's author delete an agent carrying it.
+ */
+ acknowledgeForeignContent: z.boolean().optional(),
+ /**
+ * The caller warned that someone else created this agent and the user
+ * confirmed anyway. Required for a workspace Admin's override delete.
+ */
+ acknowledgeOtherCreator: z.boolean().optional(),
+ agentId: z.string(),
+ }),
+ )
.mutation(async ({ input, ctx }) => {
if (ctx.workspaceId) {
- await assertCanPerformResourceAction({
- action: 'delete',
- db: ctx.serverDB,
- resourceId: input.agentId,
- resourceType: 'agent',
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- });
- // Same rule as transfer: the delete cascade erases every linked
- // session/topic/message, so a non-owner member must not take teammates'
- // conversations down with their own agent.
+ const { adminOverride, meta } = await resolveAgentDeleteAuthority(
+ { ...ctx, workspaceId: ctx.workspaceId },
+ input.agentId,
+ );
+ if (adminOverride && input.acknowledgeOtherCreator !== true) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.OwnerOnly } },
+ code: 'FORBIDDEN',
+ message: "Deleting another member's agent needs the confirmation that warns about it",
+ });
+ }
+ // The delete cascade trashes the agent's topics and messages, so the
+ // guard asks what it would actually take (`getDeleteImpact`; sessions
+ // and tasks stay). The agent's author, or an Admin overriding, may
+ // still delete it once the caller acknowledges that other members'
+ // content goes with it; callers that never disclosed the impact (CLI,
+ // agent tools, older clients) keep the guard.
+ const acknowledged =
+ (adminOverride || meta.userId === ctx.userId) && input.acknowledgeForeignContent === true;
if (
isWorkspaceNonOwner(ctx) &&
- (await ctx.agentModel.transferHasForeignRows(input.agentId))
+ !acknowledged &&
+ (await ctx.agentModel.getDeleteImpact(input.agentId)).hasForeignContent
) {
throw new TRPCError({
cause: { data: { code: TransferErrorCode.OwnerOnly } },
diff --git a/apps/server/src/services/trash/handlers/agent.ts b/apps/server/src/services/trash/handlers/agent.ts
index 0b849b53872..16975701bb1 100644
--- a/apps/server/src/services/trash/handlers/agent.ts
+++ b/apps/server/src/services/trash/handlers/agent.ts
@@ -60,8 +60,9 @@ export const softDeleteAgent = async (
// and the list hides them through the agent join); their topics are.
const sessionIds = await agentModel.findSessionIdsByAgentIds([agentId]);
// The cascade is scope-wide on purpose (no `restrictToCreator`): the router
- // already refused a non-owner delete of an agent that carries teammates'
- // conversations, so whatever is left is the caller's to take.
+ // only lets a non-owner through when nothing foreign rides along, or when
+ // the agent's author (or an Admin overriding on another member's agent)
+ // acknowledged that teammates' topics go with it.
const topics = await topicModel.softDeleteByParents(
{ agentIds: [agentId], sessionIds },
{ deletedAt: options.deletedAt },
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 6323c195fe9..160910f67c1 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -235,10 +235,16 @@
"compression.history": "Original conversation",
"compression.summary": "History summary",
"confirmClearCurrentMessages": "You are about to clear the current conversation messages. Once cleared, they cannot be retrieved. Please confirm your action.",
+ "confirmRemoveAgentOtherCreator": "This agent was created by {{name}}, not you. Deleting it takes it away from its creator and everyone in the workspace.",
+ "confirmRemoveAgentOtherCreatorUnknown": "This agent was created by another member, not you. Deleting it takes it away from its creator and everyone in the workspace.",
"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 category. 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 and its topics. They will be moved to the trash and can be restored within 30 days.",
+ "confirmRemoveSessionItemAlertImpactUnknown": "Couldn't check whether this agent holds other members' content. Deleting it moves every topic under it to the trash, including other members' topics. They can be restored within 30 days.",
+ "confirmRemoveSessionItemAlertWithOthers": "This agent includes comments or messages from other members. Deleting the agent moves them to the trash too, not just your own. They can be restored within 30 days.",
+ "confirmRemoveSessionItemAlertWithOthersCount_one": "This agent has {{count}} topic started by another member. Deleting the agent moves that topic and its comments to the trash too, not just your own. It can be restored within 30 days.",
+ "confirmRemoveSessionItemAlertWithOthersCount_other": "This agent has {{count}} topics started by other members. Deleting the agent moves those topics and their comments to the trash too, not just your own. They can be restored within 30 days.",
"confirmRemoveSessionSuccess": "Agent removed successfully",
"connectAgent.create.back": "Back",
"connectAgent.create.connect": "Connect",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 84c4e05fc81..17506c4a539 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -235,10 +235,16 @@
"compression.history": "原始对话",
"compression.summary": "历史记录摘要",
"confirmClearCurrentMessages": "确认清空当前会话消息吗?清空后无法恢复",
+ "confirmRemoveAgentOtherCreator": "这是 {{name}} 创建的助手,不是你的。删除后,创建者和工作区里的其他人都将无法再使用它。",
+ "confirmRemoveAgentOtherCreatorUnknown": "这是其他成员创建的助手,不是你的。删除后,创建者和工作区里的其他人都将无法再使用它。",
"confirmRemoveChatGroupItemAlert": "确认删除该群组吗?群组专有助理将会被同样删除,外部助理不受影响",
"confirmRemoveGroupItemAlert": "确认删除该分类吗?分类内的助理会移回默认列表",
"confirmRemoveGroupSuccess": "群组已删除",
"confirmRemoveSessionItemAlert": "即将删除此助手及其话题。它们会移入回收站,30 天内可以恢复。",
+ "confirmRemoveSessionItemAlertImpactUnknown": "暂时无法确认此助手下是否有其他成员的内容。删除后,助手下的所有话题(包括其他成员的)都会移入回收站,30 天内可以恢复。",
+ "confirmRemoveSessionItemAlertWithOthers": "此助手包含其他成员的评论或消息。删除助手会把它们一并移入回收站,而不只是你自己的。30 天内可以恢复。",
+ "confirmRemoveSessionItemAlertWithOthersCount_one": "此助手下有 {{count}} 个其他成员的话题。删除助手会把这些话题(含评论)一并移入回收站,而不只是你自己的。30 天内可以恢复。",
+ "confirmRemoveSessionItemAlertWithOthersCount_other": "此助手下有 {{count}} 个其他成员的话题。删除助手会把这些话题(含评论)一并移入回收站,而不只是你自己的。30 天内可以恢复。",
"confirmRemoveSessionSuccess": "助理已删除",
"connectAgent.create.back": "上一步",
"connectAgent.create.connect": "接入",
diff --git a/packages/database/src/models/__tests__/agent.characterization.test.ts b/packages/database/src/models/__tests__/agent.characterization.test.ts
index 5fcf8274a6d..e3f32cd6cdb 100644
--- a/packages/database/src/models/__tests__/agent.characterization.test.ts
+++ b/packages/database/src/models/__tests__/agent.characterization.test.ts
@@ -79,6 +79,7 @@ const PUBLIC_METHODS = [
'getAgentVisibilityMeta',
'getAssignableSessionGroupVisibility',
'getBuiltinAgent',
+ 'getDeleteImpact',
'getGroupMembershipImpact',
'getTopicShareSubject',
'hasTrashedOwner',
diff --git a/packages/database/src/models/__tests__/agent.transferGuards.test.ts b/packages/database/src/models/__tests__/agent.transferGuards.test.ts
index 917b02ac8d1..6eb361de9e4 100644
--- a/packages/database/src/models/__tests__/agent.transferGuards.test.ts
+++ b/packages/database/src/models/__tests__/agent.transferGuards.test.ts
@@ -169,6 +169,192 @@ describe('AgentModel.transferHasForeignRows', () => {
});
});
+describe('AgentModel.getDeleteImpact', () => {
+ it('reports nothing foreign when every cascaded row belongs to the caller', async () => {
+ await linkSession('agtg-own-session', ownerId);
+ await serverDB
+ .insert(topics)
+ .values({ agentId, id: 'agtg-own-topic', userId: ownerId, workspaceId: wsId });
+
+ expect(await ownerModel.getDeleteImpact(agentId)).toEqual({
+ foreignTopicCount: 0,
+ hasForeignContent: false,
+ });
+ });
+
+ it("counts teammates' live topics reached via the agent or its sessions", async () => {
+ await linkSession('agtg-teammate-session', teammateId);
+ await serverDB.insert(topics).values([
+ { agentId, id: 'agtg-own-topic', userId: ownerId, workspaceId: wsId },
+ { agentId, id: 'agtg-teammate-topic', userId: teammateId, workspaceId: wsId },
+ {
+ id: 'agtg-teammate-session-topic',
+ sessionId: 'agtg-teammate-session',
+ userId: teammateId,
+ workspaceId: wsId,
+ },
+ {
+ agentId,
+ id: 'agtg-teammate-trashed-topic',
+ isDeleted: true,
+ userId: teammateId,
+ workspaceId: wsId,
+ },
+ ]);
+
+ expect(await ownerModel.getDeleteImpact(agentId)).toEqual({
+ foreignTopicCount: 2,
+ hasForeignContent: true,
+ });
+ });
+
+ it("flags a teammate's comment on the caller's own topic without counting a topic", async () => {
+ await serverDB
+ .insert(topics)
+ .values({ agentId, id: 'agtg-own-topic', userId: ownerId, workspaceId: wsId });
+ await serverDB.insert(topicComments).values({
+ authorUserId: teammateId,
+ clientId: 'agtg-comment-client',
+ content: 'teammate note',
+ topicId: 'agtg-own-topic',
+ workspaceId: wsId,
+ });
+
+ expect(await ownerModel.getDeleteImpact(agentId)).toEqual({
+ foreignTopicCount: 0,
+ hasForeignContent: true,
+ });
+ });
+
+ it("ignores a teammate's empty session, thread and task, which the trash cascade leaves in place", async () => {
+ await linkSession('agtg-teammate-session', teammateId);
+ await serverDB
+ .insert(topics)
+ .values({ agentId, id: 'agtg-own-topic', userId: ownerId, workspaceId: wsId });
+ await serverDB.insert(threads).values({
+ agentId,
+ id: 'agtg-teammate-thread',
+ topicId: 'agtg-own-topic',
+ type: 'standalone',
+ userId: teammateId,
+ });
+ await serverDB.insert(tasks).values({
+ assigneeAgentId: agentId,
+ createdByUserId: teammateId,
+ identifier: 'AGTG-1',
+ instruction: 'teammate task',
+ seq: 1,
+ workspaceId: wsId,
+ });
+
+ expect(await ownerModel.getDeleteImpact(agentId)).toEqual({
+ foreignTopicCount: 0,
+ hasForeignContent: false,
+ });
+ });
+
+ it("flags a teammate's topicless message on the agent, which the cascade trashes", async () => {
+ await serverDB
+ .insert(messages)
+ .values({ agentId, id: 'agtg-teammate-message', role: 'user', userId: teammateId });
+
+ expect(await ownerModel.getDeleteImpact(agentId)).toEqual({
+ foreignTopicCount: 0,
+ hasForeignContent: true,
+ });
+ });
+
+ it("ignores a teammate's message inside a topic that is already in the trash", async () => {
+ await serverDB.insert(topics).values({
+ agentId,
+ id: 'agtg-teammate-trashed-topic',
+ isDeleted: true,
+ userId: teammateId,
+ workspaceId: wsId,
+ });
+ await serverDB.insert(messages).values({
+ agentId,
+ id: 'agtg-teammate-message',
+ role: 'user',
+ topicId: 'agtg-teammate-trashed-topic',
+ userId: teammateId,
+ });
+
+ expect(await ownerModel.getDeleteImpact(agentId)).toEqual({
+ foreignTopicCount: 0,
+ hasForeignContent: false,
+ });
+ });
+
+ it("flags a teammate's message inside the caller's live topic", async () => {
+ await serverDB
+ .insert(topics)
+ .values({ agentId, id: 'agtg-own-topic', userId: ownerId, workspaceId: wsId });
+ await serverDB.insert(messages).values({
+ agentId,
+ id: 'agtg-teammate-message',
+ role: 'user',
+ topicId: 'agtg-own-topic',
+ userId: teammateId,
+ });
+
+ expect(await ownerModel.getDeleteImpact(agentId)).toEqual({
+ foreignTopicCount: 0,
+ hasForeignContent: true,
+ });
+ });
+
+ it("flags a teammate's message in the caller's live topic even without the agent or session on the message", async () => {
+ await serverDB
+ .insert(topics)
+ .values({ agentId, id: 'agtg-own-topic', userId: ownerId, workspaceId: wsId });
+ await serverDB.insert(messages).values({
+ id: 'agtg-teammate-message',
+ role: 'user',
+ topicId: 'agtg-own-topic',
+ userId: teammateId,
+ });
+
+ expect(await ownerModel.getDeleteImpact(agentId)).toEqual({
+ foreignTopicCount: 0,
+ hasForeignContent: true,
+ });
+ });
+
+ it("ignores a teammate's message tagged with the agent but kept in a topic outside the cascade", async () => {
+ await serverDB
+ .insert(topics)
+ .values({ id: 'agtg-unrelated-topic', userId: ownerId, workspaceId: wsId });
+ await serverDB.insert(messages).values({
+ agentId,
+ id: 'agtg-teammate-message',
+ role: 'user',
+ topicId: 'agtg-unrelated-topic',
+ userId: teammateId,
+ });
+
+ expect(await ownerModel.getDeleteImpact(agentId)).toEqual({
+ foreignTopicCount: 0,
+ hasForeignContent: false,
+ });
+ });
+
+ it("ignores a teammate's message that is already in the trash", async () => {
+ await serverDB.insert(messages).values({
+ agentId,
+ id: 'agtg-teammate-message',
+ isDeleted: true,
+ role: 'user',
+ userId: teammateId,
+ });
+
+ expect(await ownerModel.getDeleteImpact(agentId)).toEqual({
+ foreignTopicCount: 0,
+ hasForeignContent: false,
+ });
+ });
+});
+
describe('AgentModel.transferAgentOwnership guards', () => {
const handover = (model: AgentModel) =>
serverDB.transaction((trx) =>
diff --git a/packages/database/src/models/agent/index.ts b/packages/database/src/models/agent/index.ts
index a7765d429c7..a39664acb09 100644
--- a/packages/database/src/models/agent/index.ts
+++ b/packages/database/src/models/agent/index.ts
@@ -129,6 +129,7 @@ export class AgentModel {
// **************** Transfer *************** //
transferHasForeignRows = this.withContext(transfer.transferHasForeignRows);
+ getDeleteImpact = this.withContext(transfer.getDeleteImpact);
/**
* Cross-scope transfer of agents and everything they own. The unit of work
* spans many aggregates, so it lives in {@link AgentTransferRepository};
diff --git a/packages/database/src/models/agent/transfer.ts b/packages/database/src/models/agent/transfer.ts
index 6d7fb6f042c..374193fe08a 100644
--- a/packages/database/src/models/agent/transfer.ts
+++ b/packages/database/src/models/agent/transfer.ts
@@ -1,6 +1,7 @@
-import { and, inArray, ne, or } from 'drizzle-orm';
+import { and, count, eq, inArray, isNotNull, isNull, ne, or } from 'drizzle-orm';
import { agentsToSessions, messages, sessions, tasks, threads, topics } from '../../schemas';
+import { notTrashed } from '../../utils/softDelete';
import { hasForeignTopicComments } from '../topicComment';
import { type AgentModelContext } from './context';
@@ -89,3 +90,69 @@ export const transferHasForeignRows = async (
.limit(1);
return !!foreignTask;
};
+
+/**
+ * What deleting the agent takes down besides the caller's own work, for the
+ * delete confirmation and the author's delete guard. Mirrors the trash
+ * cascade (`softDeleteAgent`), which stamps only the agent, every live topic
+ * under it (with its messages and comments) and its topicless messages —
+ * linked sessions, threads and tasks stay where they are, so they never count:
+ * - `foreignTopicCount`: live topics other members started under the agent;
+ * - `hasForeignContent`: that, or a teammate's comment / message riding along
+ * inside the caller's own topics or among the topicless messages.
+ */
+export const getDeleteImpact = async (
+ ctx: AgentModelContext,
+ agentId: string,
+): Promise<{ foreignTopicCount: number; hasForeignContent: boolean }> => {
+ const links = await ctx.db
+ .select({ sessionId: agentsToSessions.sessionId })
+ .from(agentsToSessions)
+ .where(eq(agentsToSessions.agentId, agentId));
+ const sessionIds = [...new Set(links.map((link) => link.sessionId))];
+
+ const topicWhere = and(
+ sessionIds.length > 0
+ ? or(inArray(topics.sessionId, sessionIds), eq(topics.agentId, agentId))
+ : eq(topics.agentId, agentId),
+ notTrashed(topics.isDeleted),
+ )!;
+ const [row] = await ctx.db
+ .select({ count: count() })
+ .from(topics)
+ .where(and(topicWhere, ne(topics.userId, ctx.userId)));
+ const foreignTopicCount = Number(row?.count ?? 0);
+ if (foreignTopicCount > 0) return { foreignTopicCount, hasForeignContent: true };
+
+ // Every live topic here is the caller's, so a foreign comment rides along
+ // inside one of them. NULL authors (deleted accounts) count as foreign.
+ if (await hasForeignTopicComments(ctx.db, ctx.userId, topicWhere))
+ return { foreignTopicCount, hasForeignContent: true };
+
+ // Mirror the cascade exactly: every message inside an affected live topic
+ // (matched through the topic, whatever agent / session the message itself
+ // carries), plus the topicless messages `softDeleteTopicless` stamps by
+ // agent or session. A message in a topic outside the cascade, or inside an
+ // already-trashed topic, stays where it is and does not count.
+ const topiclessScope =
+ sessionIds.length > 0
+ ? or(inArray(messages.sessionId, sessionIds), eq(messages.agentId, agentId))
+ : eq(messages.agentId, agentId);
+ const [foreignMessage] = await ctx.db
+ .select({ id: messages.id })
+ .from(messages)
+ .leftJoin(topics, eq(messages.topicId, topics.id))
+ .where(
+ and(
+ ne(messages.userId, ctx.userId),
+ notTrashed(messages.isDeleted),
+ or(
+ and(isNull(messages.topicId), topiclessScope),
+ and(isNotNull(messages.topicId), topicWhere),
+ ),
+ ),
+ )
+ .limit(1);
+
+ return { foreignTopicCount, hasForeignContent: !!foreignMessage };
+};
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 0eb97162945..219ded712ca 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -398,6 +398,10 @@ export default {
'compression.summary': 'History summary',
'confirmClearCurrentMessages':
'You are about to clear the current conversation messages. Once cleared, they cannot be retrieved. Please confirm your action.',
+ 'confirmRemoveAgentOtherCreator':
+ 'This agent was created by {{name}}, not you. Deleting it takes it away from its creator and everyone in the workspace.',
+ 'confirmRemoveAgentOtherCreatorUnknown':
+ 'This agent was created by another member, not you. Deleting it takes it away from its creator and everyone in the workspace.',
'confirmRemoveChatGroupItemAlert':
'This Group will be deleted. Group-specific assistants will also be deleted, while external assistants will not be affected.',
'confirmRemoveGroupItemAlert':
@@ -405,6 +409,14 @@ export default {
'confirmRemoveGroupSuccess': 'Group deleted successfully',
'confirmRemoveSessionItemAlert':
'You are about to delete this agent and its topics. They will be moved to the trash and can be restored within 30 days.',
+ 'confirmRemoveSessionItemAlertImpactUnknown':
+ "Couldn't check whether this agent holds other members' content. Deleting it moves every topic under it to the trash, including other members' topics. They can be restored within 30 days.",
+ 'confirmRemoveSessionItemAlertWithOthers':
+ 'This agent includes comments or messages from other members. Deleting the agent moves them to the trash too, not just your own. They can be restored within 30 days.',
+ 'confirmRemoveSessionItemAlertWithOthersCount_one':
+ 'This agent has {{count}} topic started by another member. Deleting the agent moves that topic and its comments to the trash too, not just your own. It can be restored within 30 days.',
+ 'confirmRemoveSessionItemAlertWithOthersCount_other':
+ 'This agent has {{count}} topics started by other members. Deleting the agent moves those topics and their comments to the trash too, not just your own. They can be restored within 30 days.',
'confirmRemoveSessionSuccess': 'Agent removed successfully',
'defaultAgent': 'Default Agent',
'defaultGroupChat': 'Group',
diff --git a/packages/types/src/agent/deleteImpact.ts b/packages/types/src/agent/deleteImpact.ts
new file mode 100644
index 00000000000..6d7ba3acf1b
--- /dev/null
+++ b/packages/types/src/agent/deleteImpact.ts
@@ -0,0 +1,17 @@
+/**
+ * What deleting an agent would take down besides the caller's own work, as the
+ * delete confirmation shows it (`agent.getAgentDeleteImpact`).
+ */
+export interface AgentDeleteImpact {
+ /** The agent was created by another member, not the caller. */
+ createdByOther: boolean;
+ /**
+ * Display name of the agent's creator when it is someone other than the
+ * caller (`null` when the caller created it, or the account has no name).
+ */
+ creatorName: string | null;
+ /** Live topics other members started under the agent. */
+ foreignTopicCount: number;
+ /** Other members' topics, comments or messages go to the trash with it. */
+ hasForeignContent: boolean;
+}
diff --git a/packages/types/src/agent/index.ts b/packages/types/src/agent/index.ts
index a6b6e5ec886..23744664acd 100644
--- a/packages/types/src/agent/index.ts
+++ b/packages/types/src/agent/index.ts
@@ -2,6 +2,7 @@ export * from './agencyConfig';
export * from './agentConfig';
export * from './agentIntervention';
export * from './chatConfig';
+export type * from './deleteImpact';
export * from './displayName';
export * from './document';
export * from './executionTargetRules';
diff --git a/src/features/AgentDeleteConfirm/index.test.ts b/src/features/AgentDeleteConfirm/index.test.ts
new file mode 100644
index 00000000000..90284f42a50
--- /dev/null
+++ b/src/features/AgentDeleteConfirm/index.test.ts
@@ -0,0 +1,189 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentService } from '@/services/agent';
+
+import {
+ confirmRemoveAgent,
+ getOtherCreatorWarning,
+ getRemoveAgentAlert,
+ getRemoveAgentConfirmState,
+} from './index';
+
+const createModalMock = vi.hoisted(() => vi.fn());
+
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ createModal: createModalMock,
+}));
+
+vi.mock('i18next', () => ({
+ t: (key: string, options?: { count?: number; name?: string }) =>
+ options?.count !== undefined
+ ? `${key}:${options.count}`
+ : options?.name !== undefined
+ ? `${key}:${options.name}`
+ : key,
+}));
+
+type Impact = Awaited<ReturnType<typeof agentService.getAgentDeleteImpact>>;
+
+const own = { createdByOther: false, creatorName: null } as const;
+const others = (creatorName: string | null) => ({ createdByOther: true, creatorName }) as const;
+
+describe('getRemoveAgentAlert', () => {
+ it("warns with the count of other members' topics", () => {
+ expect(getRemoveAgentAlert({ foreignTopicCount: 3, hasForeignContent: true })).toBe(
+ 'confirmRemoveSessionItemAlertWithOthersCount:3',
+ );
+ });
+
+ it('falls back to the generic other-members warning when no foreign topic is counted', () => {
+ expect(getRemoveAgentAlert({ foreignTopicCount: 0, hasForeignContent: true })).toBe(
+ 'confirmRemoveSessionItemAlertWithOthers',
+ );
+ });
+
+ it('keeps the plain copy when only the caller owns content', () => {
+ expect(getRemoveAgentAlert({ foreignTopicCount: 0, hasForeignContent: false })).toBe(
+ 'confirmRemoveSessionItemAlert',
+ );
+ });
+
+ it("warns that teammates' topics may go too when the lookup failed", () => {
+ expect(getRemoveAgentAlert(null)).toBe('confirmRemoveSessionItemAlertImpactUnknown');
+ });
+});
+
+describe('getRemoveAgentConfirmState', () => {
+ it('keeps Delete disabled while the impact lookup is in flight', () => {
+ expect(getRemoveAgentConfirmState(undefined)).toEqual({
+ acknowledgeForeignContent: false,
+ acknowledgeOtherCreator: false,
+ alert: null,
+ canConfirm: false,
+ otherCreatorWarning: null,
+ });
+ });
+
+ it("enables Delete with the warning and acknowledges teammates' content once it loaded", () => {
+ expect(
+ getRemoveAgentConfirmState({ ...own, foreignTopicCount: 3, hasForeignContent: true }),
+ ).toEqual({
+ acknowledgeForeignContent: true,
+ acknowledgeOtherCreator: false,
+ alert: 'confirmRemoveSessionItemAlertWithOthersCount:3',
+ canConfirm: true,
+ otherCreatorWarning: null,
+ });
+ });
+
+ it('acknowledges nothing when only the caller owns content', () => {
+ expect(
+ getRemoveAgentConfirmState({ ...own, foreignTopicCount: 0, hasForeignContent: false }),
+ ).toEqual({
+ acknowledgeForeignContent: false,
+ acknowledgeOtherCreator: false,
+ alert: 'confirmRemoveSessionItemAlert',
+ canConfirm: true,
+ otherCreatorWarning: null,
+ });
+ });
+
+ it('warns about unknown impact without acknowledging anything when the lookup failed', () => {
+ expect(getRemoveAgentConfirmState(null)).toEqual({
+ acknowledgeForeignContent: false,
+ acknowledgeOtherCreator: false,
+ alert: 'confirmRemoveSessionItemAlertImpactUnknown',
+ canConfirm: true,
+ otherCreatorWarning: null,
+ });
+ });
+
+ it('warns that someone else created the agent and acknowledges both facts for an Admin delete', () => {
+ expect(
+ getRemoveAgentConfirmState({
+ ...others('速冻鱼'),
+ foreignTopicCount: 5,
+ hasForeignContent: true,
+ }),
+ ).toEqual({
+ acknowledgeForeignContent: true,
+ acknowledgeOtherCreator: true,
+ alert: 'confirmRemoveSessionItemAlertWithOthersCount:5',
+ canConfirm: true,
+ otherCreatorWarning: 'confirmRemoveAgentOtherCreator:速冻鱼',
+ });
+ });
+});
+
+describe('getOtherCreatorWarning', () => {
+ it('names the creator', () => {
+ expect(
+ getOtherCreatorWarning({
+ ...others('Tsuki'),
+ foreignTopicCount: 0,
+ hasForeignContent: false,
+ }),
+ ).toBe('confirmRemoveAgentOtherCreator:Tsuki');
+ });
+
+ it('falls back to "another member" when the creator has no name', () => {
+ expect(
+ getOtherCreatorWarning({ ...others(null), foreignTopicCount: 0, hasForeignContent: false }),
+ ).toBe('confirmRemoveAgentOtherCreatorUnknown');
+ });
+
+ it("stays silent on the caller's own agent or a failed lookup", () => {
+ expect(
+ getOtherCreatorWarning({ ...own, foreignTopicCount: 2, hasForeignContent: true }),
+ ).toBeNull();
+ expect(getOtherCreatorWarning(null)).toBeNull();
+ });
+});
+
+describe('confirmRemoveAgent', () => {
+ beforeEach(() => {
+ createModalMock.mockReset();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('opens the dialog right away, before the impact lookup lands', () => {
+ vi.spyOn(agentService, 'getAgentDeleteImpact').mockReturnValue(new Promise<Impact>(() => {}));
+
+ confirmRemoveAgent({ agentId: 'agent-1', onConfirm: vi.fn() });
+
+ expect(createModalMock).toHaveBeenCalledTimes(1);
+ expect(createModalMock.mock.calls[0][0]).toMatchObject({ title: 'delete', width: 420 });
+ expect(agentService.getAgentDeleteImpact).toHaveBeenCalledWith('agent-1');
+ });
+
+ it('still opens the dialog when the impact lookup throws synchronously', async () => {
+ vi.spyOn(agentService, 'getAgentDeleteImpact').mockImplementation(() => {
+ throw new TypeError('not a function');
+ });
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ expect(() => confirmRemoveAgent({ agentId: 'agent-1', onConfirm: vi.fn() })).not.toThrow();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(createModalMock).toHaveBeenCalledTimes(1);
+ expect(consoleError).toHaveBeenCalled();
+ });
+
+ it('does not reject when the impact lookup fails', async () => {
+ vi.spyOn(agentService, 'getAgentDeleteImpact').mockRejectedValue(new Error('network'));
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ confirmRemoveAgent({ agentId: 'agent-1', onConfirm: vi.fn() });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(createModalMock).toHaveBeenCalledTimes(1);
+ expect(consoleError).toHaveBeenCalled();
+ });
+});
diff --git a/src/features/AgentDeleteConfirm/index.tsx b/src/features/AgentDeleteConfirm/index.tsx
new file mode 100644
index 00000000000..3c957802efc
--- /dev/null
+++ b/src/features/AgentDeleteConfirm/index.tsx
@@ -0,0 +1,178 @@
+import { type AgentDeleteImpact } from '@lobechat/types';
+import { Alert, Button, createModal, ModalFooter, Skeleton, useModalContext } from '@lobehub/ui';
+import { t } from 'i18next';
+import { type ReactNode, Suspense, use, useState } from 'react';
+
+import { agentService, type RemoveAgentOptions } from '@/services/agent';
+
+interface ConfirmRemoveAgentOptions {
+ agentId: string;
+ /**
+ * Runs the delete. Pass the options on to `removeAgent`: they carry the
+ * acknowledgment that lets an author delete an agent holding teammates'
+ * content, set only when the dialog actually warned about it.
+ */
+ onConfirm: (options: RemoveAgentOptions) => Promise<void> | void;
+}
+
+/**
+ * Pick the confirmation copy for an agent delete. The cascade trashes every
+ * topic under the agent, teammates' included, so the dialog must say so when
+ * they exist — with a count when other members started topics, or the generic
+ * "includes other members' content" line when only comments or messages are
+ * foreign. A failed lookup (`null`) cannot rule teammates' content out, so it
+ * warns that every topic goes rather than showing the plain copy: workspace
+ * owners skip the server guard and would otherwise delete it unwarned.
+ */
+export const getRemoveAgentAlert = (
+ impact: Pick<AgentDeleteImpact, 'foreignTopicCount' | 'hasForeignContent'> | null,
+): string => {
+ if (impact === null) return t('confirmRemoveSessionItemAlertImpactUnknown', { ns: 'chat' });
+ if (impact && impact.foreignTopicCount > 0)
+ return t('confirmRemoveSessionItemAlertWithOthersCount', {
+ count: impact.foreignTopicCount,
+ ns: 'chat',
+ });
+ if (impact?.hasForeignContent)
+ return t('confirmRemoveSessionItemAlertWithOthers', { ns: 'chat' });
+ return t('confirmRemoveSessionItemAlert', { ns: 'chat' });
+};
+
+/**
+ * The strong warning shown when someone other than the caller created the
+ * agent — a workspace Admin or Owner deleting a member's agent. `null` when
+ * the caller created it.
+ */
+export const getOtherCreatorWarning = (impact: AgentDeleteImpact | null): string | null => {
+ if (!impact?.createdByOther) return null;
+ return impact.creatorName
+ ? t('confirmRemoveAgentOtherCreator', { name: impact.creatorName, ns: 'chat' })
+ : t('confirmRemoveAgentOtherCreatorUnknown', { ns: 'chat' });
+};
+
+/**
+ * The dialog's state for an impact lookup: `undefined` while it is in flight,
+ * `null` once it failed. Delete stays disabled until the lookup settles, so no
+ * one — workspace owners included — can confirm before reading the warning.
+ * A failed lookup shows the "can't tell, every topic goes" warning and
+ * acknowledges nothing, which keeps the server guard on for non-owners while an
+ * older server without the lookup can still delete.
+ */
+export const getRemoveAgentConfirmState = (impact: AgentDeleteImpact | null | undefined) => {
+ if (impact === undefined)
+ return {
+ acknowledgeForeignContent: false,
+ acknowledgeOtherCreator: false,
+ alert: null,
+ canConfirm: false,
+ otherCreatorWarning: null,
+ } as const;
+ return {
+ acknowledgeForeignContent: !!impact?.hasForeignContent,
+ acknowledgeOtherCreator: !!impact?.createdByOther,
+ alert: getRemoveAgentAlert(impact),
+ canConfirm: true,
+ otherCreatorWarning: getOtherCreatorWarning(impact),
+ } as const;
+};
+
+interface ConfirmLayoutProps {
+ content: ReactNode;
+ onConfirm?: () => Promise<void> | void;
+}
+
+const ConfirmLayout = ({ content, onConfirm }: ConfirmLayoutProps) => {
+ const { close } = useModalContext();
+ const [deleting, setDeleting] = useState(false);
+
+ const handleConfirm = async () => {
+ if (!onConfirm) return;
+ setDeleting(true);
+ try {
+ await onConfirm();
+ } catch {
+ setDeleting(false);
+ return;
+ }
+ close();
+ };
+
+ return (
+ <>
+ <div style={{ padding: '12px 16px' }}>{content}</div>
+ <ModalFooter>
+ <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>
+ <Button
+ danger
+ disabled={!onConfirm}
+ loading={deleting}
+ type={'primary'}
+ onClick={handleConfirm}
+ >
+ {t('delete', { ns: 'common' })}
+ </Button>
+ </ModalFooter>
+ </>
+ );
+};
+
+interface LoadedConfirmProps {
+ impact: Promise<AgentDeleteImpact | null>;
+ onConfirm: ConfirmRemoveAgentOptions['onConfirm'];
+}
+
+const LoadedConfirm = ({ impact, onConfirm }: LoadedConfirmProps) => {
+ const state = getRemoveAgentConfirmState(use(impact));
+
+ // Someone else's agent: both facts go into one error alert, so the creator
+ // and the other members' topics cannot be skimmed past as routine copy.
+ const content = state.otherCreatorWarning ? (
+ <Alert showIcon description={state.alert} title={state.otherCreatorWarning} type={'error'} />
+ ) : (
+ state.alert
+ );
+
+ return (
+ <ConfirmLayout
+ content={content}
+ onConfirm={() =>
+ onConfirm({
+ acknowledgeForeignContent: state.acknowledgeForeignContent,
+ acknowledgeOtherCreator: state.acknowledgeOtherCreator,
+ })
+ }
+ />
+ );
+};
+
+/**
+ * Open the shared agent deletion confirmation. Every delete entry point (the
+ * sidebar, the mobile list, the agent profile) goes through here so authors
+ * and workspace owners read the same warning about other members' topics.
+ *
+ * The dialog opens right away, bound to `agentId`: its mask keeps the user on
+ * the agent they started from instead of a late dialog surfacing over another
+ * one. It shows a placeholder with Delete disabled until the impact lookup
+ * settles (see `getRemoveAgentConfirmState`).
+ */
+export const confirmRemoveAgent = ({ agentId, onConfirm }: ConfirmRemoveAgentOptions): void => {
+ // Built inside a promise executor so a lookup that throws synchronously
+ // still settles as "failed" and the dialog opens with the impact-unknown copy.
+ const impact = new Promise<AgentDeleteImpact>((resolve) =>
+ resolve(agentService.getAgentDeleteImpact(agentId)),
+ ).catch((error) => {
+ console.error('[confirmRemoveAgent]', error);
+ return null;
+ });
+
+ createModal({
+ content: (
+ <Suspense fallback={<ConfirmLayout content={<Skeleton.Text rows={2} />} />}>
+ <LoadedConfirm impact={impact} onConfirm={onConfirm} />
+ </Suspense>
+ ),
+ styles: { content: { padding: 0 } },
+ title: t('delete', { ns: 'common' }),
+ width: 420,
+ });
+};
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx
index f3fd5fde01e..dfb4bbd0560 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx
@@ -14,6 +14,7 @@ const mocks = vi.hoisted(() => ({
canManageSettings: false,
myPinnedIds: [] as string[],
confirmModal: vi.fn(),
+ confirmRemoveAgent: vi.fn(),
copyToClipboard: vi.fn(),
toastError: vi.fn(),
toastSuccess: vi.fn(),
@@ -104,6 +105,9 @@ vi.mock('@/hooks/useResourceManageable', () => ({
}));
vi.mock('@/services/agent', () => ({ agentService: {} }));
+vi.mock('@/features/AgentDeleteConfirm', () => ({
+ confirmRemoveAgent: mocks.confirmRemoveAgent,
+}));
vi.mock('@/features/HomeSidebar/Body/Agent/ModalProvider', () => ({
useOptionalAgentModal: () => null,
@@ -386,12 +390,46 @@ describe('useAgentDropdownMenu', () => {
if (!deleteItem) throw new Error('Expected delete menu item');
deleteItem.onClick({ domEvent: { stopPropagation: vi.fn() } });
- const { onOk } = mocks.confirmModal.mock.calls[0][0] as { onOk: () => Promise<void> };
- await onOk();
+ const { agentId, onConfirm } = mocks.confirmRemoveAgent.mock.calls[0][0] as {
+ agentId: string;
+ onConfirm: (options: { acknowledgeForeignContent: boolean }) => Promise<void>;
+ };
+ expect(agentId).toBe('agent-1');
+ await onConfirm({ acknowledgeForeignContent: true });
+ expect(mocks.home.removeAgent).toHaveBeenCalledWith('agent-1', {
+ acknowledgeForeignContent: true,
+ });
expect(mocks.toastError).toHaveBeenCalledWith('deleteHistoryMigrating');
});
+ const findDeleteItem = (items: unknown[]) =>
+ items.find(
+ (item) => item && typeof item === 'object' && 'key' in item && item.key === 'delete',
+ );
+
+ it("offers delete to a workspace Admin on another member's shared agent", () => {
+ // Admin: not the creator and not the Owner (client `canManage` false), but
+ // the server's `canManage` (AGENT_UPDATE:all) is true.
+ mocks.canEditResource = true;
+ mocks.canManage = false;
+ mocks.canManageResource = true;
+
+ const { result } = renderPublicAgentMenu('member-1');
+
+ expect(findDeleteItem(result.current() ?? [])).toBeDefined();
+ });
+
+ it("hides delete from a member on another member's agent", () => {
+ mocks.canEditResource = true;
+ mocks.canManage = false;
+ mocks.canManageResource = false;
+
+ const { result } = renderPublicAgentMenu('member-1');
+
+ expect(findDeleteItem(result.current() ?? [])).toBeUndefined();
+ });
+
it('stays native-eligible (string labels only, including the Move to Category submenu)', () => {
mocks.canEditResource = true;
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.tsx
index 616021a39a4..662494f50e7 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.tsx
@@ -31,6 +31,7 @@ import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspace
import { useAgentTransferMenuItem } from '@/business/client/hooks/useAgentTransferMenuItem';
import { useAgentTransferToMemberMenuItem } from '@/business/client/hooks/useAgentTransferToMemberMenuItem';
import { openRenameModal } from '@/components/RenameModal';
+import { confirmRemoveAgent } from '@/features/AgentDeleteConfirm';
import { useOptionalAgentModal } from '@/features/HomeSidebar/Body/Agent/ModalProvider';
import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';
@@ -171,6 +172,10 @@ export const useAgentDropdownMenu = ({
// Row-level ownership: delete/transfer/visibility management stays scoped
// to the creator or a workspace owner, separate from collaborative editing.
const canManage = useResourceManageable(userId);
+ // Delete also opens to a workspace Admin on another member's shared agent
+ // (server `canManage`); the confirmation then warns that someone else created
+ // it, and the server only accepts the delete with that acknowledgment.
+ const canDelete = canManage || canManageResource;
// Cross-workspace Transfer to… / Copy to… items (null when workspace
// feature is off or the viewer lacks permission for this agent)
@@ -575,7 +580,7 @@ export const useAgentDropdownMenu = ({
},
]
: []),
- ...(canManage
+ ...(canDelete
? [
{ type: 'divider' as const },
{
@@ -585,20 +590,16 @@ export const useAgentDropdownMenu = ({
label: t('delete', { ns: 'common' }),
onClick: ({ domEvent }: any) => {
domEvent.stopPropagation();
- confirmModal({
- cancelText: t('cancel', { ns: 'common' }),
- content: t('confirmRemoveSessionItemAlert'),
- okButtonProps: { danger: true },
- okText: t('delete', { ns: 'common' }),
- onOk: async () => {
+ confirmRemoveAgent({
+ agentId: id,
+ onConfirm: async (options) => {
try {
- await removeAgent(id);
+ await removeAgent(id, options);
toast.success(t('confirmRemoveSessionSuccess'));
} catch (error) {
toast.error(t(getDeleteErrorMessageKey(error), { ns: 'common' }));
}
},
- title: t('delete', { ns: 'common' }),
});
},
sfSymbol: 'trash',
@@ -615,8 +616,8 @@ export const useAgentDropdownMenu = ({
canCreate,
canConfigure,
canEdit,
- canManage,
canManageResource,
+ canDelete,
navigate,
pinned,
id,
diff --git a/src/features/MobileHome/SessionListContent/List/Item/Actions.tsx b/src/features/MobileHome/SessionListContent/List/Item/Actions.tsx
index 067b8bfb960..b6143df8f1f 100644
--- a/src/features/MobileHome/SessionListContent/List/Item/Actions.tsx
+++ b/src/features/MobileHome/SessionListContent/List/Item/Actions.tsx
@@ -11,10 +11,12 @@ import { Check, Copy, ListTree, MoreVertical, Pin, PinOff, Plus, Trash } from 'l
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { confirmRemoveAgent } from '@/features/AgentDeleteConfirm';
import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { usePermission } from '@/hooks/usePermission';
import { useResourceManageable } from '@/hooks/useResourceManageable';
+import { type RemoveAgentOptions } from '@/services/agent';
import { chatGroupService } from '@/services/chatGroup';
import { useHomeStore } from '@/store/home';
import { homeAgentListSelectors } from '@/store/home/selectors';
@@ -140,35 +142,43 @@ const Actions = ({
key: 'delete',
title: editReason,
danger: true,
- disabled: !editable || !manageable || !access.canManageResource,
+ // Server `canManage` covers the author, the Owner and — for another
+ // member's shared agent — an Admin, whose delete the confirmation warns
+ // about and the server accepts only with that acknowledgment.
+ disabled: !editable || !access.canManageResource || (item.type === 'group' && !manageable),
icon: <Icon icon={Trash} />,
label: t('delete', { ns: 'common' }),
- onClick: () =>
+ onClick: () => {
+ const onDelete = (options?: RemoveAgentOptions) =>
+ run(async () => {
+ try {
+ if (item.type === 'group') await removeAgentGroup(item.id);
+ else await removeAgent(item.id, options);
+ toast.success(
+ t(
+ item.type === 'group'
+ ? 'confirmRemoveGroupSuccess'
+ : 'confirmRemoveSessionSuccess',
+ ),
+ );
+ } catch (error) {
+ toast.error(t(getDeleteErrorMessageKey(error), { ns: 'common' }));
+ }
+ });
+
+ if (item.type !== 'group') {
+ confirmRemoveAgent({ agentId: item.id, onConfirm: onDelete });
+ return;
+ }
+
confirmModal({
title: t('delete', { ns: 'common' }),
- content: t(
- item.type === 'group'
- ? 'confirmRemoveChatGroupItemAlert'
- : 'confirmRemoveSessionItemAlert',
- ),
+ content: t('confirmRemoveChatGroupItemAlert'),
okText: t('delete', { ns: 'common' }),
okButtonProps: { danger: true },
- onOk: () =>
- run(async () => {
- try {
- await (item.type === 'group' ? removeAgentGroup : removeAgent)(item.id);
- toast.success(
- t(
- item.type === 'group'
- ? 'confirmRemoveGroupSuccess'
- : 'confirmRemoveSessionSuccess',
- ),
- );
- } catch (error) {
- toast.error(t(getDeleteErrorMessageKey(error), { ns: 'common' }));
- }
- }),
- }),
+ onOk: () => onDelete(),
+ });
+ },
},
];
return (
diff --git a/src/routes/(main)/agent/profile/features/Header/index.tsx b/src/routes/(main)/agent/profile/features/Header/index.tsx
index bbcabab069b..c0640cbf786 100644
--- a/src/routes/(main)/agent/profile/features/Header/index.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/index.tsx
@@ -2,7 +2,6 @@ import { isDesktop } from '@lobechat/const';
import { getOptedInPluginIds, type LobeAgentConfig } from '@lobechat/types';
import {
ActionIcon,
- confirmModal,
cssVar,
DropdownMenu,
Flexbox,
@@ -33,6 +32,7 @@ import { useBusinessAgentImportMenuItem } from '@/business/client/hooks/useBusin
import { useHasActiveWorkspace } from '@/business/client/hooks/useHasActiveWorkspace';
import { useAgentShareSupported } from '@/business/client/useAgentShareSupported';
import AgentBreadcrumb from '@/features/AgentBreadcrumb';
+import { confirmRemoveAgent } from '@/features/AgentDeleteConfirm';
import { useAgentMarketSubmission } from '@/features/AgentMarketSubmission/useAgentMarketSubmission';
import AgentProfileTabs, { AGENT_PROFILE_TABS_CENTER_STYLE } from '@/features/AgentProfileTabs';
import { type AgentProfileTab } from '@/features/AgentProfileTabs/tabOptions';
@@ -178,11 +178,11 @@ const Header = memo<HeaderProps>(({ active = 'profile' }) => {
const handleDelete = useCallback(() => {
if (!canManage || !activeAgentId) return;
- confirmModal({
- okButtonProps: { danger: true },
- onOk: async () => {
+ confirmRemoveAgent({
+ agentId: activeAgentId,
+ onConfirm: async (options) => {
try {
- await removeAgent(activeAgentId);
+ await removeAgent(activeAgentId, options);
} catch (error) {
toast.error(t(getDeleteErrorMessageKey(error), { ns: 'common' }));
return;
@@ -190,9 +190,6 @@ const Header = memo<HeaderProps>(({ active = 'profile' }) => {
toast.success(t('confirmRemoveSessionSuccess', { ns: 'chat' }));
navigate('/');
},
- content: t('confirmRemoveSessionItemAlert', { ns: 'chat' }),
- okText: t('delete', { ns: 'common' }),
- title: t('delete', { ns: 'common' }),
});
}, [activeAgentId, canManage, navigate, removeAgent, t]);
diff --git a/src/services/agent.ts b/src/services/agent.ts
index 8101d51ffb8..21e28bef34e 100644
--- a/src/services/agent.ts
+++ b/src/services/agent.ts
@@ -1,4 +1,9 @@
-import { type AgentItem, type AgentRankItem, type LobeAgentConfig } from '@lobechat/types';
+import {
+ type AgentDeleteImpact,
+ type AgentItem,
+ type AgentRankItem,
+ type LobeAgentConfig,
+} from '@lobechat/types';
import { type PartialDeep } from 'type-fest';
import { lambdaClient } from '@/libs/trpc/client';
@@ -109,6 +114,13 @@ interface AgentGroupMembershipImpactRef {
groupVisible: boolean;
}
+export interface RemoveAgentOptions {
+ /** The user confirmed a warning that other members' content goes with the agent. */
+ acknowledgeForeignContent?: boolean;
+ /** The user confirmed a warning that someone else created the agent. */
+ acknowledgeOtherCreator?: boolean;
+}
+
class AgentService {
/**
* Check if an agent with the given marketIdentifier already exists
@@ -293,8 +305,17 @@ class AgentService {
/**
* Remove an agent and its associated session
*/
- removeAgent = async (agentId: string) => {
- return lambdaClient.agent.removeAgent.mutate({ agentId });
+ removeAgent = async (agentId: string, options?: RemoveAgentOptions) => {
+ return lambdaClient.agent.removeAgent.mutate({ agentId, ...options });
+ };
+
+ /**
+ * What deleting the agent takes down besides the caller's own work — other
+ * members' topics (counted) and any other foreign content — for the delete
+ * confirmation.
+ */
+ getAgentDeleteImpact = async (agentId: string): Promise<AgentDeleteImpact> => {
+ return lambdaClient.agent.getAgentDeleteImpact.query({ agentId });
};
/**
diff --git a/src/store/home/slices/sidebarUI/action.test.ts b/src/store/home/slices/sidebarUI/action.test.ts
index 58cb15d9b3d..1c9f03d9fd4 100644
--- a/src/store/home/slices/sidebarUI/action.test.ts
+++ b/src/store/home/slices/sidebarUI/action.test.ts
@@ -180,7 +180,7 @@ describe('createSidebarUISlice', () => {
await result.current.removeAgent(mockAgentId);
});
- expect(agentService.removeAgent).toHaveBeenCalledWith(mockAgentId);
+ expect(agentService.removeAgent).toHaveBeenCalledWith(mockAgentId, undefined);
expect(spyOnRefresh).toHaveBeenCalled();
});
diff --git a/src/store/home/slices/sidebarUI/action.ts b/src/store/home/slices/sidebarUI/action.ts
index 5df90b76a2a..81ae306faeb 100644
--- a/src/store/home/slices/sidebarUI/action.ts
+++ b/src/store/home/slices/sidebarUI/action.ts
@@ -2,7 +2,7 @@ import { toast } from '@lobehub/ui';
import { t } from 'i18next';
import { cacheScope } from '@/libs/replica';
-import { agentService } from '@/services/agent';
+import { agentService, type RemoveAgentOptions } from '@/services/agent';
import { chatGroupService } from '@/services/chatGroup';
import { homeService } from '@/services/home';
import { sessionService } from '@/services/session';
@@ -160,8 +160,8 @@ export class SidebarUIActionImpl {
await operation;
};
- removeAgent = async (agentId: string): Promise<void> => {
- await agentService.removeAgent(agentId);
+ removeAgent = async (agentId: string, options?: RemoveAgentOptions): Promise<void> => {
+ await agentService.removeAgent(agentId, options);
await this.#get().refreshAgentList();
// 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)