Skip to content

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

🐛 fix(topic): delete uploaded attachments when removing a topic (#16030)

Arvin Xu1b67c1a6bdf0
diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.ts
index 112e418e0e6..cc4a2aef22e 100644
--- a/apps/server/src/routers/lambda/topic.ts
+++ b/apps/server/src/routers/lambda/topic.ts
@@ -14,9 +14,11 @@ import { z } from 'zod';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { serverDBEnv } from '@/config/db';
import { AgentModel } from '@/database/models/agent';
import { AgentOperationModel } from '@/database/models/agentOperation';
import { ChatGroupModel } from '@/database/models/chatGroup';
+import { FileModel } from '@/database/models/file';
import { MessageModel } from '@/database/models/message';
import { TopicModel } from '@/database/models/topic';
import { TopicShareModel } from '@/database/models/topicShare';
@@ -26,6 +28,7 @@ import { TopicImporterRepo } from '@/database/repositories/topicImporter';
import { chatGroups } from '@/database/schemas';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { FileService } from '@/server/services/file';
import { type BatchTaskResult } from '@/types/service';
import {
@@ -579,9 +582,31 @@ export const topicRouter = router({
removeTopic: topicProcedure
.use(withScopedPermission('topic:delete'))
- .input(z.object({ id: z.string() }))
+ .input(z.object({ id: z.string(), removeFiles: z.boolean().optional() }))
.mutation(async ({ input, ctx }) => {
- return ctx.topicModel.delete(input.id);
+ if (!input.removeFiles) return ctx.topicModel.delete(input.id);
+
+ const wsId = ctx.workspaceId ?? undefined;
+ const fileModel = new FileModel(ctx.serverDB, ctx.userId, wsId);
+
+ // Collect the topic's deletable attachments BEFORE deleting it — the lookup
+ // joins messages, which are cascade-deleted along with the topic. Files
+ // still referenced by another topic or the session are intentionally kept.
+ const fileIds = await fileModel.findDeletableFilesByTopicId(input.id);
+
+ const result = await ctx.topicModel.delete(input.id);
+
+ if (fileIds.length > 0) {
+ const needToRemove = await fileModel.deleteMany(fileIds, serverDBEnv.REMOVE_GLOBAL_FILE);
+ // deleteMany returns only files whose underlying object is no longer
+ // referenced by any other file, so the S3 cleanup is reference-safe.
+ if (needToRemove && needToRemove.length > 0) {
+ const fileService = new FileService(ctx.serverDB, ctx.userId, wsId);
+ await fileService.deleteFiles(needToRemove.map((file) => file.url!));
+ }
+ }
+
+ return result;
}),
searchTopics: topicProcedure
diff --git a/locales/en-US/topic.json b/locales/en-US/topic.json
index d0af0360f2d..dc3b92374df 100644
--- a/locales/en-US/topic.json
+++ b/locales/en-US/topic.json
@@ -4,6 +4,8 @@
"actions.autoRename": "Smart Rename",
"actions.confirmRemoveAll": "You are about to delete all topics. This action cannot be undone.",
"actions.confirmRemoveTopic": "You are about to delete this topic. This action cannot be undone.",
+ "actions.confirmRemoveTopicFiles": "Also delete images and files uploaded in this topic",
+ "actions.confirmRemoveTopicTitle": "Delete this topic?",
"actions.confirmRemoveUnstarred": "You are about to delete unstarred topics. This action cannot be undone.",
"actions.copyLink": "Copy Link",
"actions.copyLinkSuccess": "Link copied",
@@ -20,6 +22,7 @@
"actions.openInNewTab": "Open in New Tab",
"actions.openInNewWindow": "Open in a new window",
"actions.removeAll": "Delete All Topics",
+ "actions.removeTopic": "Delete Topic",
"actions.removeUnstarred": "Delete Unstarred Topics",
"actions.unfavorite": "Unfavorite",
"actions.unmarkCompleted": "Unarchive",
diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.json
index 7bd0bd90154..4ab9b91888a 100644
--- a/locales/zh-CN/topic.json
+++ b/locales/zh-CN/topic.json
@@ -4,6 +4,8 @@
"actions.autoRename": "智能重命名",
"actions.confirmRemoveAll": "您即将删除所有话题,此操作无法撤销。",
"actions.confirmRemoveTopic": "您即将删除此话题,此操作无法撤销。",
+ "actions.confirmRemoveTopicFiles": "同时删除此话题中上传的图片和文件",
+ "actions.confirmRemoveTopicTitle": "删除此话题?",
"actions.confirmRemoveUnstarred": "您即将删除未加星标的话题,此操作无法撤销。",
"actions.copyLink": "复制链接",
"actions.copyLinkSuccess": "链接已复制",
@@ -20,6 +22,7 @@
"actions.openInNewTab": "在新标签页中打开",
"actions.openInNewWindow": "打开独立窗口",
"actions.removeAll": "删除全部话题",
+ "actions.removeTopic": "删除话题",
"actions.removeUnstarred": "删除未收藏话题",
"actions.unfavorite": "取消收藏",
"actions.unmarkCompleted": "取消归档",
diff --git a/packages/database/src/models/__tests__/file.test.ts b/packages/database/src/models/__tests__/file.test.ts
index 38122c56a78..b57e6cfba6a 100644
--- a/packages/database/src/models/__tests__/file.test.ts
+++ b/packages/database/src/models/__tests__/file.test.ts
@@ -1692,6 +1692,117 @@ describe('FileModel', () => {
});
});
+ describe('findDeletableFilesByTopicId', () => {
+ const sessionId = 'topic-files-session-1';
+ const topicId = 'topic-files-topic-1';
+
+ beforeEach(async () => {
+ await serverDB.insert(sessions).values({ id: sessionId, userId });
+ await serverDB.insert(topics).values([
+ { id: topicId, sessionId, userId },
+ { id: 'topic-files-topic-2', sessionId, userId },
+ ]);
+ await serverDB.insert(messages).values([
+ { id: 'tf-msg-1', role: 'user', topicId, userId },
+ { id: 'tf-msg-1b', role: 'user', topicId, userId },
+ { id: 'tf-msg-2', role: 'user', topicId: 'topic-files-topic-2', userId },
+ ]);
+ await serverDB.insert(files).values([
+ { fileType: 'text/csv', id: 'tf-msg', name: 'msg.csv', size: 1, url: 'k-msg', userId },
+ {
+ fileType: 'application/pdf',
+ id: 'tf-shared',
+ name: 'shared.pdf',
+ size: 2,
+ url: 'k-shared',
+ userId,
+ },
+ { fileType: 'text/plain', id: 'tf-sess', name: 's.txt', size: 3, url: 'k-sess', userId },
+ { fileType: 'text/plain', id: 'tf-other', name: 'o.txt', size: 4, url: 'k-other', userId },
+ ]);
+ });
+
+ it('returns only files attached exclusively inside the topic, de-duped', async () => {
+ await serverDB.insert(messagesFiles).values([
+ { fileId: 'tf-msg', messageId: 'tf-msg-1', userId },
+ // same file attached to another message in the topic → must be de-duped
+ { fileId: 'tf-msg', messageId: 'tf-msg-1b', userId },
+ // attached only to a different topic → not a candidate
+ { fileId: 'tf-other', messageId: 'tf-msg-2', userId },
+ ]);
+
+ const result = await fileModel.findDeletableFilesByTopicId(topicId);
+
+ expect(result).toEqual(['tf-msg']);
+ });
+
+ it('preserves a file still attached to a message in another topic', async () => {
+ await serverDB.insert(messagesFiles).values([
+ { fileId: 'tf-msg', messageId: 'tf-msg-1', userId },
+ // tf-shared lives in both the deleted topic and another topic
+ { fileId: 'tf-shared', messageId: 'tf-msg-1', userId },
+ { fileId: 'tf-shared', messageId: 'tf-msg-2', userId },
+ ]);
+
+ const result = await fileModel.findDeletableFilesByTopicId(topicId);
+
+ expect(result).toEqual(['tf-msg']);
+ });
+
+ it('preserves a file still attached to a message with no topic', async () => {
+ await serverDB.insert(messages).values({ id: 'tf-msg-inbox', role: 'user', userId });
+ await serverDB.insert(messagesFiles).values([
+ { fileId: 'tf-shared', messageId: 'tf-msg-1', userId },
+ // also attached to an inbox message (topicId = null) → must be preserved
+ { fileId: 'tf-shared', messageId: 'tf-msg-inbox', userId },
+ ]);
+
+ const result = await fileModel.findDeletableFilesByTopicId(topicId);
+
+ expect(result).toEqual([]);
+ });
+
+ it('preserves a file still attached at the session level', async () => {
+ await serverDB
+ .insert(messagesFiles)
+ .values({ fileId: 'tf-sess', messageId: 'tf-msg-1', userId });
+ // also bound to the session → survives a single-topic deletion
+ await serverDB.insert(filesToSessions).values({ fileId: 'tf-sess', sessionId, userId });
+
+ const result = await fileModel.findDeletableFilesByTopicId(topicId);
+
+ expect(result).toEqual([]);
+ });
+
+ it('returns an empty array when the topic has no message files', async () => {
+ const result = await fileModel.findDeletableFilesByTopicId(topicId);
+ expect(result).toEqual([]);
+ });
+
+ it('does not return files belonging to another user', async () => {
+ await serverDB.insert(messages).values({
+ id: 'tf-msg-other',
+ role: 'user',
+ topicId,
+ userId: 'user2',
+ });
+ await serverDB.insert(files).values({
+ fileType: 'text/plain',
+ id: 'tf-user2',
+ name: 'u2.txt',
+ size: 5,
+ url: 'k-u2',
+ userId: 'user2',
+ });
+ await serverDB
+ .insert(messagesFiles)
+ .values({ fileId: 'tf-user2', messageId: 'tf-msg-other', userId: 'user2' });
+
+ const result = await fileModel.findDeletableFilesByTopicId(topicId);
+ expect(result).toEqual([]);
+ });
+ });
+
describe('updateGlobalFile', () => {
it('should update url and metadata of a global file by hashId', async () => {
await fileModel.createGlobalFile({
diff --git a/packages/database/src/models/file.ts b/packages/database/src/models/file.ts
index f9c5c86393a..6bbd0906f04 100644
--- a/packages/database/src/models/file.ts
+++ b/packages/database/src/models/file.ts
@@ -1,6 +1,20 @@
import type { QueryFileListParams } from '@lobechat/types';
import { FilesTabs, SortType } from '@lobechat/types';
-import { and, asc, count, desc, eq, ilike, inArray, like, notExists, or, sum } from 'drizzle-orm';
+import {
+ and,
+ asc,
+ count,
+ desc,
+ eq,
+ ilike,
+ inArray,
+ isNull,
+ like,
+ ne,
+ notExists,
+ or,
+ sum,
+} from 'drizzle-orm';
import type { PgTransaction } from 'drizzle-orm/pg-core';
import type { FileItem, NewFile, NewGlobalFile } from '../schemas';
@@ -455,6 +469,63 @@ export class FileModel {
return [...deduped.values()];
};
+ /**
+ * Find the user-uploaded files that can be safely deleted when a topic is
+ * removed: files attached to messages inside the topic that have **no other
+ * reference** surviving the deletion.
+ *
+ * Deleting a `files` row cascades to `messages_files` and `files_to_sessions`,
+ * so a file still referenced elsewhere would silently disappear from there.
+ * A candidate is therefore preserved (excluded) when it is still attached:
+ * - to a message in another topic (or a message with no topic), or
+ * - at the session level (`files_to_sessions`), which outlives a single topic.
+ *
+ * Session-level files are likewise never returned, matching the behaviour
+ * documented on {@link findFilesToInitInSandbox}.
+ */
+ findDeletableFilesByTopicId = async (topicId: string): Promise<string[]> => {
+ const candidates = await this.db
+ .selectDistinct({ id: messagesFiles.fileId })
+ .from(messagesFiles)
+ .innerJoin(messages, eq(messagesFiles.messageId, messages.id))
+ .where(and(eq(messages.topicId, topicId), eq(messagesFiles.userId, this.userId)));
+
+ const candidateIds = candidates.map((row) => row.id);
+ if (candidateIds.length === 0) return [];
+
+ const [messageRefsOutsideTopic, sessionRefs] = await Promise.all([
+ // same file attached to a message in a different topic (or no topic)
+ this.db
+ .selectDistinct({ id: messagesFiles.fileId })
+ .from(messagesFiles)
+ .innerJoin(messages, eq(messagesFiles.messageId, messages.id))
+ .where(
+ and(
+ inArray(messagesFiles.fileId, candidateIds),
+ eq(messagesFiles.userId, this.userId),
+ or(ne(messages.topicId, topicId), isNull(messages.topicId)),
+ ),
+ ),
+ // same file attached at the session level — survives topic deletion
+ this.db
+ .selectDistinct({ id: filesToSessions.fileId })
+ .from(filesToSessions)
+ .where(
+ and(
+ inArray(filesToSessions.fileId, candidateIds),
+ eq(filesToSessions.userId, this.userId),
+ ),
+ ),
+ ]);
+
+ const referencedElsewhere = new Set<string>([
+ ...messageRefsOutsideTopic.map((row) => row.id),
+ ...sessionRefs.map((row) => row.id),
+ ]);
+
+ return candidateIds.filter((id) => !referencedElsewhere.has(id));
+ };
+
countFilesByHash = async (hash: string) => {
const result = await this.db
.select({
diff --git a/packages/locales/src/default/topic.ts b/packages/locales/src/default/topic.ts
index a757d569451..bd3e8885252 100644
--- a/packages/locales/src/default/topic.ts
+++ b/packages/locales/src/default/topic.ts
@@ -4,6 +4,8 @@ export default {
'actions.autoRename': 'Smart Rename',
'actions.confirmRemoveAll': 'You are about to delete all topics. This action cannot be undone.',
'actions.confirmRemoveTopic': 'You are about to delete this topic. This action cannot be undone.',
+ 'actions.confirmRemoveTopicFiles': 'Also delete images and files uploaded in this topic',
+ 'actions.confirmRemoveTopicTitle': 'Delete this topic?',
'actions.confirmRemoveUnstarred':
'You are about to delete unstarred topics. This action cannot be undone.',
'actions.copyLink': 'Copy Link',
@@ -23,6 +25,7 @@ export default {
'actions.openInNewTab': 'Open in New Tab',
'actions.openInNewWindow': 'Open in a new window',
'actions.removeAll': 'Delete All Topics',
+ 'actions.removeTopic': 'Delete Topic',
'actions.removeUnstarred': 'Delete Unstarred Topics',
'defaultTitle': 'Default Topic',
'displayItems': 'Display Items',
diff --git a/src/features/DeleteTopicConfirm/Content.tsx b/src/features/DeleteTopicConfirm/Content.tsx
new file mode 100644
index 00000000000..e291ca53745
--- /dev/null
+++ b/src/features/DeleteTopicConfirm/Content.tsx
@@ -0,0 +1,34 @@
+'use client';
+
+import { Checkbox, Flexbox } from '@lobehub/ui';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+interface DeleteTopicConfirmContentProps {
+ defaultRemoveFiles?: boolean;
+ onChange: (removeFiles: boolean) => void;
+}
+
+const DeleteTopicConfirmContent = memo<DeleteTopicConfirmContentProps>(
+ ({ onChange, defaultRemoveFiles = true }) => {
+ const { t } = useTranslation('topic');
+ const [checked, setChecked] = useState(defaultRemoveFiles);
+
+ return (
+ <Flexbox gap={12}>
+ {t('actions.confirmRemoveTopic')}
+ <Checkbox
+ checked={checked}
+ onChange={(value) => {
+ setChecked(value);
+ onChange(value);
+ }}
+ >
+ {t('actions.confirmRemoveTopicFiles')}
+ </Checkbox>
+ </Flexbox>
+ );
+ },
+);
+
+export default DeleteTopicConfirmContent;
diff --git a/src/features/DeleteTopicConfirm/index.tsx b/src/features/DeleteTopicConfirm/index.tsx
new file mode 100644
index 00000000000..9288c1a10a4
--- /dev/null
+++ b/src/features/DeleteTopicConfirm/index.tsx
@@ -0,0 +1,35 @@
+'use client';
+
+import { confirmModal } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+
+import DeleteTopicConfirmContent from './Content';
+
+/**
+ * Open the "delete topic" confirmation dialog. The dialog includes a checkbox —
+ * checked by default — to also delete images/files uploaded in the topic, so
+ * removing a conversation doesn't leave orphaned attachments in storage.
+ *
+ * @param onConfirm invoked on confirm with the current checkbox value.
+ */
+export const confirmRemoveTopic = (onConfirm: (removeFiles: boolean) => Promise<void> | void) => {
+ // Default to removing attachments to avoid orphaned storage.
+ const state = { removeFiles: true };
+
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: (
+ <DeleteTopicConfirmContent
+ onChange={(removeFiles) => {
+ state.removeFiles = removeFiles;
+ }}
+ />
+ ),
+ okButtonProps: { danger: true },
+ okText: t('actions.removeTopic', { ns: 'topic' }),
+ onOk: async () => {
+ await onConfirm(state.removeFiles);
+ },
+ title: t('actions.confirmRemoveTopicTitle', { ns: 'topic' }),
+ });
+};
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
index f9db5251049..df78713f5f1 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
@@ -2,7 +2,6 @@ import { AGENT_CHAT_TOPIC_URL } from '@lobechat/const';
import type { ChatTopicStatus } from '@lobechat/types';
import { type MenuProps } from '@lobehub/ui';
import { Icon } from '@lobehub/ui';
-import { confirmModal } from '@lobehub/ui/base-ui';
import { App } from 'antd';
import {
Archive,
@@ -26,6 +25,7 @@ import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspa
import { openRenameModal } from '@/components/RenameModal';
import { isDesktop } from '@/const/version';
import { createMoveTopicsModal } from '@/features/AgentTopicManager/MoveTopicsModal';
+import { confirmRemoveTopic } from '@/features/DeleteTopicConfirm';
import { openShareModal } from '@/features/ShareModal';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
@@ -233,15 +233,8 @@ export const useTopicItemDropdownMenu = ({
key: 'delete',
label: t('delete', { ns: 'common' }),
onClick: () => {
- confirmModal({
- cancelText: t('cancel', { ns: 'common' }),
- content: t('actions.confirmRemoveTopic'),
- okButtonProps: { danger: true },
- okText: t('delete', { ns: 'common' }),
- onOk: async () => {
- await removeTopic(id);
- },
- title: t('delete', { ns: 'common' }),
+ confirmRemoveTopic(async (removeFiles) => {
+ await removeTopic(id, removeFiles);
});
},
},
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
index 68c8501930c..de035ac845b 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
@@ -2,7 +2,6 @@ import { GROUP_CHAT_TOPIC_URL } from '@lobechat/const';
import type { ChatTopicStatus } from '@lobechat/types';
import { type MenuProps } from '@lobehub/ui';
import { Icon } from '@lobehub/ui';
-import { confirmModal } from '@lobehub/ui/base-ui';
import { App } from 'antd';
import {
Archive,
@@ -21,6 +20,7 @@ import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { isDesktop } from '@/const/version';
+import { confirmRemoveTopic } from '@/features/DeleteTopicConfirm';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import { useAppOrigin } from '@/hooks/useAppOrigin';
@@ -178,15 +178,8 @@ export const useTopicItemDropdownMenu = ({
key: 'delete',
label: t('delete', { ns: 'common' }),
onClick: () => {
- confirmModal({
- cancelText: t('cancel', { ns: 'common' }),
- content: t('actions.confirmRemoveTopic'),
- okButtonProps: { danger: true },
- okText: t('delete', { ns: 'common' }),
- onOk: async () => {
- await removeTopic(id);
- },
- title: t('delete', { ns: 'common' }),
+ confirmRemoveTopic(async (removeFiles) => {
+ await removeTopic(id, removeFiles);
});
},
},
diff --git a/src/services/topic/index.ts b/src/services/topic/index.ts
index def53c10905..0bbd3d11048 100644
--- a/src/services/topic/index.ts
+++ b/src/services/topic/index.ts
@@ -118,8 +118,8 @@ export class TopicService {
return lambdaClient.topic.disableSharing.mutate({ topicId });
};
- removeTopic = (id: string) => {
- return lambdaClient.topic.removeTopic.mutate({ id });
+ removeTopic = (id: string, removeFiles?: boolean) => {
+ return lambdaClient.topic.removeTopic.mutate({ id, removeFiles });
};
removeTopics = (sessionId: string) => {
diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.ts
index 3911470a1d3..e26729192f2 100644
--- a/src/store/chat/slices/topic/action.test.ts
+++ b/src/store/chat/slices/topic/action.test.ts
@@ -1212,10 +1212,28 @@ describe('topic action', () => {
await result.current.removeTopic(topicId);
});
- expect(topicService.removeTopic).toHaveBeenCalledWith(topicId);
+ expect(topicService.removeTopic).toHaveBeenCalledWith(topicId, undefined);
expect(refreshTopicSpy).toHaveBeenCalled();
expect(switchTopicSpy).toHaveBeenCalled();
});
+ it('should forward removeFiles so the topic attachments are deleted', async () => {
+ const topicId = 'topic-1';
+ const { result } = renderHook(() => useChatStore());
+ const activeAgentId = 'test-session-id';
+
+ await act(async () => {
+ useChatStore.setState({ activeAgentId, activeTopicId: topicId });
+ });
+
+ vi.spyOn(result.current, 'refreshTopic').mockResolvedValue(undefined);
+
+ await act(async () => {
+ await result.current.removeTopic(topicId, true);
+ });
+
+ expect(topicService.removeTopic).toHaveBeenCalledWith(topicId, true);
+ });
+
it('should remove a specific topic and its messages, then not switch topic if not active', async () => {
const topicId = 'topic-1';
const { result } = renderHook(() => useChatStore());
@@ -1232,7 +1250,7 @@ describe('topic action', () => {
await result.current.removeTopic(topicId);
});
- expect(topicService.removeTopic).toHaveBeenCalledWith(topicId);
+ expect(topicService.removeTopic).toHaveBeenCalledWith(topicId, undefined);
expect(refreshTopicSpy).toHaveBeenCalled();
expect(switchTopicSpy).not.toHaveBeenCalled();
});
@@ -1253,7 +1271,7 @@ describe('topic action', () => {
await result.current.removeTopic(topicId);
});
- expect(topicService.removeTopic).toHaveBeenCalledWith(topicId);
+ expect(topicService.removeTopic).toHaveBeenCalledWith(topicId, undefined);
expect(refreshTopicSpy).toHaveBeenCalled();
expect(switchTopicSpy).toHaveBeenCalled();
});
@@ -1310,7 +1328,7 @@ describe('topic action', () => {
const topicData =
useChatStore.getState().topicDataMap[topicMapKey({ agentId: activeAgentId })];
- expect(topicService.removeTopic).toHaveBeenCalledWith(topicId);
+ expect(topicService.removeTopic).toHaveBeenCalledWith(topicId, undefined);
expect(topicData).toMatchObject({
currentPage: 1,
hasMore: true,
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index 9379c4ca13c..88311d9012c 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -1199,13 +1199,13 @@ export class ChatTopicActionImpl {
void evictMessageCache(() => true);
};
- removeTopic = async (id: string): Promise<void> => {
+ removeTopic = async (id: string, removeFiles?: boolean): Promise<void> => {
const { activeAgentId, activeGroupId, activeTopicId, switchTopic, refreshTopic } = this.#get();
// Allow deletion when either agentId or groupId is active
if (!activeAgentId && !activeGroupId) return;
- // remove topic
- await topicService.removeTopic(id);
+ // remove topic (and optionally its uploaded attachments)
+ await topicService.removeTopic(id, removeFiles);
this.#get().internal_dispatchTopic({ type: 'deleteTopic', id }, 'removeTopic');
await refreshTopic();
// drop the deleted topic's message cache so it doesn't orphan in IndexedDB