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(trash): recycle bin for topics (#18893)

Arvin Xucaef8e6cb576
diff --git a/apps/server/src/router-hono/workflows/index.ts b/apps/server/src/router-hono/workflows/index.ts
index f5912eaf3d9..9490aaa7a57 100644
--- a/apps/server/src/router-hono/workflows/index.ts
+++ b/apps/server/src/router-hono/workflows/index.ts
@@ -10,6 +10,7 @@ import onboardingTaskRecommendationApp from './onboarding-task-recommendation';
import onboardingUnderstandingApp from './onboarding-understanding';
import taskApp from './task';
import topicAutoSummaryApp from './topic-auto-summary';
+import trashApp from './trash';
import verifyApp from './verify';
const app = new Hono().basePath('/api/workflows');
@@ -24,6 +25,7 @@ app.route('/onboarding/understanding', onboardingUnderstandingApp);
app.route('/onboarding/task-recommendations', onboardingTaskRecommendationApp);
app.route('/task', taskApp);
app.route('/topic-auto-summary', topicAutoSummaryApp);
+app.route('/trash', trashApp);
app.route('/verify', verifyApp);
export default app;
diff --git a/apps/server/src/router-hono/workflows/trash/handlers/purge.ts b/apps/server/src/router-hono/workflows/trash/handlers/purge.ts
new file mode 100644
index 00000000000..b2d43013f55
--- /dev/null
+++ b/apps/server/src/router-hono/workflows/trash/handlers/purge.ts
@@ -0,0 +1,37 @@
+import debug from 'debug';
+import type { Context } from 'hono';
+
+import { getServerDB } from '@/database/server';
+import { TrashService } from '@/server/services/trash';
+
+const log = debug('lobe-server:workflows:trash:purge');
+
+/**
+ * Cron-style purge of recycle-bin roots past their retention window — see
+ * {@link TrashService.sweepExpired}. Also prunes registry rows whose resource
+ * is already gone.
+ *
+ * No per-user authentication: this is a global scan registered as a QStash
+ * Schedule (e.g. `0 * * * *`) pointing at `/api/workflows/trash/purge`.
+ * Signature verification is handled by the `qstashAuth` middleware mounted on
+ * the route. Accepts an optional JSON body `{ limit?: number }` to tune the
+ * per-tick batch.
+ */
+export async function purge(c: Context) {
+ try {
+ const body = await c.req.json<{ limit?: number }>().catch(() => ({}) as { limit?: number });
+ const db = await getServerDB();
+ const outcome = await TrashService.sweepExpired(db, { limit: body?.limit });
+
+ log(
+ 'Trash purge: purged=%d failed=%d pruned=%d',
+ outcome.purged,
+ outcome.failed,
+ outcome.pruned,
+ );
+ return c.json({ ...outcome, success: true });
+ } catch (error) {
+ console.error('[trash/purge] Error:', error);
+ return c.json({ error: error instanceof Error ? error.message : 'Internal error' }, 500);
+ }
+}
diff --git a/apps/server/src/router-hono/workflows/trash/index.ts b/apps/server/src/router-hono/workflows/trash/index.ts
new file mode 100644
index 00000000000..f63d5b2f76b
--- /dev/null
+++ b/apps/server/src/router-hono/workflows/trash/index.ts
@@ -0,0 +1,10 @@
+import { Hono } from 'hono';
+
+import { qstashAuth } from '../middlewares/qstashAuth';
+import { purge } from './handlers/purge';
+
+const app = new Hono();
+
+app.post('/purge', qstashAuth(), purge);
+
+export default app;
diff --git a/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.ts
index e9865aab509..63c7579cda1 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.ts
@@ -1,8 +1,8 @@
// @vitest-environment node
import { type LobeChatDatabase } from '@lobechat/database';
-import { messages, sessions, topics } from '@lobechat/database/schemas';
+import { messages, sessions, topics, trashItems } from '@lobechat/database/schemas';
import { getTestDB } from '@lobechat/database/test-utils';
-import { eq } from 'drizzle-orm';
+import { and, eq, isNull } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { topicRouter } from '../../topic';
@@ -396,12 +396,20 @@ describe('Topic Router Integration Tests', () => {
agentId: testAgentId,
});
- const remainingTopics = await serverDB
+ // Recycle bin: rows are stamped (hidden from reads), not dropped, and
+ // each one is registered as its own restorable root.
+ const liveTopics = await serverDB
+ .select()
+ .from(topics)
+ .where(and(eq(topics.sessionId, testSessionId), isNull(topics.deletedAt)));
+ expect(liveTopics).toHaveLength(0);
+ const stamped = await serverDB
.select()
.from(topics)
.where(eq(topics.sessionId, testSessionId));
-
- expect(remainingTopics).toHaveLength(0);
+ expect(stamped).toHaveLength(2);
+ expect(await serverDB.select().from(trashItems)).toHaveLength(2);
+ expect((await caller.getTopics({ agentId: testAgentId })).items).toHaveLength(0);
});
it('should batch delete topics using sessionId', async () => {
@@ -421,7 +429,7 @@ describe('Topic Router Integration Tests', () => {
const remainingTopics = await serverDB
.select()
.from(topics)
- .where(eq(topics.sessionId, testSessionId));
+ .where(and(eq(topics.sessionId, testSessionId), isNull(topics.deletedAt)));
expect(remainingTopics).toHaveLength(0);
});
@@ -442,7 +450,10 @@ describe('Topic Router Integration Tests', () => {
agentId: testAgentId,
});
- const remainingTopics = await serverDB.select().from(topics).where(eq(topics.userId, userId));
+ const remainingTopics = await serverDB
+ .select()
+ .from(topics)
+ .where(and(eq(topics.userId, userId), isNull(topics.deletedAt)));
expect(remainingTopics).toHaveLength(0);
});
@@ -831,7 +842,7 @@ describe('Topic Router Integration Tests', () => {
const remainingTopics = await serverDB
.select()
.from(topics)
- .where(eq(topics.sessionId, testSessionId));
+ .where(and(eq(topics.sessionId, testSessionId), isNull(topics.deletedAt)));
expect(remainingTopics).toHaveLength(1);
expect(remainingTopics[0].title).toBe('Topic 3');
@@ -847,9 +858,15 @@ describe('Topic Router Integration Tests', () => {
await caller.removeTopic({ id: topicId });
- const deletedTopic = await serverDB.select().from(topics).where(eq(topics.id, topicId));
-
- expect(deletedTopic).toHaveLength(0);
+ // Moved to the recycle bin: still on disk with a stamp, invisible to reads.
+ const [trashed] = await serverDB.select().from(topics).where(eq(topics.id, topicId));
+ expect(trashed.deletedAt).toBeTruthy();
+ expect(await caller.getTopics({ agentId: testAgentId })).toMatchObject({ items: [] });
+ const [registry] = await serverDB
+ .select()
+ .from(trashItems)
+ .where(eq(trashItems.resourceId, topicId));
+ expect(registry).toMatchObject({ resourceType: 'topic', rootId: null, userId });
});
it('should count topics', async () => {
diff --git a/apps/server/src/routers/lambda/__tests__/shareVisitorEntryGuard.router.test.ts b/apps/server/src/routers/lambda/__tests__/shareVisitorEntryGuard.router.test.ts
index 9963e06cac8..3179649d255 100644
--- a/apps/server/src/routers/lambda/__tests__/shareVisitorEntryGuard.router.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/shareVisitorEntryGuard.router.test.ts
@@ -89,6 +89,15 @@ vi.mock('@/database/models/file', () => ({
}),
}));
+// removeTopic moves the topic to the recycle bin; attachments flagged with
+// `removeFiles` are only dropped when that bin row is purged.
+const mockTrashTopics = vi.fn();
+vi.mock('@/server/services/trash', () => ({
+ TrashService: vi.fn(function () {
+ return { trashTopics: mockTrashTopics };
+ }),
+}));
+
const mockDeleteFiles = vi.fn();
vi.mock('@/server/services/file', () => ({
FileService: vi.fn(function () {
@@ -135,23 +144,25 @@ describe('agent-share visitor guards on creator-facing RPCs', () => {
});
describe('topic.removeTopic', () => {
- it('does not delete attachments when the id is a visitor topic', async () => {
- // The visitor topic is invisible to `findOwnTopicById`, and
- // `TopicModel.delete` refuses to remove it — so its files must survive.
+ it('neither trashes nor touches attachments when the id is a visitor topic', async () => {
+ // The visitor topic is invisible to `findOwnTopicById`, so it must not
+ // reach the recycle bin and its files must survive.
mockTopicFindOwnTopicById.mockResolvedValue(undefined);
await topicCaller().removeTopic({ id: visitorTopicId, removeFiles: true });
+ expect(mockTrashTopics).not.toHaveBeenCalled();
expect(mockFindDeletableFilesByTopicId).not.toHaveBeenCalled();
expect(mockFileDeleteMany).not.toHaveBeenCalled();
expect(mockDeleteFiles).not.toHaveBeenCalled();
});
- it('still deletes attachments of the creator’s own topic', async () => {
+ it('moves the creator’s own topic to the bin with its attachment removal deferred to purge', async () => {
await topicCaller().removeTopic({ id: 'topic-1', removeFiles: true });
- expect(mockFindDeletableFilesByTopicId).toHaveBeenCalledWith('topic-1');
- expect(mockDeleteFiles).toHaveBeenCalledWith(['s3://file-1']);
+ expect(mockTrashTopics).toHaveBeenCalledWith(['topic-1'], { removeFiles: true });
+ // nothing is dropped from storage until the bin row is purged
+ expect(mockDeleteFiles).not.toHaveBeenCalled();
});
});
diff --git a/apps/server/src/routers/lambda/__tests__/trash.test.ts b/apps/server/src/routers/lambda/__tests__/trash.test.ts
new file mode 100644
index 00000000000..def56ebb906
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/trash.test.ts
@@ -0,0 +1,58 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+// serverDatabase middleware calls getServerDB(); the service is mocked, so the
+// handle it returns is never dereferenced.
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return {};
+ }),
+}));
+
+const mockList = vi.fn(async () => ({ items: [], nextCursor: null }));
+const mockCountByType = vi.fn(async () => ({}));
+const mockEmptyTrash = vi.fn(async () => ({ purged: 0 }));
+vi.mock('@/server/services/trash', () => ({
+ TrashService: vi.fn(function () {
+ return { countByType: mockCountByType, emptyTrash: mockEmptyTrash, list: mockList };
+ }),
+}));
+
+const { trashRouter } = await import('../trash');
+
+const owner: any = { serverDB: {}, userId: 'owner-1', workspaceId: 'ws-1', workspaceRole: 'owner' };
+const member: any = { ...owner, userId: 'member-1', workspaceRole: 'member' };
+const personal: any = { serverDB: {}, userId: 'user-1' };
+
+describe('trashRouter visibility', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('limits a workspace non-owner to the roots they trashed themselves', async () => {
+ const caller = trashRouter.createCaller(member);
+
+ await caller.list({ resourceType: 'message' });
+ await caller.countByType();
+
+ expect(mockList).toHaveBeenCalledWith(
+ expect.objectContaining({ deletedByUserId: 'member-1', resourceType: 'message' }),
+ );
+ expect(mockCountByType).toHaveBeenCalledWith({ deletedByUserId: 'member-1' });
+ });
+
+ it('shows the owner and a personal user the whole bin in scope', async () => {
+ for (const ctx of [owner, personal]) {
+ const caller = trashRouter.createCaller(ctx);
+ await caller.list();
+ await caller.countByType();
+ }
+
+ for (const [params] of mockList.mock.calls as any[]) {
+ expect(params.deletedByUserId).toBeUndefined();
+ }
+ for (const [options] of mockCountByType.mock.calls as any[]) {
+ expect(options.deletedByUserId).toBeUndefined();
+ }
+ });
+});
diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.ts
index d108850025e..7b7171f4104 100644
--- a/apps/server/src/routers/lambda/index.ts
+++ b/apps/server/src/routers/lambda/index.ts
@@ -94,6 +94,7 @@ import { taskRouter } from './task';
import { threadRouter } from './thread';
import { topicRouter } from './topic';
import { topicCommentRouter } from './topicComment';
+import { trashRouter } from './trash';
import { uploadRouter } from './upload';
import { usageRouter } from './usage';
import { userRouter } from './user';
@@ -181,6 +182,7 @@ export const lambdaRouter = router({
task: taskRouter,
thread: threadRouter,
topic: topicRouter,
+ trash: trashRouter,
topicComment: topicCommentRouter,
upload: uploadRouter,
usage: usageRouter,
diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.ts
index 76cad7c5b89..0acad5fc22a 100644
--- a/apps/server/src/routers/lambda/topic.ts
+++ b/apps/server/src/routers/lambda/topic.ts
@@ -17,7 +17,6 @@ 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';
@@ -35,9 +34,9 @@ import type { LobeChatDatabase } from '@/database/type';
import { notTrashed } from '@/database/utils/softDelete';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-import { FileService } from '@/server/services/file';
import { createFtsSearchRepo } from '@/server/services/ftsSearch';
import { TopicReferenceService } from '@/server/services/topicReference';
+import { TrashService } from '@/server/services/trash';
import { after } from '@/server/utils/scheduleAfterResponse';
import { type BatchTaskResult } from '@/types/service';
@@ -85,6 +84,7 @@ const topicProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>
topicImporterRepo: new TopicImporterRepo(ctx.serverDB, ctx.userId, wsId),
topicModel: new TopicModel(ctx.serverDB, ctx.userId, wsId),
topicShareModel: new TopicShareModel(ctx.serverDB, ctx.userId, wsId),
+ trashService: new TrashService(ctx.serverDB, ctx.userId, wsId),
},
});
});
@@ -372,7 +372,7 @@ export const topicRouter = router({
assertWorkspaceRowManageable(ctx, userId, 'topic');
}
- return ctx.topicModel.batchDelete(input.ids);
+ await ctx.trashService.trashTopics(input.ids);
}),
batchDeleteByAgentId: topicProcedure
@@ -381,7 +381,7 @@ export const topicRouter = router({
.mutation(async ({ input, ctx }) => {
const restrictToCreator = shouldRestrictBulkDeleteToCreator(ctx, input.scope);
- return ctx.topicModel.batchDeleteByAgentId(input.agentId, { restrictToCreator });
+ await ctx.trashService.trashTopicsByAgent(input.agentId, { restrictToCreator });
}),
batchDeleteByGroupId: topicProcedure
@@ -391,7 +391,7 @@ export const topicRouter = router({
await assertCanUseConversationTargets(guardCtx(ctx), [{ groupId: input.groupId }]);
const restrictToCreator = shouldRestrictBulkDeleteToCreator(ctx, input.scope);
- return ctx.topicModel.batchDeleteByGroupId(input.groupId, { restrictToCreator });
+ await ctx.trashService.trashTopicsByGroup(input.groupId, { restrictToCreator });
}),
batchDeleteBySessionId: topicProcedure
@@ -419,7 +419,7 @@ export const topicRouter = router({
const restrictToCreator = shouldRestrictBulkDeleteToCreator(ctx, input.scope);
- return ctx.topicModel.batchDeleteBySessionId(resolved.sessionId, { restrictToCreator });
+ await ctx.trashService.trashTopicsBySession(resolved.sessionId, { restrictToCreator });
}),
batchMoveTopics: topicProcedure
@@ -912,9 +912,14 @@ export const topicRouter = router({
removeAllTopics: topicProcedure
.use(withScopedPermission('topic:delete'))
.mutation(async ({ ctx }) => {
- return ctx.topicModel.deleteAll();
+ await ctx.trashService.trashAllTopics();
}),
+ /**
+ * Move a topic to the recycle bin. With `removeFiles`, the attachments only
+ * this topic references go along as children and are dropped from storage
+ * when the topic is purged (restore brings them back too).
+ */
removeTopic: topicProcedure
.use(withScopedPermission('topic:delete'))
.input(z.object({ id: z.string(), removeFiles: z.boolean().optional() }))
@@ -927,32 +932,10 @@ export const topicRouter = router({
const topic = await ctx.topicModel.findOwnTopicById(input.id);
if (topic) assertWorkspaceRowManageable(ctx, topic.userId, 'topic');
- // No creator-visible topic behind this id: run the (no-op) delete for the
- // unchanged return shape, but never touch any files.
- if (!input.removeFiles || !topic) return ctx.topicModel.delete(input.id);
-
- // 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 ctx.fileModel.findDeletableFilesByTopicId(input.id);
+ // No creator-visible topic behind this id: nothing to trash.
+ if (!topic) return;
- const result = await ctx.topicModel.delete(input.id);
-
- if (fileIds.length > 0) {
- const needToRemove = await ctx.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 wsId = ctx.workspaceId ?? undefined;
- const fileService = new FileService(ctx.serverDB, ctx.userId, wsId);
- await fileService.deleteFiles(needToRemove.map((file) => file.url!));
- }
- }
-
- return result;
+ await ctx.trashService.trashTopics([input.id], { removeFiles: input.removeFiles });
}),
searchTopics: topicSearchProcedure
diff --git a/apps/server/src/routers/lambda/trash.ts b/apps/server/src/routers/lambda/trash.ts
new file mode 100644
index 00000000000..90cda8b96cb
--- /dev/null
+++ b/apps/server/src/routers/lambda/trash.ts
@@ -0,0 +1,104 @@
+import { TRASH_RESOURCE_TYPES } from '@lobechat/types';
+import { z } from 'zod';
+
+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { TrashService } from '@/server/services/trash';
+
+import {
+ assertWorkspaceRowManageable,
+ isWorkspaceNonOwner,
+} from './_helpers/assertWorkspaceRowManageable';
+
+const trashProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+ const wsId = ctx.workspaceId ?? undefined;
+ return opts.next({
+ ctx: { trashService: new TrashService(ctx.serverDB, ctx.userId, wsId) },
+ });
+});
+
+const resourceTypeSchema = z.enum(TRASH_RESOURCE_TYPES);
+
+/**
+ * Recycle bin. Personal mode lists the caller's own rows; in a workspace the
+ * owner sees every root while a non-owner member sees only the roots they
+ * trashed themselves — a root's title can be a content excerpt of a resource
+ * that member cannot view. Restore / purge apply the
+ * same row-level rule as delete did: the member who trashed a row (or any
+ * workspace owner) may bring it back or drop it for good.
+ */
+export const trashRouter = router({
+ countByType: trashProcedure.query(async ({ ctx }) =>
+ ctx.trashService.countByType({ deletedByUserId: actorFilter(ctx) }),
+ ),
+
+ emptyTrash: trashProcedure
+ .input(z.object({ resourceType: resourceTypeSchema.optional() }).optional())
+ .mutation(async ({ input, ctx }) => {
+ // The actor filter is pushed into the query rather than applied to a
+ // page of results, so a member with more items than one page still
+ // empties all of them.
+ return ctx.trashService.emptyTrash({
+ deletedByUserId: actorFilter(ctx),
+ resourceType: input?.resourceType,
+ });
+ }),
+
+ list: trashProcedure
+ .input(
+ z
+ .object({
+ cursor: z.string().nullish(),
+ limit: z.number().int().min(1).max(200).optional(),
+ resourceType: resourceTypeSchema.optional(),
+ })
+ .optional(),
+ )
+ .query(async ({ input, ctx }) =>
+ ctx.trashService.list({
+ cursor: input?.cursor,
+ deletedByUserId: actorFilter(ctx),
+ limit: input?.limit,
+ resourceType: input?.resourceType,
+ }),
+ ),
+
+ purge: trashProcedure
+ .input(z.object({ ids: z.array(z.string()).min(1).max(200) }))
+ .mutation(async ({ input, ctx }) => {
+ await assertItemsManageable(ctx, input.ids);
+ return ctx.trashService.purge(input.ids);
+ }),
+
+ restore: trashProcedure
+ .input(z.object({ ids: z.array(z.string()).min(1).max(200) }))
+ .mutation(async ({ input, ctx }) => {
+ await assertItemsManageable(ctx, input.ids);
+ return ctx.trashService.restore(input.ids);
+ }),
+});
+
+/** Workspace non-owners only see and sweep the roots they trashed themselves; owners get the whole bin. */
+const actorFilter = (ctx: Parameters<typeof isWorkspaceNonOwner>[0] & { userId: string }) =>
+ isWorkspaceNonOwner(ctx) ? ctx.userId : undefined;
+
+/** Every requested registry row must be manageable by the caller (creator or workspace owner). */
+const assertItemsManageable = async (
+ ctx: {
+ trashService: TrashService;
+ userId: string;
+ workspaceId?: string | null;
+ workspaceRole?: string;
+ },
+ ids: string[],
+) => {
+ if (!ctx.workspaceId) return;
+ const items = await ctx.trashService.findByIds(ids);
+ for (const item of items) {
+ assertWorkspaceRowManageable(ctx, item.deletedByUserId ?? item.userId, 'trash item');
+ }
+};
+
+export type TrashRouter = typeof trashRouter;
diff --git a/apps/server/src/services/trash/__tests__/index.test.ts b/apps/server/src/services/trash/__tests__/index.test.ts
new file mode 100644
index 00000000000..fee1d6015d9
--- /dev/null
+++ b/apps/server/src/services/trash/__tests__/index.test.ts
@@ -0,0 +1,196 @@
+// @vitest-environment node
+import { TRASH_EMPTY_BATCH_SIZE } from '@lobechat/const';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentModel } from '@/database/models/agent';
+import { MessageModel } from '@/database/models/message';
+import { TopicModel } from '@/database/models/topic';
+import { TrashModel } from '@/database/models/trash';
+import { messages, topics, trashItems, users, workspaces } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { TrashService } from '../index';
+
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(() => ({ deleteFile: vi.fn(), deleteFiles: vi.fn() })),
+}));
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'trash-service-user';
+const otherUserId = 'trash-service-other';
+
+let service: TrashService;
+let topicModel: TopicModel;
+let agentModel: AgentModel;
+let messageModel: MessageModel;
+let trashModel: TrashModel;
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ service = new TrashService(serverDB, userId);
+ topicModel = new TopicModel(serverDB, userId);
+ agentModel = new AgentModel(serverDB, userId);
+ messageModel = new MessageModel(serverDB, userId);
+ trashModel = new TrashModel(serverDB, userId);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+describe('TrashService', () => {
+ describe('topics', () => {
+ it('hides a trashed topic from reads, lists it in the bin, restores it with its messages intact', async () => {
+ const agent = await agentModel.create({ title: 'Bot' });
+ const topic = await topicModel.create({ agentId: agent.id, title: 'Plan the trip' });
+ await messageModel.create({
+ agentId: agent.id,
+ content: 'hi',
+ role: 'user',
+ topicId: topic.id,
+ });
+
+ const [root] = await service.trashTopics([topic.id]);
+ expect(root.resourceType).toBe('topic');
+ expect(root.title).toBe('Plan the trip');
+
+ // invisible to every ordinary read …
+ expect(await topicModel.findById(topic.id)).toBeUndefined();
+ expect((await topicModel.query({ agentId: agent.id })).items).toHaveLength(0);
+ // … but the rows are still there
+ expect(
+ await serverDB.select().from(messages).where(eq(messages.topicId, topic.id)),
+ ).toHaveLength(1);
+
+ const { items } = await service.list();
+ expect(items.map((i) => i.resourceId)).toEqual([topic.id]);
+ expect(await service.countByType()).toEqual({ topic: 1 });
+
+ const outcome = await service.restore([root.id]);
+ expect(outcome.restored.map((i) => i.resourceId)).toEqual([topic.id]);
+ expect(outcome.failed).toEqual([]);
+ expect(await topicModel.findById(topic.id)).toMatchObject({ deletedAt: null, id: topic.id });
+ expect(await serverDB.select().from(trashItems)).toHaveLength(0);
+ });
+
+ it('bulk sweeps become one restorable root per topic', async () => {
+ const agent = await agentModel.create({ title: 'Bot' });
+ await topicModel.create({ agentId: agent.id, title: 'a' });
+ await topicModel.create({ agentId: agent.id, title: 'b' });
+ const roots = await service.trashTopicsByAgent(agent.id);
+ expect(roots).toHaveLength(2);
+ expect((await topicModel.query({ agentId: agent.id })).items).toHaveLength(0);
+ expect((await service.list()).items).toHaveLength(2);
+ });
+ });
+
+ describe('sweep', () => {
+ it('purges only expired roots, across users, and prunes stale registry rows', async () => {
+ const otherService = new TrashService(serverDB, otherUserId);
+ const otherTopicModel = new TopicModel(serverDB, otherUserId);
+
+ const mine = await topicModel.create({ title: 'mine' });
+ const theirs = await otherTopicModel.create({ title: 'theirs' });
+ const fresh = await topicModel.create({ title: 'fresh' });
+ const [mineRoot] = await service.trashTopics([mine.id]);
+ const [theirsRoot] = await otherService.trashTopics([theirs.id]);
+ await service.trashTopics([fresh.id]);
+ // backdate two of them past the retention window
+ const past = new Date(Date.now() - 1000);
+ await serverDB
+ .update(trashItems)
+ .set({ expiresAt: past })
+ .where(eq(trashItems.id, mineRoot.id));
+ await serverDB
+ .update(trashItems)
+ .set({ expiresAt: past })
+ .where(eq(trashItems.id, theirsRoot.id));
+ // and one orphan registry row whose topic vanished through another path
+ await trashModel.register({
+ deletedAt: new Date(),
+ root: { resourceId: 'tpc_ghost', resourceType: 'topic' },
+ });
+
+ const outcome = await TrashService.sweepExpired(serverDB);
+ expect(outcome).toEqual({ failed: 0, pruned: 1, purged: 2 });
+ expect(await serverDB.select().from(topics).where(eq(topics.id, mine.id))).toHaveLength(0);
+ expect(await serverDB.select().from(topics).where(eq(topics.id, theirs.id))).toHaveLength(0);
+ expect(await serverDB.select().from(topics).where(eq(topics.id, fresh.id))).toHaveLength(1);
+ expect((await service.list()).items.map((i) => i.resourceId)).toEqual([fresh.id]);
+ });
+
+ it('emptyTrash purges everything in scope', async () => {
+ const a = await topicModel.create({ title: 'a' });
+ const b = await topicModel.create({ title: 'b' });
+ await service.trashTopics([a.id, b.id]);
+ const { purged } = await service.emptyTrash();
+ expect(purged).toBe(2);
+ expect((await service.list()).items).toHaveLength(0);
+ expect(await serverDB.select().from(topics)).toHaveLength(0);
+ });
+
+ it('emptyTrash purges one bounded batch per call and says when more remain', async () => {
+ const created = await Promise.all(
+ Array.from({ length: TRASH_EMPTY_BATCH_SIZE + 3 }, (_, i) =>
+ topicModel.create({ title: `t${i}` }),
+ ),
+ );
+ await service.trashTopics(created.map((t) => t.id));
+
+ const first = await service.emptyTrash();
+ expect(first).toEqual({ hasMore: true, purged: TRASH_EMPTY_BATCH_SIZE });
+ expect((await service.countByType()).topic).toBe(3);
+
+ const second = await service.emptyTrash();
+ expect(second).toEqual({ hasMore: false, purged: 3 });
+ expect(await serverDB.select().from(topics)).toHaveLength(0);
+ });
+
+ it('a purge that lands after a concurrent restore leaves the restored topic alone', async () => {
+ const topic = await topicModel.create({ title: 'raced' });
+ const [root] = await service.trashTopics([topic.id]);
+ // The restore commits between the purge's registry read and its delete:
+ // the registry row is still there, but the topic is live again.
+ await topicModel.restore([topic.id]);
+
+ await service.purge([root.id]);
+ expect(await topicModel.findById(topic.id)).toBeTruthy();
+ });
+
+ it('emptyTrash scoped to an actor clears every one of their roots, not just a first page', async () => {
+ // A workspace non-owner may only empty what they trashed themselves. The
+ // filter has to live in the query: applying it to one page of results
+ // would silently leave the rest behind while the UI says "emptied".
+ const workspaceId = 'trash-empty-ws';
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'ws',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ });
+ const mine = new TrashService(serverDB, userId, workspaceId);
+ const theirs = new TrashService(serverDB, otherUserId, workspaceId);
+ const myTopics = new TopicModel(serverDB, userId, workspaceId);
+ const theirTopics = new TopicModel(serverDB, otherUserId, workspaceId);
+
+ for (let i = 0; i < 3; i++) {
+ const t = await myTopics.create({ title: `mine ${i}` });
+ await mine.trashTopics([t.id]);
+ }
+ const theirTopic = await theirTopics.create({ title: 'theirs' });
+ await theirs.trashTopics([theirTopic.id]);
+
+ const { hasMore, purged } = await mine.emptyTrash({ deletedByUserId: userId });
+
+ expect(purged).toBe(3);
+ expect(hasMore).toBe(false);
+ // the teammate's row is untouched and still listed workspace-wide
+ const left = await mine.list();
+ expect(left.items.map((item) => item.resourceId)).toEqual([theirTopic.id]);
+ });
+ });
+});
diff --git a/apps/server/src/services/trash/handlers/index.ts b/apps/server/src/services/trash/handlers/index.ts
new file mode 100644
index 00000000000..7fae218d324
--- /dev/null
+++ b/apps/server/src/services/trash/handlers/index.ts
@@ -0,0 +1,30 @@
+import type { TrashResourceType } from '@lobechat/types';
+
+import { topicHandler } from './topic';
+import type { TrashHandler } from './types';
+
+/**
+ * One handler per trashable kind. `Partial` on purpose: `TrashResourceType`
+ * already names the kinds this feature will cover, and they are wired in one
+ * at a time (topic first — see the phasing table in
+ * docs/development/soft-delete-recycle-bin-design.md). Nothing can register a
+ * registry row for a kind with no handler, since registration happens inside
+ * the handler itself.
+ */
+export const TRASH_HANDLERS: Partial<Record<TrashResourceType, TrashHandler>> = {
+ topic: topicHandler,
+};
+
+/**
+ * A registry row whose kind has no handler can only come from a newer version
+ * of the app writing rows this one does not understand — surface it instead of
+ * silently skipping the row and leaving it in the bin forever.
+ */
+export const resolveTrashHandler = (resourceType: TrashResourceType): TrashHandler => {
+ const handler = TRASH_HANDLERS[resourceType];
+ if (!handler) throw new Error(`No recycle-bin handler for resource type "${resourceType}"`);
+ return handler;
+};
+
+export { topicCascades } from './topic';
+export * from './types';
diff --git a/apps/server/src/services/trash/handlers/topic.ts b/apps/server/src/services/trash/handlers/topic.ts
new file mode 100644
index 00000000000..c39423bf5d7
--- /dev/null
+++ b/apps/server/src/services/trash/handlers/topic.ts
@@ -0,0 +1,66 @@
+import { serverDBEnv } from '@/config/db';
+import { FileModel } from '@/database/models/file';
+import { TopicModel } from '@/database/models/topic';
+import type { TrashRegisterEntry } from '@/database/models/trash';
+import type { TopicItem } from '@/database/schemas';
+
+import {
+ type TrashCascade,
+ type TrashHandler,
+ type TrashHandlerContext,
+ TrashRestoreError,
+} from './types';
+
+export const topicEntry = (topic: TopicItem, removeFiles?: boolean): TrashRegisterEntry => ({
+ meta: removeFiles ? { removeFiles: true } : undefined,
+ resourceId: topic.id,
+ resourceType: 'topic',
+ title: topic.title,
+});
+
+/**
+ * Every stamped topic becomes its own root (a bulk "clear topics" is N
+ * restorable rows, the same way a multi-select delete in a file manager is).
+ * Messages / threads under it are hidden by the parent and hard-cascade at
+ * purge time.
+ */
+export const topicCascades = (topics: TopicItem[], removeFiles?: boolean): TrashCascade[] =>
+ topics.map((topic) => ({ children: [], root: topicEntry(topic, removeFiles) }));
+
+export const topicHandler: TrashHandler = {
+ purge: async (ctx, root) => {
+ // `removeFiles` was requested at delete time: collect the attachments only
+ // this topic still references (same reference-safe set the hard delete
+ // used). Computed now, not at trash time, so a file that got attached
+ // elsewhere meanwhile is kept — and before the delete, because the lookup
+ // joins the messages the delete cascades away.
+ const fileModel = new FileModel(ctx.db, ctx.userId, ctx.workspaceId);
+ const fileIds = root.meta?.removeFiles
+ ? await fileModel.findDeletableFilesByTopicId(root.resourceId)
+ : [];
+
+ const purged = await new TopicModel(ctx.db, ctx.userId, ctx.workspaceId).purge([
+ root.resourceId,
+ ]);
+ // Nothing deleted means the topic was restored in the meantime: leave its
+ // attachments alone too.
+ if (purged.length === 0 || fileIds.length === 0) return;
+
+ const removed = await fileModel.deleteMany(fileIds, serverDBEnv.REMOVE_GLOBAL_FILE);
+ if (removed && removed.length > 0) {
+ await ctx.fileService.deleteFiles(removed.map((file) => file.url!));
+ }
+ },
+ restore: async (ctx: TrashHandlerContext, root) => {
+ const topicModel = new TopicModel(ctx.db, ctx.userId, ctx.workspaceId);
+ const [topic] = await topicModel.findTrashedByIds([root.resourceId]);
+ if (!topic) throw new TrashRestoreError('notFound');
+
+ // No parent-in-bin check yet: a topic's containers (agent, chat group) are
+ // not trashable in this phase, so they can never be sitting in the bin.
+ // The check goes in with the agent handler — see `TrashRestoreError`'s
+ // `parentTrashed` code, which the client already renders.
+ await topicModel.restore([root.resourceId]);
+ },
+ type: 'topic',
+};
diff --git a/apps/server/src/services/trash/handlers/types.ts b/apps/server/src/services/trash/handlers/types.ts
new file mode 100644
index 00000000000..1ce0d46513f
--- /dev/null
+++ b/apps/server/src/services/trash/handlers/types.ts
@@ -0,0 +1,61 @@
+import type { TrashResourceType, TrashRestoreErrorCode } from '@lobechat/types';
+
+import type { TrashRegisterEntry } from '@/database/models/trash';
+import type { TrashItemRow } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+import type { FileService } from '@/server/services/file';
+
+/**
+ * Per-request context handed to every handler. `db` may be a transaction
+ * client — handlers must build their models on it rather than reaching for a
+ * global instance so a failure between "stamp the rows" and "register them"
+ * rolls back both.
+ */
+export interface TrashHandlerContext {
+ db: LobeChatDatabase;
+ fileService: FileService;
+ userId: string;
+ workspaceId?: string;
+}
+
+/** What a soft delete produced: the root registry entry plus every cascaded child. */
+export interface TrashCascade {
+ children: TrashRegisterEntry[];
+ root: TrashRegisterEntry;
+}
+
+export class TrashRestoreError extends Error {
+ constructor(
+ public readonly code: TrashRestoreErrorCode,
+ message?: string,
+ ) {
+ super(message ?? code);
+ this.name = 'TrashRestoreError';
+ }
+}
+
+/**
+ * One handler per {@link TrashResourceType}. A handler owns three things:
+ * how its rows are stamped (and which children go along), how they come back,
+ * and how they are finally hard-deleted — including external side effects
+ * (S3 objects) that only run at purge time.
+ */
+export interface TrashHandler {
+ /**
+ * Hard-delete the root and its registered children. Runs after the row has
+ * been in the bin for the retention window, or when the user empties the bin.
+ */
+ purge: (ctx: TrashHandlerContext, root: TrashItemRow, children: TrashItemRow[]) => Promise<void>;
+ /**
+ * Un-stamp the root and its registered children. Must throw
+ * {@link TrashRestoreError} with `parentTrashed` when a parent of the root is
+ * itself in the bin (the user has to restore that root first), and with
+ * `notFound` when the source row is gone.
+ */
+ restore: (
+ ctx: TrashHandlerContext,
+ root: TrashItemRow,
+ children: TrashItemRow[],
+ ) => Promise<void>;
+ type: TrashResourceType;
+}
diff --git a/apps/server/src/services/trash/index.ts b/apps/server/src/services/trash/index.ts
new file mode 100644
index 00000000000..b4c687e924f
--- /dev/null
+++ b/apps/server/src/services/trash/index.ts
@@ -0,0 +1,336 @@
+import { TRASH_EMPTY_BATCH_SIZE, TRASH_PURGE_BATCH_SIZE } from '@lobechat/const';
+import type {
+ TrashCountByType,
+ TrashItem,
+ TrashListParams,
+ TrashListResult,
+ TrashResourceType,
+ TrashRestoreErrorCode,
+} from '@lobechat/types';
+import debug from 'debug';
+
+import { TopicModel } from '@/database/models/topic';
+import { TrashModel } from '@/database/models/trash';
+import type { TrashItemRow } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+import type { SoftDeleteOptions } from '@/database/utils/softDelete';
+import { FileService } from '@/server/services/file';
+
+import {
+ resolveTrashHandler,
+ topicCascades,
+ type TrashCascade,
+ type TrashHandlerContext,
+ TrashRestoreError,
+} from './handlers';
+
+const log = debug('lobe-server:trash');
+
+export { TrashRestoreError } from './handlers';
+
+export interface TrashOptions {
+ /** Workspace non-owner members may only sweep their own rows. */
+ restrictToCreator?: boolean;
+}
+
+export interface TrashRestoreOutcome {
+ failed: { code: TrashRestoreErrorCode; id: string }[];
+ restored: TrashItem[];
+}
+
+export interface TrashSweepOutcome {
+ /** Roots that threw during purge — left in place for the next tick. */
+ failed: number;
+ /** Registry rows dropped because their resource was already gone. */
+ pruned: number;
+ /** Roots hard-deleted this tick. */
+ purged: number;
+}
+
+/**
+ * Recycle-bin orchestrator. Every user-facing "delete" of a trash-aware entity
+ * funnels through `trashXxx` here: the handler stamps the rows (and their
+ * cascade), and the registry gets one root row plus a child row per cascaded
+ * resource. Restore / purge walk the registry the other way.
+ *
+ * Stamp + register run in one transaction, so a failure between the two can
+ * never leave rows hidden but unlisted.
+ */
+export class TrashService {
+ private readonly db: LobeChatDatabase;
+ private readonly userId: string;
+ private readonly workspaceId?: string;
+ private readonly trashModel: TrashModel;
+ private fileServiceInstance?: FileService;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.db = db;
+ this.userId = userId;
+ this.workspaceId = workspaceId;
+ this.trashModel = new TrashModel(db, userId, workspaceId);
+ }
+
+ /**
+ * Built on first use: the storage client reads S3 env at construction, and
+ * the service is instantiated in router middleware for every request —
+ * only purge paths ever need it.
+ */
+ private get fileService(): FileService {
+ this.fileServiceInstance ??= new FileService(this.db, this.userId, this.workspaceId);
+ return this.fileServiceInstance;
+ }
+
+ private ctx = (db: LobeChatDatabase = this.db): TrashHandlerContext => {
+ const getFileService = () => this.fileService;
+ return {
+ db,
+ get fileService() {
+ return getFileService();
+ },
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ };
+ };
+
+ private stampOptions = (options?: TrashOptions): SoftDeleteOptions => ({
+ deletedAt: new Date(),
+ restrictToCreator: options?.restrictToCreator,
+ });
+
+ /** Run a soft delete and register whatever it produced, atomically. */
+ private async commit(
+ run: (ctx: TrashHandlerContext) => Promise<TrashCascade[] | TrashCascade | null>,
+ deletedAt: Date,
+ ): Promise<TrashItemRow[]> {
+ return this.db.transaction(async (tx) => {
+ const db = tx as unknown as LobeChatDatabase;
+ const produced = await run(this.ctx(db));
+ const cascades = (Array.isArray(produced) ? produced : produced ? [produced] : []).filter(
+ Boolean,
+ );
+ // One chunked bulk write for the whole batch: a "clear all topics" over
+ // hundreds of rows must not hold the transaction open for one registry
+ // round trip per topic.
+ const roots = await new TrashModel(db, this.userId, this.workspaceId).registerMany(
+ { cascades, deletedAt },
+ tx,
+ );
+ log(
+ 'trashed %d root(s): %o',
+ roots.length,
+ roots.map((r) => `${r.resourceType}:${r.resourceId}`),
+ );
+ return roots;
+ });
+ }
+
+ // ─────────────────────────── trash (soft delete) ───────────────────────────
+
+ trashTopics = async (ids: string[], options?: TrashOptions & { removeFiles?: boolean }) => {
+ const stamp = this.stampOptions(options);
+ return this.commit(async (ctx) => {
+ const topics = await new TopicModel(ctx.db, this.userId, this.workspaceId).softDelete(
+ ids,
+ stamp,
+ );
+ return topicCascades(topics, options?.removeFiles);
+ }, stamp.deletedAt);
+ };
+
+ trashTopicsBySession = async (sessionId: string | null | undefined, options?: TrashOptions) => {
+ const stamp = this.stampOptions(options);
+ return this.commit(async (ctx) => {
+ const topics = await new TopicModel(
+ ctx.db,
+ this.userId,
+ this.workspaceId,
+ ).softDeleteBySessionId(sessionId, stamp);
+ return topicCascades(topics);
+ }, stamp.deletedAt);
+ };
+
+ trashTopicsByAgent = async (agentId: string, options?: TrashOptions) => {
+ const stamp = this.stampOptions(options);
+ return this.commit(async (ctx) => {
+ const topics = await new TopicModel(
+ ctx.db,
+ this.userId,
+ this.workspaceId,
+ ).softDeleteByAgentId(agentId, stamp);
+ return topicCascades(topics);
+ }, stamp.deletedAt);
+ };
+
+ trashTopicsByGroup = async (groupId: string | null | undefined, options?: TrashOptions) => {
+ const stamp = this.stampOptions(options);
+ return this.commit(async (ctx) => {
+ const topics = await new TopicModel(
+ ctx.db,
+ this.userId,
+ this.workspaceId,
+ ).softDeleteByGroupId(groupId, stamp);
+ return topicCascades(topics);
+ }, stamp.deletedAt);
+ };
+
+ trashAllTopics = async () => {
+ const stamp = this.stampOptions();
+ return this.commit(async (ctx) => {
+ const topics = await new TopicModel(ctx.db, this.userId, this.workspaceId).softDeleteAll(
+ stamp,
+ );
+ return topicCascades(topics);
+ }, stamp.deletedAt);
+ };
+
+ // ─────────────────────────── list ───────────────────────────
+
+ list = (params?: TrashListParams): Promise<TrashListResult> => this.trashModel.list(params);
+
+ countByType = (options?: { deletedByUserId?: string }): Promise<TrashCountByType> =>
+ this.trashModel.countByType(options);
+
+ findByIds = async (ids: string[]): Promise<TrashItem[]> =>
+ (await this.trashModel.findByIds(ids)).map(this.toItem);
+
+ // ─────────────────────────── restore ───────────────────────────
+
+ /**
+ * Restore roots by registry id. Each root is its own unit of work: one that
+ * cannot come back (parent still in the bin, resource already gone) is
+ * reported in `failed` and does not block the others.
+ */
+ restore = async (itemIds: string[]): Promise<TrashRestoreOutcome> => {
+ const outcome: TrashRestoreOutcome = { failed: [], restored: [] };
+ const roots = await this.trashModel.findByIds(itemIds);
+ const known = new Set(roots.map((row) => row.id));
+ for (const id of itemIds) {
+ if (!known.has(id)) outcome.failed.push({ code: 'notFound', id });
+ }
+
+ for (const root of roots) {
+ if (root.rootId) {
+ // Children are restored through their root, never on their own.
+ outcome.failed.push({ code: 'parentTrashed', id: root.id });
+ continue;
+ }
+ try {
+ await this.db.transaction(async (tx) => {
+ const db = tx as unknown as LobeChatDatabase;
+ const registry = new TrashModel(db, this.userId, this.workspaceId);
+ const children = await registry.findChildren(root.id, tx);
+ await resolveTrashHandler(root.resourceType).restore(this.ctx(db), root, children);
+ await registry.removeByIds([root.id], tx);
+ });
+ outcome.restored.push(this.toItem(root));
+ } catch (error) {
+ if (error instanceof TrashRestoreError) {
+ if (error.code === 'notFound') {
+ // Nothing to bring back — drop the stale registry row so the bin
+ // stops advertising it.
+ await this.trashModel.removeByIds([root.id]);
+ }
+ outcome.failed.push({ code: error.code, id: root.id });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return outcome;
+ };
+
+ // ─────────────────────────── purge (hard delete) ───────────────────────────
+
+ /** Permanently delete roots by registry id (their cascade goes with them). */
+ purge = async (itemIds: string[]): Promise<{ purged: number }> => {
+ const roots = (await this.trashModel.findByIds(itemIds)).filter((row) => !row.rootId);
+ let purged = 0;
+ for (const root of roots) {
+ await this.purgeRoot(root);
+ purged += 1;
+ }
+ return { purged };
+ };
+
+ /**
+ * Permanently delete one bounded batch of roots from the caller's bin
+ * (optionally one type only). Each purge is serial and may call storage, so
+ * a bin of thousands must not ride a single HTTP request: the caller repeats
+ * while `hasMore` is true, and every call commits only what it finished.
+ */
+ emptyTrash = async (options?: {
+ /**
+ * Restrict the sweep to roots this user trashed. A workspace non-owner may
+ * only empty their own items — filtered in the query, not on a page of
+ * results, so "empty trash" really does empty everything it is allowed to.
+ */
+ deletedByUserId?: string;
+ resourceType?: TrashResourceType;
+ }): Promise<{ hasMore: boolean; purged: number }> => {
+ const ids = await this.trashModel.listAllRootIds({
+ ...options,
+ limit: TRASH_EMPTY_BATCH_SIZE + 1,
+ });
+ const { purged } = await this.purge(ids.slice(0, TRASH_EMPTY_BATCH_SIZE));
+ // `purged === 0` with rows left means nothing in reach could be purged;
+ // stop instead of letting the client spin.
+ return { hasMore: ids.length > TRASH_EMPTY_BATCH_SIZE && purged > 0, purged };
+ };
+
+ private purgeRoot = async (root: TrashItemRow) => {
+ const children = await this.trashModel.findChildren(root.id);
+ // Side effects (S3) and hard deletes are not transactional with each
+ // other by nature; run them, then drop the registry rows. If the handler
+ // throws, the root stays listed and the sweep retries next tick.
+ await resolveTrashHandler(root.resourceType).purge(this.ctx(), root, children);
+ await this.trashModel.removeByIds([root.id]);
+ log('purged %s:%s (+%d children)', root.resourceType, root.resourceId, children.length);
+ };
+
+ private toItem = (row: TrashItemRow): TrashItem => ({
+ deletedAt: row.deletedAt,
+ deletedByUserId: row.deletedByUserId,
+ expiresAt: row.expiresAt,
+ id: row.id,
+ meta: row.meta ?? null,
+ resourceId: row.resourceId,
+ resourceType: row.resourceType,
+ rootId: row.rootId,
+ title: row.title,
+ userId: row.userId,
+ workspaceId: row.workspaceId,
+ });
+
+ // ─────────────────────────── sweep (cron) ───────────────────────────
+
+ /**
+ * Hard-delete every root past its `expiresAt`, across all users. Runs as a
+ * QStash schedule (see `router-hono/workflows/trash`). Each root is purged
+ * under its owner's scope; one failure is logged and skipped so a single
+ * poisoned row cannot stall the sweep.
+ */
+ static sweepExpired = async (
+ db: LobeChatDatabase,
+ options?: { limit?: number; now?: Date },
+ ): Promise<TrashSweepOutcome> => {
+ const outcome: TrashSweepOutcome = { failed: 0, pruned: 0, purged: 0 };
+ const roots = await TrashModel.listExpiredRoots(db, {
+ limit: options?.limit ?? TRASH_PURGE_BATCH_SIZE,
+ now: options?.now,
+ });
+
+ for (const root of roots) {
+ const service = new TrashService(db, root.userId, root.workspaceId ?? undefined);
+ try {
+ await service.purgeRoot(root);
+ outcome.purged += 1;
+ } catch (error) {
+ outcome.failed += 1;
+ log('purge failed for %s:%s — %O', root.resourceType, root.resourceId, error);
+ }
+ }
+
+ outcome.pruned = await TrashModel.pruneOrphans(db);
+ return outcome;
+ };
+}
diff --git a/docs/development/soft-delete-recycle-bin-design.md b/docs/development/soft-delete-recycle-bin-design.md
index 437b9629ebc..41a014a11de 100644
--- a/docs/development/soft-delete-recycle-bin-design.md
+++ b/docs/development/soft-delete-recycle-bin-design.md
@@ -19,19 +19,30 @@ The one-line contract:
## 0. Phasing
-The mechanism is generic, but it lands in two steps so the pattern can prove itself on the
-highest-traffic domain before it touches every content table:
-
-| Phase | Scope | Status |
-| ----- | -------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
-| 1 | Chat domain: **topics**, **agents**, **messages**; the bin UI; purge sweep | this branch (`feat/soft-delete-mvp`) |
-| 2 | chat groups, Pages / documents, files, knowledge bases, projects, tasks + goals, generation topics | already implemented end-to-end on `feat/soft-delete-recycle-bin`, held back until 1 ships |
-
-Phase 1 deliberately keeps a few phase-2 edges simple: `removeTopic({ removeFiles })` no longer
-deletes attachments at delete time — the flag is remembered on the registry row and the
-still-exclusive attachments are removed when the topic is **purged** (files stay live and visible in
-the meantime, since `files` has no stamp yet); and bulk "clear conversation" sweeps
-(`removeMessagesByAssistant/ByGroup`) remain hard deletes.
+The mechanism is generic, but it lands one layer — and then one entity — at a time, so each step is
+small enough to verify on its own:
+
+| Step | Scope | Where |
+| ---- | -------------------------------------------------------------------------------------------------- | -------------------------------- |
+| 1 | Schema: `trash_items` + `is_deleted` / `deleted_at` on 19 content tables | merged (`0152`) |
+| 2 | Read side: every ownership-scoped read hides stamped rows | `feat/soft-delete-schema` |
+| 3 | **Topics** end to end — stamp, register, restore, purge, sweep — plus the recycle-bin UI | `feat/trash-topic` (this branch) |
+| 4 | Agents (cascading to their topics) and messages (tree rewrite) | `feat/soft-delete-mvp` |
+| 5 | Chat groups, Pages / documents, files, knowledge bases, projects, tasks + goals, generation topics | `feat/soft-delete-recycle-bin` |
+
+Step 3 is the smallest slice that is useful on its own: deleting a conversation is the most frequent
+destructive action in the product, and a topic's cascade is the simplest one (messages and threads
+are hidden by their parent and hard-cascade at purge, so nothing below the topic needs a stamp).
+
+While only topics are trashable, a few edges stay deliberately simple:
+
+- `removeTopic({ removeFiles })` no longer deletes attachments at delete time — the flag is
+ remembered on the registry row and the still-exclusive attachments are removed when the topic is
+ **purged**. Files have no stamp yet, so they stay visible in the meantime.
+- The restore path has no parent-in-bin check: a topic's containers (agent, chat group) cannot be
+ trashed yet, so they can never be sitting in the bin. The check arrives with the agent handler.
+- Bulk "clear conversation" sweeps (`removeMessagesByAssistant/ByGroup`) and every non-topic delete
+ remain hard deletes.
## 1. Audit — what deletion looked like before
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 8de4cbab389..81db7eed6fa 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -1305,6 +1305,7 @@
"settingsSearch.tabKeywords.stats": "analytics, statistics, stats",
"settingsSearch.tabKeywords.storage": "storage, files, import, export, backup, reset, clear data, clear storage, knowledge base, account deletion, delete account",
"settingsSearch.tabKeywords.systemTools": "system tools, built-in tools, system, node, python, cli, environment",
+ "settingsSearch.tabKeywords.trash": "trash, recycle bin, deleted, restore, undelete, recover",
"settingsSearch.tabKeywords.usage": "usage, consumption, quota, spend, statistics",
"skillGroup.agentConnectors": "Agent Connectors",
"skillGroup.builtinSkills": "Built-in Skills",
@@ -1529,6 +1530,7 @@
"tab.sync": "Cloud Sync",
"tab.systemTools": "System Tools",
"tab.tools": "Tools",
+ "tab.trash": "Trash",
"tab.tts": "Text-to-Speech",
"tab.uploadZip": "Upload Zip",
"tab.uploadZip.desc": "Upload a local .zip or .skill file",
@@ -1746,6 +1748,38 @@
"tools.tabs.all": "All",
"tools.tabs.installed": "Enabled",
"tools.title": "Skills",
+ "trash.actions.empty": "Empty trash",
+ "trash.actions.emptyType": "Empty {{type}}",
+ "trash.actions.loadMore": "Load more",
+ "trash.actions.purge": "Delete forever",
+ "trash.actions.restore": "Restore",
+ "trash.columns.deletedAt": "Deleted",
+ "trash.columns.expiresIn": "Auto-deletes",
+ "trash.columns.name": "Name",
+ "trash.columns.type": "Type",
+ "trash.desc": "Deleted items stay here for {{days}} days and can be restored. After that they are removed permanently.",
+ "trash.empty.desc": "Conversations, agents and messages you delete land here for {{days}} days before they are removed for good.",
+ "trash.empty.title": "Trash is empty",
+ "trash.emptyConfirm.content": "Permanently delete {{count}} item(s)? This cannot be undone.",
+ "trash.emptyConfirm.title": "Empty trash",
+ "trash.emptyType.desc": "No deleted {{type}} right now.",
+ "trash.expiresIn.days": "in {{count}} days",
+ "trash.expiresIn.soon": "within a day",
+ "trash.filter.all": "All",
+ "trash.loadFailed.desc": "Check your connection and try again.",
+ "trash.loadFailed.title": "Could not load the trash",
+ "trash.meta.children": "{{count}} items inside",
+ "trash.purge.success": "Deleted permanently",
+ "trash.purgeConfirm.content": "Permanently delete \"{{title}}\"? This cannot be undone.",
+ "trash.purgeConfirm.title": "Delete forever",
+ "trash.restore.failed.notFound": "This item no longer exists.",
+ "trash.restore.failed.parentTrashed": "Restore the container it belongs to first — that item is also in the trash.",
+ "trash.restore.success": "Restored",
+ "trash.title": "Trash",
+ "trash.type.agent": "Agent",
+ "trash.type.message": "Message",
+ "trash.type.topic": "Topic",
+ "trash.untitled": "Untitled",
"workspace.apiKey.policy.desc": "Choose who can create personal API Keys that act on their behalf in this workspace.",
"workspace.apiKey.policy.options.allMembers": "All members",
"workspace.apiKey.policy.options.onlyAdmins": "Only admins",
diff --git a/locales/en-US/topic.json b/locales/en-US/topic.json
index f532af55390..aabc9ac0174 100644
--- a/locales/en-US/topic.json
+++ b/locales/en-US/topic.json
@@ -9,17 +9,17 @@
"actions.archiveMergedPullRequestsWorkspace": "Archive All Topics with Merged PRs",
"actions.autoRename": "Smart Rename",
"actions.confirmArchiveMergedPullRequestsWorkspace": "Archive all Workspace topics with merged PRs, including topics created by other members?",
- "actions.confirmRemoveAll": "You are about to delete all topics. This action cannot be undone.",
- "actions.confirmRemoveAllOwn": "You are about to delete all topics you created in the current list. Topics created by other Workspace members will remain. This action cannot be undone.",
- "actions.confirmRemoveAllWorkspace": "You are about to delete all topics in the current Workspace list, including topics created by other members. This action cannot be undone.",
- "actions.confirmRemoveAllWorkspaceAcknowledge": "I understand that this permanently deletes other members' topics.",
- "actions.confirmRemoveTopic": "You are about to delete this topic. This action cannot be undone.",
+ "actions.confirmRemoveAll": "You are about to delete all topics. They will be moved to the trash and can be restored within 30 days.",
+ "actions.confirmRemoveAllOwn": "You are about to delete all topics you created in the current list. Topics created by other Workspace members will remain. Deleted topics move to the trash and can be restored within 30 days.",
+ "actions.confirmRemoveAllWorkspace": "You are about to delete all topics in the current Workspace list, including topics created by other members. They move to the trash and can be restored within 30 days.",
+ "actions.confirmRemoveAllWorkspaceAcknowledge": "I understand that this moves other members' topics to the trash.",
+ "actions.confirmRemoveTopic": "You are about to delete this topic. It will be moved to the trash and can be restored within 30 days.",
"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.confirmRemoveUnstarredOwn": "You are about to delete unstarred topics you created. Topics created by other Workspace members will remain. This action cannot be undone.",
- "actions.confirmRemoveUnstarredWorkspace": "You are about to delete all unstarred topics in the current Workspace list, including topics created by other members. Starred topics will remain. This action cannot be undone.",
- "actions.confirmRemoveUnstarredWorkspaceAcknowledge": "I understand that this permanently deletes other members' unstarred topics.",
+ "actions.confirmRemoveUnstarred": "You are about to delete unstarred topics. They will be moved to the trash and can be restored within 30 days.",
+ "actions.confirmRemoveUnstarredOwn": "You are about to delete unstarred topics you created. Topics created by other Workspace members will remain. Deleted topics move to the trash and can be restored within 30 days.",
+ "actions.confirmRemoveUnstarredWorkspace": "You are about to delete all unstarred topics in the current Workspace list, including topics created by other members. Starred topics will remain. Deleted topics move to the trash and can be restored within 30 days.",
+ "actions.confirmRemoveUnstarredWorkspaceAcknowledge": "I understand that this moves other members' unstarred topics to the trash.",
"actions.copyLink": "Copy Link",
"actions.copyLinkSuccess": "Link copied",
"actions.copySessionId": "Copy Topic ID",
@@ -157,7 +157,7 @@
"management.bulk.archive": "Archive",
"management.bulk.cancel": "Cancel",
"management.bulk.delete": "Delete",
- "management.bulk.deleteConfirm": "You are about to delete {{count}} topics. This action cannot be undone.",
+ "management.bulk.deleteConfirm": "You are about to delete {{count}} topics. They will be moved to the trash and can be restored within 30 days.",
"management.bulk.deleteTitle": "Delete topics?",
"management.bulk.favorite": "Favorite",
"management.bulk.move": "Move to agent",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index bfe5eae6294..9b37a251cfd 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -1305,6 +1305,7 @@
"settingsSearch.tabKeywords.stats": "数据统计,统计,分析",
"settingsSearch.tabKeywords.storage": "存储,文件,导入,导出,备份,重置,清除数据,清理存储,知识库,资源,注销,删除账号",
"settingsSearch.tabKeywords.systemTools": "系统工具,内置工具,系统,node,python,cli,环境",
+ "settingsSearch.tabKeywords.trash": "回收站, 垃圾桶, 已删除, 恢复, 还原, 找回",
"settingsSearch.tabKeywords.usage": "用量,消耗,配额,花费,统计",
"skillGroup.agentConnectors": "助理连接器",
"skillGroup.builtinSkills": "内置技能",
@@ -1529,6 +1530,7 @@
"tab.sync": "云端同步",
"tab.systemTools": "系统工具",
"tab.tools": "工具",
+ "tab.trash": "回收站",
"tab.tts": "语音服务",
"tab.uploadZip": "上传 Zip",
"tab.uploadZip.desc": "上传本地 .zip 或 .skill 文件",
@@ -1746,6 +1748,38 @@
"tools.tabs.all": "全部",
"tools.tabs.installed": "已启用",
"tools.title": "技能",
+ "trash.actions.empty": "清空回收站",
+ "trash.actions.emptyType": "清空{{type}}",
+ "trash.actions.loadMore": "加载更多",
+ "trash.actions.purge": "彻底删除",
+ "trash.actions.restore": "恢复",
+ "trash.columns.deletedAt": "删除时间",
+ "trash.columns.expiresIn": "自动清理",
+ "trash.columns.name": "名称",
+ "trash.columns.type": "类型",
+ "trash.desc": "删除的内容会在回收站保留 {{days}} 天,期间可以随时恢复;到期后将被永久删除。",
+ "trash.empty.desc": "你删除的会话、助手和消息会先进入这里,保留 {{days}} 天后才会被永久删除。",
+ "trash.empty.title": "回收站是空的",
+ "trash.emptyConfirm.content": "永久删除这 {{count}} 项?此操作无法撤销。",
+ "trash.emptyConfirm.title": "清空回收站",
+ "trash.emptyType.desc": "目前没有已删除的{{type}}。",
+ "trash.expiresIn.days": "{{count}} 天后",
+ "trash.expiresIn.soon": "一天内",
+ "trash.filter.all": "全部",
+ "trash.loadFailed.desc": "请检查网络连接后重试。",
+ "trash.loadFailed.title": "回收站加载失败",
+ "trash.meta.children": "内含 {{count}} 项",
+ "trash.purge.success": "已永久删除",
+ "trash.purgeConfirm.content": "永久删除「{{title}}」?此操作无法撤销。",
+ "trash.purgeConfirm.title": "彻底删除",
+ "trash.restore.failed.notFound": "该项目已不存在。",
+ "trash.restore.failed.parentTrashed": "它所属的容器也在回收站中,请先恢复该容器。",
+ "trash.restore.success": "已恢复",
+ "trash.title": "回收站",
+ "trash.type.agent": "助手",
+ "trash.type.message": "消息",
+ "trash.type.topic": "话题",
+ "trash.untitled": "未命名",
"workspace.apiKey.policy.desc": "选择哪些成员可以创建代表自己访问此工作区的个人 API Key。",
"workspace.apiKey.policy.options.allMembers": "所有成员",
"workspace.apiKey.policy.options.onlyAdmins": "仅管理员",
diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.json
index 3b94e319347..923e82fa565 100644
--- a/locales/zh-CN/topic.json
+++ b/locales/zh-CN/topic.json
@@ -9,17 +9,17 @@
"actions.archiveMergedPullRequestsWorkspace": "归档所有 PR 已合并的话题",
"actions.autoRename": "智能重命名",
"actions.confirmArchiveMergedPullRequestsWorkspace": "归档工作区中所有 PR 已合并的话题,包括其他成员创建的话题?",
- "actions.confirmRemoveAll": "您即将删除所有话题,此操作无法撤销。",
- "actions.confirmRemoveAllOwn": "您即将删除当前列表中由您创建的全部话题。其他工作区成员创建的话题将保留。此操作无法撤销。",
- "actions.confirmRemoveAllWorkspace": "您即将删除当前工作区列表中的全部话题,包括其他成员创建的话题。此操作无法撤销。",
- "actions.confirmRemoveAllWorkspaceAcknowledge": "我已知晓此操作将永久删除其他成员的话题",
- "actions.confirmRemoveTopic": "您即将删除此话题,此操作无法撤销。",
+ "actions.confirmRemoveAll": "即将删除全部话题。它们会移入回收站,30 天内可以恢复。",
+ "actions.confirmRemoveAllOwn": "即将删除当前列表中你创建的全部话题,其他 Workspace 成员创建的话题会保留。已删除的话题会移入回收站,30 天内可以恢复。",
+ "actions.confirmRemoveAllWorkspace": "即将删除当前 Workspace 列表中的全部话题,包括其他成员创建的话题。它们会移入回收站,30 天内可以恢复。",
+ "actions.confirmRemoveAllWorkspaceAcknowledge": "我知道这会把其他成员的话题移入回收站。",
+ "actions.confirmRemoveTopic": "即将删除此话题。它会移入回收站,30 天内可以恢复。",
"actions.confirmRemoveTopicFiles": "同时删除此话题中上传的图片和文件",
"actions.confirmRemoveTopicTitle": "删除此话题?",
- "actions.confirmRemoveUnstarred": "您即将删除未加星标的话题,此操作无法撤销。",
- "actions.confirmRemoveUnstarredOwn": "您即将删除自己创建的未收藏话题。其他工作区成员创建的话题将保留。此操作无法撤销。",
- "actions.confirmRemoveUnstarredWorkspace": "您即将删除当前工作区列表中的所有未收藏话题,包括其他成员创建的话题。已收藏话题会保留。此操作无法撤销。",
- "actions.confirmRemoveUnstarredWorkspaceAcknowledge": "我已知晓此操作将永久删除其他成员创建的未收藏话题",
+ "actions.confirmRemoveUnstarred": "即将删除未收藏的话题。它们会移入回收站,30 天内可以恢复。",
+ "actions.confirmRemoveUnstarredOwn": "即将删除你创建的未收藏话题,其他 Workspace 成员创建的话题会保留。已删除的话题会移入回收站,30 天内可以恢复。",
+ "actions.confirmRemoveUnstarredWorkspace": "即将删除当前 Workspace 列表中的全部未收藏话题,包括其他成员创建的话题;已收藏的话题会保留。已删除的话题会移入回收站,30 天内可以恢复。",
+ "actions.confirmRemoveUnstarredWorkspaceAcknowledge": "我知道这会把其他成员未收藏的话题移入回收站。",
"actions.copyLink": "复制链接",
"actions.copyLinkSuccess": "链接已复制",
"actions.copySessionId": "复制话题 ID",
@@ -157,7 +157,7 @@
"management.bulk.archive": "归档",
"management.bulk.cancel": "取消",
"management.bulk.delete": "删除",
- "management.bulk.deleteConfirm": "即将删除 {{count}} 个话题,此操作无法撤销。",
+ "management.bulk.deleteConfirm": "即将删除 {{count}} 个话题。它们会移入回收站,30 天内可以恢复。",
"management.bulk.deleteTitle": "删除话题?",
"management.bulk.favorite": "收藏",
"management.bulk.move": "移动到助手",
diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.ts
index e62da458512..41897b08812 100644
--- a/packages/const/src/apiKeyScope.ts
+++ b/packages/const/src/apiKeyScope.ts
@@ -281,6 +281,10 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRule
topUp: 'blocked',
topic: rw('chat:read', 'chat:write'),
topicComment: rw('chat:read', 'chat:write'),
+ // The recycle bin spans every content kind (chats, agents, files, tasks …) —
+ // restore / purge is a destructive cross-cutting surface, so restricted keys
+ // never reach it; only full-access keys can.
+ trash: 'blocked',
upload: rw('file:read', 'file:write'),
usage: rw('usage:read', null),
user: rw('user:read', 'user:write'),
diff --git a/packages/const/src/index.ts b/packages/const/src/index.ts
index a11fa934c75..8b6d2d4a294 100644
--- a/packages/const/src/index.ts
+++ b/packages/const/src/index.ts
@@ -31,6 +31,7 @@ export * from './theme';
export * from './threadDrag';
export * from './topicDrag';
export * from './trace';
+export * from './trash';
export * from './url';
export * from './user';
export * from './userMemory';
diff --git a/packages/const/src/trash.ts b/packages/const/src/trash.ts
new file mode 100644
index 00000000000..aadae0b52fc
--- /dev/null
+++ b/packages/const/src/trash.ts
@@ -0,0 +1,21 @@
+/**
+ * How long a trashed item stays restorable before the purge sweep hard-deletes
+ * it. Mirrors the retention most desktop / cloud recycle bins use, long enough
+ * that a Monday "where did my chat go" still finds last month's cleanup.
+ */
+export const TRASH_RETENTION_DAYS = 30;
+
+export const TRASH_RETENTION_MS = TRASH_RETENTION_DAYS * 24 * 60 * 60 * 1000;
+
+/** Page size the recycle bin UI asks for; keeps the first paint cheap. */
+export const TRASH_LIST_PAGE_SIZE = 50;
+
+/**
+ * Roots one "empty trash" request purges before handing control back to the
+ * client, which repeats while more remain. Each purge is serial and may call
+ * storage, so this keeps a single request well inside its time budget.
+ */
+export const TRASH_EMPTY_BATCH_SIZE = 50;
+
+/** Roots the purge sweep hard-deletes per invocation. Bounded so one cron tick never runs away. */
+export const TRASH_PURGE_BATCH_SIZE = 200;
diff --git a/packages/database/src/models/__tests__/topicShare.test.ts b/packages/database/src/models/__tests__/topicShare.test.ts
index 4367d5bd6f8..2b2724383c5 100644
--- a/packages/database/src/models/__tests__/topicShare.test.ts
+++ b/packages/database/src/models/__tests__/topicShare.test.ts
@@ -1,5 +1,6 @@
// @vitest-environment node
import { TRPCError } from '@trpc/server';
+import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
@@ -106,6 +107,25 @@ describe('TopicShareModel', () => {
expect(result!.visibility).toBe('link');
});
+ it('stops resolving once the topic is in the recycle bin', async () => {
+ // A trashed topic keeps its share row and its messages until purge, and
+ // this query carries no user scope (that is the point of a public link),
+ // so without an explicit gate an anonymous visitor could keep reading a
+ // deleted conversation.
+ const created = await topicShareModel.create(topicId, 'link');
+ expect(await TopicShareModel.findByShareId(serverDB, created.id)).toBeDefined();
+
+ await serverDB
+ .update(topics)
+ .set({ deletedAt: new Date(), isDeleted: true })
+ .where(eq(topics.id, topicId));
+
+ expect(await TopicShareModel.findByShareId(serverDB, created.id)).toBeNull();
+ await expect(
+ TopicShareModel.findByShareIdWithAccessCheck(serverDB, created.id, userId),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
it('should return null when share does not exist', async () => {
const result = await topicShareModel.updateVisibility('non-existent-topic', 'link');
diff --git a/packages/database/src/models/__tests__/trash.test.ts b/packages/database/src/models/__tests__/trash.test.ts
new file mode 100644
index 00000000000..1671db068f7
--- /dev/null
+++ b/packages/database/src/models/__tests__/trash.test.ts
@@ -0,0 +1,238 @@
+import { TRASH_RETENTION_MS } from '@lobechat/const';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { topics, trashItems, users, workspaces } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { TrashModel } from '../trash';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'trash-model-user';
+const otherUserId = 'trash-model-other';
+const workspaceId = 'trash-model-ws';
+
+const model = new TrashModel(serverDB, userId);
+const otherModel = new TrashModel(serverDB, otherUserId);
+
+const at = (iso: string) => new Date(iso);
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: userId, slug: workspaceId });
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+describe('TrashModel', () => {
+ describe('register', () => {
+ it('registers a root with children and stamps expiry from the retention window', async () => {
+ const deletedAt = at('2026-08-01T00:00:00Z');
+ const root = await model.register({
+ children: [
+ { resourceId: 'tpc_1', resourceType: 'topic', title: 'first' },
+ { resourceId: 'tpc_2', resourceType: 'topic', title: 'second' },
+ ],
+ deletedAt,
+ root: { meta: { childCount: 2 }, resourceId: 'agt_1', resourceType: 'agent', title: 'Bot' },
+ });
+
+ expect(root.rootId).toBeNull();
+ expect(root.deletedByUserId).toBe(userId);
+ expect(root.expiresAt.getTime()).toBe(deletedAt.getTime() + TRASH_RETENTION_MS);
+
+ const children = await model.findChildren(root.id);
+ expect(children.map((c) => c.resourceId).sort()).toEqual(['tpc_1', 'tpc_2']);
+ expect(children.every((c) => c.rootId === root.id)).toBe(true);
+ });
+
+ it('is idempotent on the root resource and keeps a child that was trashed earlier on its own', async () => {
+ // A topic trashed last week keeps its own root row when its agent is
+ // trashed today: it was in the bin before the agent and must stay there
+ // after the agent is restored.
+ const topicRoot = await model.register({
+ deletedAt: at('2026-08-01T00:00:00Z'),
+ root: { resourceId: 'tpc_old', resourceType: 'topic', title: 'old' },
+ });
+ const agentRoot = await model.register({
+ children: [
+ { resourceId: 'tpc_old', resourceType: 'topic', title: 'old' },
+ { resourceId: 'tpc_new', resourceType: 'topic', title: 'new' },
+ ],
+ deletedAt: at('2026-08-08T00:00:00Z'),
+ root: { resourceId: 'agt_1', resourceType: 'agent', title: 'Bot' },
+ });
+ const again = await model.register({
+ deletedAt: at('2026-08-09T00:00:00Z'),
+ root: { resourceId: 'agt_1', resourceType: 'agent', title: 'Bot renamed' },
+ });
+
+ expect(again.id).toBe(agentRoot.id);
+ expect(again.title).toBe('Bot renamed');
+
+ const oldTopic = await model.findByResource('topic', 'tpc_old');
+ expect(oldTopic?.id).toBe(topicRoot.id);
+ expect(oldTopic?.rootId).toBeNull();
+
+ const children = await model.findChildren(agentRoot.id);
+ expect(children.map((c) => c.resourceId)).toEqual(['tpc_new']);
+ });
+ });
+
+ describe('registerMany', () => {
+ it('registers many roots with their children in one call, in input order', async () => {
+ const cascades = Array.from({ length: 3 }, (_, i) => ({
+ children: [{ resourceId: `msg_${i}`, resourceType: 'message' as const }],
+ root: { resourceId: `tpc_${i}`, resourceType: 'topic' as const, title: `t${i}` },
+ }));
+ const roots = await model.registerMany({
+ cascades,
+ deletedAt: at('2026-08-01T00:00:00Z'),
+ });
+
+ expect(roots.map((r) => r.resourceId)).toEqual(['tpc_0', 'tpc_1', 'tpc_2']);
+ expect(roots.every((r) => r.rootId === null)).toBe(true);
+ for (const [i, root] of roots.entries()) {
+ const children = await model.findChildren(root.id);
+ expect(children.map((c) => c.resourceId)).toEqual([`msg_${i}`]);
+ }
+
+ // re-registering converges on the existing rows instead of failing
+ const again = await model.registerMany({
+ cascades: cascades.slice(0, 1),
+ deletedAt: at('2026-08-02T00:00:00Z'),
+ });
+ expect(again[0].id).toBe(roots[0].id);
+ expect(again[0].deletedAt).toEqual(at('2026-08-02T00:00:00Z'));
+ });
+ });
+
+ describe('list / countByType', () => {
+ it('lists roots only, newest first, scoped to the caller, with type filter and keyset paging', async () => {
+ for (let i = 0; i < 5; i++) {
+ await model.register({
+ children: [{ resourceId: `child_${i}`, resourceType: 'topic' }],
+ deletedAt: at(`2026-08-0${i + 1}T00:00:00Z`),
+ root: { resourceId: `agt_${i}`, resourceType: 'agent', title: `agent ${i}` },
+ });
+ }
+ await model.register({
+ deletedAt: at('2026-08-09T00:00:00Z'),
+ root: { resourceId: 'msg_1', resourceType: 'message', title: 'a message' },
+ });
+ await otherModel.register({
+ deletedAt: at('2026-08-10T00:00:00Z'),
+ root: { resourceId: 'agt_other', resourceType: 'agent', title: 'not mine' },
+ });
+
+ const first = await model.list({ limit: 3 });
+ expect(first.items.map((i) => i.resourceId)).toEqual(['msg_1', 'agt_4', 'agt_3']);
+ expect(first.nextCursor).toBeTruthy();
+
+ const second = await model.list({ cursor: first.nextCursor, limit: 3 });
+ expect(second.items.map((i) => i.resourceId)).toEqual(['agt_2', 'agt_1', 'agt_0']);
+ expect(second.nextCursor).toBeNull();
+
+ const agentsOnly = await model.list({ resourceType: 'agent' });
+ expect(agentsOnly.items).toHaveLength(5);
+ expect(agentsOnly.items.every((i) => i.rootId === null)).toBe(true);
+
+ expect(await model.countByType()).toEqual({ agent: 5, message: 1 });
+ expect(await otherModel.countByType()).toEqual({ agent: 1 });
+ });
+
+ it('scopes workspace listings to the workspace, not the caller', async () => {
+ const wsModel = new TrashModel(serverDB, userId, workspaceId);
+ const wsOther = new TrashModel(serverDB, otherUserId, workspaceId);
+ await wsModel.register({
+ deletedAt: at('2026-08-01T00:00:00Z'),
+ root: { resourceId: 'tpc_ws', resourceType: 'topic', title: 'spec' },
+ });
+ await model.register({
+ deletedAt: at('2026-08-02T00:00:00Z'),
+ root: { resourceId: 'tpc_personal', resourceType: 'topic', title: 'mine' },
+ });
+
+ const seenByTeammate = await wsOther.list();
+ expect(seenByTeammate.items.map((i) => i.resourceId)).toEqual(['tpc_ws']);
+ expect((await model.list()).items.map((i) => i.resourceId)).toEqual(['tpc_personal']);
+ });
+
+ it('narrows list and counts to one actor with deletedByUserId', async () => {
+ const wsModel = new TrashModel(serverDB, userId, workspaceId);
+ const wsOther = new TrashModel(serverDB, otherUserId, workspaceId);
+ await wsModel.register({
+ deletedAt: at('2026-08-01T00:00:00Z'),
+ root: { resourceId: 'msg_owner', resourceType: 'message', title: 'private excerpt' },
+ });
+ await wsOther.register({
+ deletedAt: at('2026-08-02T00:00:00Z'),
+ root: { resourceId: 'tpc_member', resourceType: 'topic', title: 'member topic' },
+ });
+
+ const own = await wsOther.list({ deletedByUserId: otherUserId });
+ expect(own.items.map((i) => i.resourceId)).toEqual(['tpc_member']);
+ expect(await wsOther.countByType({ deletedByUserId: otherUserId })).toEqual({ topic: 1 });
+ // without the filter the workspace scope still sees both
+ expect(await wsOther.countByType()).toEqual({ message: 1, topic: 1 });
+ });
+ });
+
+ describe('removeByIds', () => {
+ it('drops the root and cascades its children', async () => {
+ const root = await model.register({
+ children: [{ resourceId: 'tpc_1', resourceType: 'topic' }],
+ deletedAt: at('2026-08-01T00:00:00Z'),
+ root: { resourceId: 'agt_1', resourceType: 'agent' },
+ });
+ await model.removeByIds([root.id]);
+ expect(await serverDB.select().from(trashItems)).toHaveLength(0);
+ });
+ });
+
+ describe('sweep helpers', () => {
+ it('listExpiredRoots returns roots past their expiry across users, oldest first', async () => {
+ const now = at('2026-09-15T00:00:00Z');
+ await model.register({
+ deletedAt: at('2026-08-01T00:00:00Z'), // expires 08-31
+ root: { resourceId: 'agt_expired', resourceType: 'agent' },
+ });
+ await otherModel.register({
+ deletedAt: at('2026-07-01T00:00:00Z'), // expires 07-31
+ root: { resourceId: 'agt_older', resourceType: 'agent' },
+ });
+ await model.register({
+ deletedAt: at('2026-09-10T00:00:00Z'), // not yet
+ root: { resourceId: 'agt_fresh', resourceType: 'agent' },
+ });
+
+ const due = await TrashModel.listExpiredRoots(serverDB, { limit: 10, now });
+ expect(due.map((r) => r.resourceId)).toEqual(['agt_older', 'agt_expired']);
+ });
+
+ it('pruneOrphans drops registry rows whose resource is gone or no longer stamped', async () => {
+ const deletedAt = at('2026-08-01T00:00:00Z');
+ await serverDB.insert(topics).values([
+ { deletedAt, id: 'tpc_stamped', isDeleted: true, title: 'still trashed', userId },
+ { id: 'tpc_live', title: 'restored elsewhere', userId },
+ ]);
+ await model.register({
+ deletedAt,
+ root: { resourceId: 'tpc_stamped', resourceType: 'topic' },
+ });
+ await model.register({ deletedAt, root: { resourceId: 'tpc_live', resourceType: 'topic' } });
+ await model.register({ deletedAt, root: { resourceId: 'tpc_gone', resourceType: 'topic' } });
+
+ const pruned = await TrashModel.pruneOrphans(serverDB);
+ expect(pruned).toBe(2);
+ const left = await serverDB.select().from(trashItems).where(eq(trashItems.userId, userId));
+ expect(left.map((r) => r.resourceId)).toEqual(['tpc_stamped']);
+ });
+ });
+});
diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.ts
index 6a3c27d83ef..c5a200ac431 100644
--- a/packages/database/src/models/topic.ts
+++ b/packages/database/src/models/topic.ts
@@ -59,7 +59,13 @@ import { idGenerator } from '../utils/idGenerator';
import { inJsonStringArray } from '../utils/inJsonStringArray';
import { searchableMessage } from '../utils/searchableMessage';
import { notShareVisitorTopic } from '../utils/shareVisitor';
-import { notTrashed } from '../utils/softDelete';
+import {
+ isTrashed,
+ notTrashed,
+ restoreStamp,
+ type SoftDeleteOptions,
+ trashStamp,
+} from '../utils/softDelete';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
import { recomputeTopicUsage } from './topicUsage';
@@ -458,6 +464,19 @@ export class TopicModel {
private workspaceScope = () =>
buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics);
+ /**
+ * {@link workspaceScope} without the recycle-bin filter, still excluding
+ * share-visitor topics — restore / trash lookups / purge internals only.
+ */
+ private trashScope = () =>
+ and(
+ buildWorkspaceWhere(
+ { includeTrashed: true, userId: this.userId, workspaceId: this.workspaceId },
+ topics,
+ ),
+ this.notShareVisitor(),
+ );
+
private ownership = () => and(this.workspaceScope(), this.notShareVisitor());
/**
@@ -1792,6 +1811,152 @@ export class TopicModel {
return this.db.delete(topics).where(and(this.mine(), this.notShareVisitor()));
};
+ // **************** Recycle bin *************** //
+
+ /**
+ * Move topics to the recycle bin: stamp `deleted_at` and return the rows so
+ * the caller can register them. Rows already trashed are left untouched (their
+ * own registry row keeps their original stamp). Messages / threads are not
+ * stamped — they are hidden by their parent and hard-cascade at purge time.
+ */
+ softDelete = async (ids: string[], options: SoftDeleteOptions): Promise<TopicItem[]> => {
+ if (ids.length === 0) return [];
+ return this.db
+ .update(topics)
+ .set(trashStamp(options.deletedAt))
+ .where(
+ and(
+ inArray(topics.id, ids),
+ options.restrictToCreator ? this.mine() : this.ownership(),
+ this.notShareVisitor(),
+ ),
+ )
+ .returning();
+ };
+
+ /** Soft-delete counterpart of `batchDeleteBySessionId` (`sessionId` null = the agent's default session). */
+ softDeleteBySessionId = async (
+ sessionId: string | null | undefined,
+ options: SoftDeleteOptions,
+ ): Promise<TopicItem[]> => {
+ return this.db
+ .update(topics)
+ .set(trashStamp(options.deletedAt))
+ .where(
+ and(
+ this.matchSession(sessionId),
+ options.restrictToCreator ? this.mine() : this.ownership(),
+ this.notShareVisitor(),
+ ),
+ )
+ .returning();
+ };
+
+ softDeleteByGroupId = async (
+ groupId: string | null | undefined,
+ options: SoftDeleteOptions,
+ ): Promise<TopicItem[]> => {
+ return this.db
+ .update(topics)
+ .set(trashStamp(options.deletedAt))
+ .where(
+ and(
+ this.matchGroup(groupId),
+ options.restrictToCreator ? this.mine() : this.ownership(),
+ this.notShareVisitor(),
+ ),
+ )
+ .returning();
+ };
+
+ softDeleteByAgentId = async (
+ agentId: string,
+ options: SoftDeleteOptions,
+ ): Promise<TopicItem[]> => {
+ return this.db
+ .update(topics)
+ .set(trashStamp(options.deletedAt))
+ .where(
+ and(
+ eq(topics.agentId, agentId),
+ options.restrictToCreator ? this.mine() : this.ownership(),
+ this.notShareVisitor(),
+ ),
+ )
+ .returning();
+ };
+
+ /**
+ * Cascade helper for trashing an agent / group / session: stamps every live
+ * topic that hangs off any of the given parents (by `agent_id`, `session_id`
+ * or `group_id`) in one statement.
+ */
+ softDeleteByParents = async (
+ parents: { agentIds?: string[]; groupIds?: string[]; sessionIds?: string[] },
+ options: SoftDeleteOptions,
+ ): Promise<TopicItem[]> => {
+ const conditions: SQL[] = [];
+ if (parents.agentIds?.length) conditions.push(inArray(topics.agentId, parents.agentIds));
+ if (parents.sessionIds?.length) conditions.push(inArray(topics.sessionId, parents.sessionIds));
+ if (parents.groupIds?.length) conditions.push(inArray(topics.groupId, parents.groupIds));
+ if (conditions.length === 0) return [];
+
+ return this.db
+ .update(topics)
+ .set(trashStamp(options.deletedAt))
+ .where(
+ and(
+ or(...conditions),
+ options.restrictToCreator ? this.mine() : this.ownership(),
+ this.notShareVisitor(),
+ ),
+ )
+ .returning();
+ };
+
+ softDeleteAll = async (options: SoftDeleteOptions): Promise<TopicItem[]> => {
+ return this.db
+ .update(topics)
+ .set(trashStamp(options.deletedAt))
+ .where(and(this.mine(), this.notShareVisitor()))
+ .returning();
+ };
+
+ /** Bring trashed topics back. Only rows currently stamped are touched. */
+ restore = async (ids: string[]): Promise<TopicItem[]> => {
+ if (ids.length === 0) return [];
+ return this.db
+ .update(topics)
+ .set(restoreStamp())
+ .where(and(inArray(topics.id, ids), this.trashScope(), isTrashed(topics.isDeleted)))
+ .returning();
+ };
+
+ /** Trashed rows by id, bypassing the recycle-bin filter (restore / purge internals). */
+ findTrashedByIds = async (ids: string[]): Promise<TopicItem[]> => {
+ if (ids.length === 0) return [];
+ return this.db
+ .select()
+ .from(topics)
+ .where(and(inArray(topics.id, ids), this.trashScope(), isTrashed(topics.isDeleted)));
+ };
+
+ /**
+ * Hard delete for the purge sweep: bypasses the recycle-bin filter so a
+ * trashed row (invisible to `delete`) can actually be removed. FK cascades
+ * take messages, threads and the rest with it.
+ */
+ purge = async (ids: string[]): Promise<string[]> => {
+ if (ids.length === 0) return [];
+ // Only rows still stamped: a restore that commits between the registry
+ // read and this delete must win, not be hard-deleted as a stale purge.
+ const rows = await this.db
+ .delete(topics)
+ .where(and(inArray(topics.id, ids), this.trashScope(), isTrashed(topics.isDeleted)))
+ .returning({ id: topics.id });
+ return rows.map((row) => row.id);
+ };
+
// **************** Update *************** //
update = async (id: string, data: Partial<TopicItem>) => {
diff --git a/packages/database/src/models/topicShare.ts b/packages/database/src/models/topicShare.ts
index 85e226c7413..fc21ba21ec5 100644
--- a/packages/database/src/models/topicShare.ts
+++ b/packages/database/src/models/topicShare.ts
@@ -9,6 +9,7 @@ import {
normalizeInboxAgentMeta,
normalizeInboxAgentTitle,
} from '../utils/inboxAgent';
+import { notTrashed } from '../utils/softDelete';
import { buildWorkspaceWhere } from '../utils/workspace';
export type TopicShareData = NonNullable<
@@ -144,7 +145,12 @@ export class TopicShareModel {
workspaceId: topicShares.workspaceId,
})
.from(topicShares)
- .innerJoin(topics, eq(topicShares.topicId, topics.id))
+ // A share is resolved with no user scope at all (that is the point of a
+ // public link), so it never passes through `buildWorkspaceWhere` and has
+ // to carry the recycle-bin gate itself: a trashed topic keeps its
+ // `topic_shares` row and its messages until purge, and without this an
+ // anonymous visitor could keep reading a deleted conversation.
+ .innerJoin(topics, and(eq(topicShares.topicId, topics.id), notTrashed(topics.isDeleted)))
.leftJoin(agents, eq(topics.agentId, agents.id))
.leftJoin(chatGroups, eq(topics.groupId, chatGroups.id))
.where(eq(topicShares.id, shareId))
diff --git a/packages/database/src/models/trash.ts b/packages/database/src/models/trash.ts
new file mode 100644
index 00000000000..6dfd0dd78c8
--- /dev/null
+++ b/packages/database/src/models/trash.ts
@@ -0,0 +1,393 @@
+import { TRASH_LIST_PAGE_SIZE, TRASH_RETENTION_MS } from '@lobechat/const';
+import type {
+ TrashCountByType,
+ TrashItem,
+ TrashItemMeta,
+ TrashListParams,
+ TrashListResult,
+ TrashResourceType,
+} from '@lobechat/types';
+import { and, asc, count, desc, eq, inArray, isNull, lt, lte, or, sql } from 'drizzle-orm';
+
+import type { NewTrashItemRow, TrashItemRow } from '../schemas';
+import { agents, messages, topics, trashItems } from '../schemas';
+import type { LobeChatDatabase, Transaction } from '../type';
+import { buildWorkspaceWhere } from '../utils/workspace';
+
+/** Rows per multi-row registry insert — well under Postgres' bind-parameter cap. */
+const REGISTER_CHUNK_SIZE = 500;
+
+export interface TrashRegisterEntry {
+ meta?: TrashItemMeta | null;
+ resourceId: string;
+ resourceType: TrashResourceType;
+ title?: string | null;
+}
+
+export interface TrashRegisterParams {
+ /** Rows stamped along with the root; registered under `rootId` and never listed on their own. */
+ children?: TrashRegisterEntry[];
+ deletedAt: Date;
+ /** Defaults to `deletedAt + TRASH_RETENTION_MS`. */
+ expiresAt?: Date;
+ root: TrashRegisterEntry;
+}
+
+/**
+ * Source tables for the "does the resource still exist" checks. Purge relies
+ * on FK cascades for children, so a root's registry row can be orphaned only
+ * when its resource was hard-deleted through a non-trash path — the sweep
+ * uses this map to prune those.
+ */
+const ROOT_TABLES: Record<TrashResourceType, { id: any; isDeleted: any; table: any }> = {
+ agent: { id: agents.id, isDeleted: agents.isDeleted, table: agents },
+ message: { id: messages.id, isDeleted: messages.isDeleted, table: messages },
+ topic: { id: topics.id, isDeleted: topics.isDeleted, table: topics },
+};
+
+const toTrashItem = (row: TrashItemRow): TrashItem => ({
+ deletedAt: row.deletedAt,
+ deletedByUserId: row.deletedByUserId,
+ expiresAt: row.expiresAt,
+ id: row.id,
+ meta: row.meta ?? null,
+ resourceId: row.resourceId,
+ resourceType: row.resourceType,
+ rootId: row.rootId,
+ title: row.title,
+ userId: row.userId,
+ workspaceId: row.workspaceId,
+});
+
+/**
+ * Registry over trashed rows — see `schemas/trash.ts` for the contract.
+ *
+ * Scope: personal mode lists the caller's own roots; workspace mode lists
+ * every root in the workspace (a member tidying their own agent and an owner
+ * tidying a member's both land here — the row records who pressed delete).
+ */
+export class TrashModel {
+ private db: LobeChatDatabase;
+ private userId: string;
+ private workspaceId?: string;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.db = db;
+ this.userId = userId;
+ this.workspaceId = workspaceId;
+ }
+
+ private ownership = () =>
+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, trashItems);
+
+ // ─────────────────────────── writes ───────────────────────────
+
+ /**
+ * Register a root (and its cascaded children) in the bin. Idempotent on the
+ * resource: trashing something already registered updates its stamp instead
+ * of failing the unique index, so a retried request converges.
+ */
+ register = async (params: TrashRegisterParams, trx?: Transaction): Promise<TrashItemRow> => {
+ const [root] = await this.registerMany(
+ {
+ cascades: [{ children: params.children, root: params.root }],
+ deletedAt: params.deletedAt,
+ expiresAt: params.expiresAt,
+ },
+ trx,
+ );
+ return root;
+ };
+
+ /**
+ * Register many roots (each with its cascaded children) sharing one stamp.
+ * Rows are written in chunked multi-row statements, so a bulk "clear topics"
+ * over hundreds of rows is a handful of round trips instead of one per root
+ * inside the caller's transaction. Returns the root rows in input order.
+ */
+ registerMany = async (
+ params: {
+ cascades: Pick<TrashRegisterParams, 'children' | 'root'>[];
+ deletedAt: Date;
+ expiresAt?: Date;
+ },
+ trx?: Transaction,
+ ): Promise<TrashItemRow[]> => {
+ if (params.cascades.length === 0) return [];
+ const run = async (tx: Transaction | LobeChatDatabase) => {
+ const expiresAt =
+ params.expiresAt ?? new Date(params.deletedAt.getTime() + TRASH_RETENTION_MS);
+ const stamp = {
+ deletedAt: params.deletedAt,
+ deletedByUserId: this.userId,
+ expiresAt,
+ userId: this.userId,
+ workspaceId: this.workspaceId ?? null,
+ };
+ const key = (type: string, id: string) => `${type}:${id}`;
+
+ const rootValues: NewTrashItemRow[] = params.cascades.map(({ root }) => ({
+ ...stamp,
+ meta: root.meta ?? null,
+ resourceId: root.resourceId,
+ resourceType: root.resourceType,
+ rootId: null,
+ title: root.title ?? null,
+ }));
+ const rootsByKey = new Map<string, TrashItemRow>();
+ for (let i = 0; i < rootValues.length; i += REGISTER_CHUNK_SIZE) {
+ const rows = await tx
+ .insert(trashItems)
+ .values(rootValues.slice(i, i + REGISTER_CHUNK_SIZE))
+ .onConflictDoUpdate({
+ set: {
+ deletedAt: sql`excluded.deleted_at`,
+ deletedByUserId: sql`excluded.deleted_by_user_id`,
+ expiresAt: sql`excluded.expires_at`,
+ meta: sql`excluded.meta`,
+ rootId: sql`NULL`,
+ title: sql`excluded.title`,
+ },
+ target: [trashItems.resourceType, trashItems.resourceId],
+ })
+ .returning();
+ for (const row of rows) rootsByKey.set(key(row.resourceType, row.resourceId), row);
+ }
+
+ const childValues: NewTrashItemRow[] = params.cascades.flatMap(({ children, root }) => {
+ const rootRow = rootsByKey.get(key(root.resourceType, root.resourceId))!;
+ return (children ?? []).map((child) => ({
+ ...stamp,
+ meta: child.meta ?? null,
+ resourceId: child.resourceId,
+ resourceType: child.resourceType,
+ rootId: rootRow.id,
+ title: child.title ?? null,
+ }));
+ });
+ // A child that already has its own registry row (trashed earlier on
+ // its own) keeps it: it was in the bin before the root and must stay
+ // there after the root is restored. `DO NOTHING` preserves that.
+ for (let i = 0; i < childValues.length; i += REGISTER_CHUNK_SIZE) {
+ await tx
+ .insert(trashItems)
+ .values(childValues.slice(i, i + REGISTER_CHUNK_SIZE))
+ .onConflictDoNothing({ target: [trashItems.resourceType, trashItems.resourceId] });
+ }
+
+ return params.cascades.map(({ root }) =>
+ rootsByKey.get(key(root.resourceType, root.resourceId))!,
+ );
+ };
+
+ return trx ? run(trx) : run(this.db);
+ };
+
+ /** Drop registry rows once their resource is restored or purged. Children cascade via `root_id`. */
+ removeByIds = async (ids: string[], trx?: Transaction) => {
+ if (ids.length === 0) return;
+ const db = trx ?? this.db;
+ await db.delete(trashItems).where(inArray(trashItems.id, ids));
+ };
+
+ removeByResources = async (
+ entries: { resourceId: string; resourceType: TrashResourceType }[],
+ trx?: Transaction,
+ ) => {
+ if (entries.length === 0) return;
+ const db = trx ?? this.db;
+ const byType = new Map<TrashResourceType, string[]>();
+ for (const entry of entries) {
+ const list = byType.get(entry.resourceType) ?? [];
+ list.push(entry.resourceId);
+ byType.set(entry.resourceType, list);
+ }
+ for (const [resourceType, ids] of byType) {
+ await db
+ .delete(trashItems)
+ .where(and(eq(trashItems.resourceType, resourceType), inArray(trashItems.resourceId, ids)));
+ }
+ };
+
+ // ─────────────────────────── reads ───────────────────────────
+
+ /**
+ * Roots in the caller's scope, newest first, keyset-paginated on
+ * `(deleted_at, id)`.
+ */
+ list = async (params: TrashListParams = {}): Promise<TrashListResult> => {
+ const limit = Math.min(Math.max(params.limit ?? TRASH_LIST_PAGE_SIZE, 1), 200);
+ const cursor = decodeCursor(params.cursor);
+
+ const rows = await this.db
+ .select()
+ .from(trashItems)
+ .where(
+ and(
+ this.ownership(),
+ isNull(trashItems.rootId),
+ params.resourceType ? eq(trashItems.resourceType, params.resourceType) : undefined,
+ params.deletedByUserId
+ ? eq(trashItems.deletedByUserId, params.deletedByUserId)
+ : undefined,
+ cursor
+ ? or(
+ lt(trashItems.deletedAt, cursor.deletedAt),
+ and(eq(trashItems.deletedAt, cursor.deletedAt), lt(trashItems.id, cursor.id)),
+ )
+ : undefined,
+ ),
+ )
+ .orderBy(desc(trashItems.deletedAt), desc(trashItems.id))
+ .limit(limit + 1);
+
+ const page = rows.slice(0, limit);
+ const last = page.at(-1);
+ return {
+ items: page.map((row) => toTrashItem(row)),
+ nextCursor: rows.length > limit && last ? encodeCursor(last) : null,
+ };
+ };
+
+ countByType = async (options?: { deletedByUserId?: string }): Promise<TrashCountByType> => {
+ const rows = await this.db
+ .select({ resourceType: trashItems.resourceType, total: count() })
+ .from(trashItems)
+ .where(
+ and(
+ this.ownership(),
+ isNull(trashItems.rootId),
+ options?.deletedByUserId
+ ? eq(trashItems.deletedByUserId, options.deletedByUserId)
+ : undefined,
+ ),
+ )
+ .groupBy(trashItems.resourceType);
+
+ return Object.fromEntries(rows.map((row) => [row.resourceType, row.total]));
+ };
+
+ findById = async (id: string): Promise<TrashItemRow | undefined> => {
+ return this.db.query.trashItems.findFirst({
+ where: and(eq(trashItems.id, id), this.ownership()),
+ });
+ };
+
+ findByIds = async (ids: string[]): Promise<TrashItemRow[]> => {
+ if (ids.length === 0) return [];
+ return this.db
+ .select()
+ .from(trashItems)
+ .where(and(inArray(trashItems.id, ids), this.ownership()));
+ };
+
+ findByResource = async (
+ resourceType: TrashResourceType,
+ resourceId: string,
+ ): Promise<TrashItemRow | undefined> => {
+ return this.db.query.trashItems.findFirst({
+ where: and(
+ eq(trashItems.resourceType, resourceType),
+ eq(trashItems.resourceId, resourceId),
+ this.ownership(),
+ ),
+ });
+ };
+
+ /** Registry rows cascaded under a root (any type). */
+ findChildren = async (rootId: string, trx?: Transaction): Promise<TrashItemRow[]> => {
+ const db = trx ?? this.db;
+ return db.select().from(trashItems).where(eq(trashItems.rootId, rootId));
+ };
+
+ /** Every root in scope — used by "empty trash". */
+ listAllRootIds = async (options?: {
+ /** Restrict to roots this user trashed — a workspace non-owner may only empty their own. */
+ deletedByUserId?: string;
+ /** Cap the ids returned — empty-trash works one bounded batch per request. */
+ limit?: number;
+ resourceType?: TrashResourceType;
+ }): Promise<string[]> => {
+ const query = this.db
+ .select({ id: trashItems.id })
+ .from(trashItems)
+ .where(
+ and(
+ this.ownership(),
+ isNull(trashItems.rootId),
+ options?.resourceType ? eq(trashItems.resourceType, options.resourceType) : undefined,
+ options?.deletedByUserId
+ ? eq(trashItems.deletedByUserId, options.deletedByUserId)
+ : undefined,
+ ),
+ )
+ .orderBy(asc(trashItems.deletedAt), asc(trashItems.id));
+ const rows = await (options?.limit ? query.limit(options.limit) : query);
+ return rows.map((row) => row.id);
+ };
+
+ // ─────────────────────────── sweep (global, not user-scoped) ───────────────────────────
+
+ /**
+ * Expired roots across every user, oldest first. The purge sweep instantiates
+ * a per-owner service for each so hard deletes run under the right scope.
+ */
+ static listExpiredRoots = async (
+ db: LobeChatDatabase,
+ params: { limit: number; now?: Date },
+ ): Promise<TrashItemRow[]> => {
+ const now = params.now ?? new Date();
+ return db
+ .select()
+ .from(trashItems)
+ .where(and(isNull(trashItems.rootId), lte(trashItems.expiresAt, now)))
+ .orderBy(asc(trashItems.expiresAt), asc(trashItems.id))
+ .limit(params.limit);
+ };
+
+ /**
+ * Drop root registry rows whose resource no longer exists (hard-deleted
+ * through a non-trash path — a user purge, an FK cascade from a parent that
+ * was itself purged, …) or is no longer stamped (restored through a
+ * non-trash path). Returns how many were pruned.
+ */
+ static pruneOrphans = async (db: LobeChatDatabase): Promise<number> => {
+ let pruned = 0;
+ for (const [resourceType, source] of Object.entries(ROOT_TABLES) as [
+ TrashResourceType,
+ (typeof ROOT_TABLES)[TrashResourceType],
+ ][]) {
+ const result = await db
+ .delete(trashItems)
+ .where(
+ and(
+ eq(trashItems.resourceType, resourceType),
+ isNull(trashItems.rootId),
+ sql`NOT EXISTS (SELECT 1 FROM ${source.table} WHERE ${source.id} = ${trashItems.resourceId} AND ${source.isDeleted} = true)`,
+ ),
+ )
+ .returning({ id: trashItems.id });
+ pruned += result.length;
+ }
+ return pruned;
+ };
+}
+
+// keyset cursor: base64url of `<deletedAt ms>:<id>`
+const encodeCursor = (row: Pick<TrashItemRow, 'deletedAt' | 'id'>) =>
+ Buffer.from(`${row.deletedAt.getTime()}:${row.id}`).toString('base64url');
+
+const decodeCursor = (cursor?: string | null): { deletedAt: Date; id: string } | null => {
+ if (!cursor) return null;
+ try {
+ const raw = Buffer.from(cursor, 'base64url').toString('utf8');
+ const idx = raw.indexOf(':');
+ if (idx < 0) return null;
+ const ms = Number(raw.slice(0, idx));
+ const id = raw.slice(idx + 1);
+ if (!Number.isFinite(ms) || !id) return null;
+ return { deletedAt: new Date(ms), id };
+ } catch {
+ return null;
+ }
+};
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index e675925cf29..0a1a17e2a7f 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -1430,6 +1430,7 @@ export default {
'storage, files, import, export, backup, reset, clear data, clear storage, knowledge base, account deletion, delete account',
'settingsSearch.tabKeywords.systemTools':
'system tools, built-in tools, system, node, python, cli, environment',
+ 'settingsSearch.tabKeywords.trash': 'trash, recycle bin, deleted, restore, undelete, recover',
'settingsSearch.tabKeywords.usage': 'usage, consumption, quota, spend, statistics',
'settingSystem.oauth.info.desc': 'Logged in',
'settingSystem.oauth.info.title': 'Account Information',
@@ -1797,6 +1798,7 @@ When I am ___, I need ___
'tab.skillIntegration': 'Integration',
'tab.stats': 'Analytics',
'tab.storage': 'Storage',
+ 'tab.trash': 'Trash',
'tab.sync': 'Cloud Sync',
'tab.systemTools': 'System Tools',
'tab.tools': 'Tools',
@@ -1807,6 +1809,41 @@ When I am ___, I need ___
'tools.builtins.lobe-attachments.description':
'Page through attached files that were too long to include in full',
'tools.builtins.lobe-attachments.title': 'Attachments',
+ 'trash.actions.empty': 'Empty trash',
+ 'trash.actions.emptyType': 'Empty {{type}}',
+ 'trash.actions.loadMore': 'Load more',
+ 'trash.actions.purge': 'Delete forever',
+ 'trash.actions.restore': 'Restore',
+ 'trash.columns.deletedAt': 'Deleted',
+ 'trash.columns.expiresIn': 'Auto-deletes',
+ 'trash.columns.name': 'Name',
+ 'trash.columns.type': 'Type',
+ 'trash.desc':
+ 'Deleted items stay here for {{days}} days and can be restored. After that they are removed permanently.',
+ 'trash.empty.desc':
+ 'Conversations, agents and messages you delete land here for {{days}} days before they are removed for good.',
+ 'trash.empty.title': 'Trash is empty',
+ 'trash.emptyConfirm.content': 'Permanently delete {{count}} item(s)? This cannot be undone.',
+ 'trash.emptyConfirm.title': 'Empty trash',
+ 'trash.emptyType.desc': 'No deleted {{type}} right now.',
+ 'trash.expiresIn.days': 'in {{count}} days',
+ 'trash.expiresIn.soon': 'within a day',
+ 'trash.filter.all': 'All',
+ 'trash.loadFailed.desc': 'Check your connection and try again.',
+ 'trash.loadFailed.title': 'Could not load the trash',
+ 'trash.meta.children': '{{count}} items inside',
+ 'trash.purgeConfirm.content': 'Permanently delete "{{title}}"? This cannot be undone.',
+ 'trash.purgeConfirm.title': 'Delete forever',
+ 'trash.restore.failed.notFound': 'This item no longer exists.',
+ 'trash.restore.failed.parentTrashed':
+ 'Restore the container it belongs to first — that item is also in the trash.',
+ 'trash.restore.success': 'Restored',
+ 'trash.purge.success': 'Deleted permanently',
+ 'trash.title': 'Trash',
+ 'trash.type.agent': 'Agent',
+ 'trash.type.message': 'Message',
+ 'trash.type.topic': 'Topic',
+ 'trash.untitled': 'Untitled',
'workspace.create.descPlaceholder': 'Describe what this workspace is for (optional)',
'workspace.create.namePlaceholder': 'e.g. Acme Team',
'workspace.create.submit': 'Create workspace',
diff --git a/packages/locales/src/default/topic.ts b/packages/locales/src/default/topic.ts
index 807ee920296..8fb2238bce5 100644
--- a/packages/locales/src/default/topic.ts
+++ b/packages/locales/src/default/topic.ts
@@ -11,24 +11,26 @@ export default {
'actions.archiveMergedPullRequestsSuccess_other': 'Archived {{count}} topics with merged PRs.',
'actions.confirmArchiveMergedPullRequestsWorkspace':
'Archive all Workspace topics with merged PRs, including topics created by other members?',
- 'actions.confirmRemoveAll': 'You are about to delete all topics. This action cannot be undone.',
+ 'actions.confirmRemoveAll':
+ 'You are about to delete all topics. They will be moved to the trash and can be restored within 30 days.',
'actions.confirmRemoveAllOwn':
- 'You are about to delete all topics you created in the current list. Topics created by other Workspace members will remain. This action cannot be undone.',
+ 'You are about to delete all topics you created in the current list. Topics created by other Workspace members will remain. Deleted topics move to the trash and can be restored within 30 days.',
'actions.confirmRemoveAllWorkspace':
- 'You are about to delete all topics in the current Workspace list, including topics created by other members. This action cannot be undone.',
+ 'You are about to delete all topics in the current Workspace list, including topics created by other members. They move to the trash and can be restored within 30 days.',
'actions.confirmRemoveAllWorkspaceAcknowledge':
- "I understand that this permanently deletes other members' topics.",
- 'actions.confirmRemoveTopic': 'You are about to delete this topic. This action cannot be undone.',
+ "I understand that this moves other members' topics to the trash.",
+ 'actions.confirmRemoveTopic':
+ 'You are about to delete this topic. It will be moved to the trash and can be restored within 30 days.',
'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.',
+ 'You are about to delete unstarred topics. They will be moved to the trash and can be restored within 30 days.',
'actions.confirmRemoveUnstarredOwn':
- 'You are about to delete unstarred topics you created. Topics created by other Workspace members will remain. This action cannot be undone.',
+ 'You are about to delete unstarred topics you created. Topics created by other Workspace members will remain. Deleted topics move to the trash and can be restored within 30 days.',
'actions.confirmRemoveUnstarredWorkspace':
- 'You are about to delete all unstarred topics in the current Workspace list, including topics created by other members. Starred topics will remain. This action cannot be undone.',
+ 'You are about to delete all unstarred topics in the current Workspace list, including topics created by other members. Starred topics will remain. Deleted topics move to the trash and can be restored within 30 days.',
'actions.confirmRemoveUnstarredWorkspaceAcknowledge':
- "I understand that this permanently deletes other members' unstarred topics.",
+ "I understand that this moves other members' unstarred topics to the trash.",
'actions.copyLink': 'Copy Link',
'actions.copyLinkSuccess': 'Link copied',
'actions.copySessionId': 'Copy Topic ID',
@@ -198,7 +200,7 @@ export default {
'management.bulk.cancel': 'Cancel',
'management.bulk.delete': 'Delete',
'management.bulk.deleteConfirm':
- 'You are about to delete {{count}} topics. This action cannot be undone.',
+ 'You are about to delete {{count}} topics. They will be moved to the trash and can be restored within 30 days.',
'management.bulk.deleteTitle': 'Delete topics?',
'management.bulk.favorite': 'Favorite',
'management.bulk.move': 'Move to agent',
diff --git a/packages/types/src/trash.ts b/packages/types/src/trash.ts
index fe76018b2d1..700545e545b 100644
--- a/packages/types/src/trash.ts
+++ b/packages/types/src/trash.ts
@@ -67,6 +67,12 @@ export interface TrashItem {
export interface TrashListParams {
cursor?: string | null;
+ /**
+ * Only roots this user trashed. Set server-side for workspace non-owners, so
+ * a member never sees titles of teammates' resources (a message root's title
+ * is a content excerpt).
+ */
+ deletedByUserId?: string;
limit?: number;
resourceType?: TrashResourceType;
}
diff --git a/src/features/Settings/features/SettingsContent.tsx b/src/features/Settings/features/SettingsContent.tsx
index fc94a3a7151..bec4f9f0f64 100644
--- a/src/features/Settings/features/SettingsContent.tsx
+++ b/src/features/Settings/features/SettingsContent.tsx
@@ -40,6 +40,7 @@ const COMPACT_HEADER_TABS = [
SettingsTabs.ServiceModel,
SettingsTabs.Stats,
SettingsTabs.Storage,
+ SettingsTabs.Trash,
] as const;
interface SettingsContentProps {
@@ -71,6 +72,7 @@ const SettingsContent = ({ mobile, activeTab }: SettingsContentProps) => {
[SettingsTabs.ServiceModel]: t('setting:tab.serviceModel'),
[SettingsTabs.Stats]: t('auth:tab.stats'),
[SettingsTabs.Storage]: t('setting:tab.storage'),
+ [SettingsTabs.Trash]: t('setting:tab.trash'),
};
useSettingsAnchorScroll();
diff --git a/src/features/Settings/features/componentMap.desktop.ts b/src/features/Settings/features/componentMap.desktop.ts
index 73450908580..2f7bc0192f8 100644
--- a/src/features/Settings/features/componentMap.desktop.ts
+++ b/src/features/Settings/features/componentMap.desktop.ts
@@ -30,6 +30,7 @@ import Stats from '../stats';
import Storage from '../storage';
import SystemTools from '../system-tools';
import Tools from '../tools';
+import Trash from '../trash';
export const componentMap = {
[SettingsTabs.Advanced]: Advanced,
@@ -46,6 +47,7 @@ export const componentMap = {
[SettingsTabs.Proxy]: Proxy,
[SettingsTabs.SystemTools]: SystemTools,
[SettingsTabs.Storage]: Storage,
+ [SettingsTabs.Trash]: Trash,
[SettingsTabs.Devices]: Devices,
[SettingsTabs.Labels]: Labels,
// Profile related tabs
diff --git a/src/features/Settings/features/componentMap.ts b/src/features/Settings/features/componentMap.ts
index 1e7987cc6db..7c1c88406c2 100644
--- a/src/features/Settings/features/componentMap.ts
+++ b/src/features/Settings/features/componentMap.ts
@@ -53,6 +53,9 @@ export const componentMap = {
[SettingsTabs.Storage]: dynamic(() => import('../storage'), {
loading: loading('Settings > Storage'),
}),
+ [SettingsTabs.Trash]: dynamic(() => import('../trash'), {
+ loading: loading('Settings > Trash'),
+ }),
[SettingsTabs.Devices]: dynamic(() => import('../devices'), {
loading: loading('Settings > Devices'),
}),
diff --git a/src/features/Settings/hooks/useCategory.tsx b/src/features/Settings/hooks/useCategory.tsx
index 75174ed8064..0b3a43f30c0 100644
--- a/src/features/Settings/hooks/useCategory.tsx
+++ b/src/features/Settings/hooks/useCategory.tsx
@@ -28,6 +28,7 @@ import {
Sparkles,
TagIcon,
TerminalSquare,
+ Trash2,
Wrench,
} from 'lucide-react';
import { useMemo } from 'react';
@@ -256,6 +257,11 @@ export const useCategory = () => {
key: SettingsTabs.Storage,
label: t('tab.storage'),
},
+ {
+ icon: Trash2,
+ key: SettingsTabs.Trash,
+ label: t('tab.trash'),
+ },
!hideDocs && {
icon: Info,
key: SettingsTabs.About,
diff --git a/src/features/Settings/trash/features/TrashList.tsx b/src/features/Settings/trash/features/TrashList.tsx
new file mode 100644
index 00000000000..52ba6b63f47
--- /dev/null
+++ b/src/features/Settings/trash/features/TrashList.tsx
@@ -0,0 +1,315 @@
+'use client';
+
+import { TRASH_RETENTION_DAYS } from '@lobechat/const';
+import type { TrashItem, TrashResourceType } from '@lobechat/types';
+import { Center, Empty, Flexbox, Icon } from '@lobehub/ui';
+import { Avatar, Button, confirmModal, Segmented, Tag, Text, toast } from '@lobehub/ui/base-ui';
+import { createStaticStyles } from 'antd-style';
+import dayjs from 'dayjs';
+import relativeTime from 'dayjs/plugin/relativeTime';
+import { Trash2Icon } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import LiteTable, { type LiteTableColumn } from '@/components/LiteTable';
+import { useIsMobile } from '@/hooks/useIsMobile';
+import { trashSelectors, useTrashStore } from '@/store/trash';
+
+import { TRASH_TYPE_ICON, TRASH_TYPE_ORDER } from './typeMeta';
+
+dayjs.extend(relativeTime);
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ container: css`
+ overflow: hidden;
+ padding-block: 16px;
+ border-radius: ${cssVar.borderRadius};
+ background: ${cssVar.colorBgContainer};
+ `,
+ header: css`
+ display: flex;
+ flex-wrap: wrap;
+ gap: 12px;
+ align-items: center;
+ justify-content: space-between;
+
+ padding-block-end: 16px;
+ padding-inline: 24px;
+ `,
+ muted: css`
+ color: ${cssVar.colorTextSecondary};
+ `,
+ title: css`
+ overflow: hidden;
+ font-weight: 500;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+}));
+
+const TrashList = () => {
+ const { t } = useTranslation('setting');
+ const { t: tc } = useTranslation('common');
+ const mobile = useIsMobile();
+
+ const [
+ items,
+ nextCursor,
+ activeType,
+ countByType,
+ isLoadingMore,
+ loadingIds,
+ setActiveType,
+ restore,
+ purge,
+ emptyTrash,
+ loadMore,
+ useFetchTrash,
+ useFetchTrashCount,
+ ] = useTrashStore((s) => [
+ s.items,
+ s.nextCursor,
+ s.activeType,
+ s.countByType,
+ s.isLoadingMore,
+ s.loadingIds,
+ s.setActiveType,
+ s.restore,
+ s.purge,
+ s.emptyTrash,
+ s.loadMore,
+ s.useFetchTrash,
+ s.useFetchTrashCount,
+ ]);
+ const isEmpty = useTrashStore(trashSelectors.isEmpty);
+ const total = useTrashStore(trashSelectors.totalCount);
+
+ const { error, isLoading, isValidating, mutate: retry } = useFetchTrash(true, activeType);
+ useFetchTrashCount(true);
+
+ const typeLabel = (type: TrashResourceType) => t(`trash.type.${type}` as const);
+
+ // A rejected call (network / server) must not end in a silent spinner stop:
+ // the user has to know whether the row was restored or deleted.
+ const reportFailure = () => toast.error(tc('operationFailed'));
+
+ const handleRestore = async (item: TrashItem) => {
+ let outcome: Awaited<ReturnType<typeof restore>>;
+ try {
+ outcome = await restore([item.id]);
+ } catch {
+ reportFailure();
+ return;
+ }
+ const failure = outcome.failed[0];
+ if (failure) {
+ toast.error(t(`trash.restore.failed.${failure.code}`));
+ return;
+ }
+ toast.success(t('trash.restore.success'));
+ };
+
+ const handlePurge = (item: TrashItem) => {
+ confirmModal({
+ cancelText: tc('cancel'),
+ content: t('trash.purgeConfirm.content', { title: item.title || t('trash.untitled') }),
+ okButtonProps: { danger: true },
+ okText: t('trash.actions.purge'),
+ onOk: async () => {
+ try {
+ await purge([item.id]);
+ } catch {
+ reportFailure();
+ return;
+ }
+ toast.success(t('trash.purge.success'));
+ },
+ title: t('trash.purgeConfirm.title'),
+ });
+ };
+
+ const handleEmpty = () => {
+ const count = activeType ? (countByType[activeType] ?? items.length) : total;
+ confirmModal({
+ cancelText: tc('cancel'),
+ content: t('trash.emptyConfirm.content', { count }),
+ okButtonProps: { danger: true },
+ okText: activeType
+ ? t('trash.actions.emptyType', { type: typeLabel(activeType) })
+ : t('trash.actions.empty'),
+ onOk: async () => {
+ try {
+ await emptyTrash();
+ } catch {
+ reportFailure();
+ return;
+ }
+ toast.success(t('trash.purge.success'));
+ },
+ title: t('trash.emptyConfirm.title'),
+ });
+ };
+
+ const expiresLabel = (expiresAt: Date) => {
+ const days = dayjs(expiresAt).diff(dayjs(), 'day');
+ return days < 1 ? t('trash.expiresIn.soon') : t('trash.expiresIn.days', { count: days });
+ };
+
+ const columns: LiteTableColumn<TrashItem>[] = [
+ {
+ key: 'name',
+ listSlot: 'title',
+ render: (item) => {
+ const TypeIcon = TRASH_TYPE_ICON[item.resourceType];
+ const avatar = item.meta?.avatar;
+ return (
+ <Flexbox horizontal align={'center'} gap={10} style={{ minWidth: 0 }}>
+ {avatar ? (
+ <Avatar
+ avatar={avatar}
+ background={item.meta?.backgroundColor ?? undefined}
+ size={28}
+ />
+ ) : (
+ <Center
+ height={28}
+ style={{ borderRadius: 6, flex: 'none', opacity: 0.7 }}
+ width={28}
+ >
+ <Icon icon={TypeIcon} size={18} />
+ </Center>
+ )}
+ <Flexbox style={{ minWidth: 0 }}>
+ <span className={styles.title}>{item.title || t('trash.untitled')}</span>
+ {!!item.meta?.childCount && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('trash.meta.children', { count: item.meta.childCount })}
+ </Text>
+ )}
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+ title: t('trash.columns.name'),
+ },
+ {
+ key: 'type',
+ render: (item) => <Tag>{typeLabel(item.resourceType)}</Tag>,
+ title: t('trash.columns.type'),
+ width: 130,
+ },
+ {
+ key: 'deletedAt',
+ render: (item) => (
+ <span className={styles.muted} title={dayjs(item.deletedAt).format('YYYY-MM-DD HH:mm')}>
+ {dayjs(item.deletedAt).fromNow()}
+ </span>
+ ),
+ title: t('trash.columns.deletedAt'),
+ width: 150,
+ },
+ {
+ key: 'expiresAt',
+ render: (item) => <span className={styles.muted}>{expiresLabel(item.expiresAt)}</span>,
+ title: t('trash.columns.expiresIn'),
+ width: 140,
+ },
+ {
+ key: 'actions',
+ listSlot: 'actions',
+ render: (item) => {
+ const busy = loadingIds.includes(item.id);
+ return (
+ <Flexbox horizontal gap={4} onClick={(e) => e.stopPropagation()}>
+ <Button loading={busy} size={'small'} onClick={() => handleRestore(item)}>
+ {t('trash.actions.restore')}
+ </Button>
+ <Button
+ danger
+ disabled={busy}
+ size={'small'}
+ type={'text'}
+ onClick={() => handlePurge(item)}
+ >
+ {t('trash.actions.purge')}
+ </Button>
+ </Flexbox>
+ );
+ },
+ title: '',
+ width: 200,
+ },
+ ];
+
+ const typeOptions = [
+ { label: `${t('trash.filter.all')}${total ? ` · ${total}` : ''}`, value: 'all' },
+ ...TRASH_TYPE_ORDER.filter((type) => countByType[type]).map((type) => ({
+ label: `${typeLabel(type)} · ${countByType[type]}`,
+ value: type,
+ })),
+ ];
+
+ return (
+ <div className={styles.container}>
+ <div className={styles.header}>
+ <Segmented
+ options={typeOptions}
+ size={'small'}
+ value={activeType ?? 'all'}
+ onChange={(value) =>
+ setActiveType(value === 'all' ? undefined : (value as TrashResourceType))
+ }
+ />
+ <Button
+ danger
+ disabled={items.length === 0}
+ icon={Trash2Icon}
+ size={mobile ? 'small' : undefined}
+ onClick={handleEmpty}
+ >
+ {activeType
+ ? t('trash.actions.emptyType', { type: typeLabel(activeType) })
+ : t('trash.actions.empty')}
+ </Button>
+ </div>
+ <LiteTable
+ columns={columns}
+ dataSource={items}
+ loading={isLoading && !isEmpty && items.length === 0}
+ rowKey={(item) => item.id}
+ emptyText={
+ <Center height={240} width={'100%'}>
+ {error ? (
+ <Empty
+ description={t('trash.loadFailed.desc')}
+ title={t('trash.loadFailed.title')}
+ action={
+ <Button loading={isValidating} size={'small'} onClick={() => retry()}>
+ {tc('retry')}
+ </Button>
+ }
+ />
+ ) : (
+ <Empty
+ title={activeType ? undefined : t('trash.empty.title')}
+ description={
+ activeType
+ ? t('trash.emptyType.desc', { type: typeLabel(activeType) })
+ : t('trash.empty.desc', { days: TRASH_RETENTION_DAYS })
+ }
+ />
+ )}
+ </Center>
+ }
+ />
+ {nextCursor && (
+ <Center style={{ paddingBlockStart: 12 }}>
+ <Button loading={isLoadingMore} size={'small'} type={'text'} onClick={() => loadMore()}>
+ {t('trash.actions.loadMore')}
+ </Button>
+ </Center>
+ )}
+ </div>
+ );
+};
+
+export default TrashList;
diff --git a/src/features/Settings/trash/features/typeMeta.ts b/src/features/Settings/trash/features/typeMeta.ts
new file mode 100644
index 00000000000..5e3b27bff7d
--- /dev/null
+++ b/src/features/Settings/trash/features/typeMeta.ts
@@ -0,0 +1,12 @@
+import type { TrashResourceType } from '@lobechat/types';
+import { BotIcon, HashIcon, MessageSquareIcon } from 'lucide-react';
+
+/** Icon per recycle-bin resource kind — mirrors the sidebar / recents glyphs. */
+export const TRASH_TYPE_ICON: Record<TrashResourceType, typeof HashIcon> = {
+ agent: BotIcon,
+ message: MessageSquareIcon,
+ topic: HashIcon,
+};
+
+/** Order the type filter shows kinds in — most-deleted first. */
+export const TRASH_TYPE_ORDER: TrashResourceType[] = ['topic', 'agent', 'message'];
diff --git a/src/features/Settings/trash/index.tsx b/src/features/Settings/trash/index.tsx
new file mode 100644
index 00000000000..64eba465c01
--- /dev/null
+++ b/src/features/Settings/trash/index.tsx
@@ -0,0 +1,32 @@
+'use client';
+
+import { TRASH_RETENTION_DAYS } from '@lobechat/const';
+import { Flexbox } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
+import { useTranslation } from 'react-i18next';
+
+import SettingHeader from '@/features/Settings/features/SettingHeader';
+
+import TrashList from './features/TrashList';
+
+interface PageProps {
+ showSettingHeader?: boolean;
+}
+
+const Page = ({ showSettingHeader = true }: PageProps) => {
+ const { t } = useTranslation('setting');
+
+ return (
+ <>
+ {showSettingHeader && <SettingHeader title={t('tab.trash')} />}
+ <Flexbox gap={12}>
+ <Text type={'secondary'}>{t('trash.desc', { days: TRASH_RETENTION_DAYS })}</Text>
+ <TrashList />
+ </Flexbox>
+ </>
+ );
+};
+
+Page.displayName = 'TrashSettings';
+
+export default Page;
diff --git a/src/features/SettingsSearch/items.ts b/src/features/SettingsSearch/items.ts
index 581cb2f843f..d5143c88734 100644
--- a/src/features/SettingsSearch/items.ts
+++ b/src/features/SettingsSearch/items.ts
@@ -146,6 +146,7 @@ export const TAB_SEARCH_EN_KEYWORDS: Partial<Record<SettingsTabs, string[]>> = {
'account deletion',
'delete account',
],
+ [SettingsTabs.Trash]: ['trash', 'recycle bin', 'deleted', 'restore', 'undelete', 'recover'],
[SettingsTabs.SystemTools]: [
'system tools',
'built-in tools',
@@ -193,6 +194,7 @@ export const TAB_SEARCH_KEYWORDS_KEYS: Partial<Record<SettingsTabs, string>> = {
[SettingsTabs.Stats]: 'settingsSearch.tabKeywords.stats',
[SettingsTabs.Storage]: 'settingsSearch.tabKeywords.storage',
[SettingsTabs.SystemTools]: 'settingsSearch.tabKeywords.systemTools',
+ [SettingsTabs.Trash]: 'settingsSearch.tabKeywords.trash',
[SettingsTabs.Usage]: 'settingsSearch.tabKeywords.usage',
};
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index f07deab935d..eeb2e6cadf8 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -838,6 +838,11 @@ export const knowledgeBaseKeys = {
};
// ---- device -------------------------------------------------------------
+export const trashKeys = {
+ countByType: def('trash:countByType', () => ['trash:countByType']),
+ list: def('trash:list', (resourceType?: string | null) => ['trash:list', resourceType ?? 'all']),
+};
+
export const deviceKeys = {
appUpdateState: def('device:appUpdateState', (workspaceId: string | null, deviceId: string) => [
'device:appUpdateState',
@@ -1591,6 +1596,7 @@ export const swrKeys = {
documentComment: documentCommentKeys,
documentLike: documentLikeKeys,
topicAction: topicActionKeys,
+ trash: trashKeys,
user: userKeys,
userMemory: userMemoryKeys,
verify: verifyKeys,
diff --git a/src/services/trash.ts b/src/services/trash.ts
new file mode 100644
index 00000000000..889361fc203
--- /dev/null
+++ b/src/services/trash.ts
@@ -0,0 +1,31 @@
+import type { TrashListParams, TrashResourceType } from '@lobechat/types';
+
+import { lambdaClient } from '@/libs/trpc/client';
+
+/**
+ * Single chokepoint for the `trash` (recycle bin) TRPC router. Components,
+ * hooks and stores call this instead of reaching into `lambdaClient.trash.*`.
+ */
+class TrashService {
+ list(params?: TrashListParams) {
+ return lambdaClient.trash.list.query(params ?? undefined);
+ }
+
+ countByType() {
+ return lambdaClient.trash.countByType.query();
+ }
+
+ restore(ids: string[]) {
+ return lambdaClient.trash.restore.mutate({ ids });
+ }
+
+ purge(ids: string[]) {
+ return lambdaClient.trash.purge.mutate({ ids });
+ }
+
+ emptyTrash(resourceType?: TrashResourceType) {
+ return lambdaClient.trash.emptyTrash.mutate(resourceType ? { resourceType } : undefined);
+ }
+}
+
+export const trashService = new TrashService();
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index 06d6bde0d3d..4f9da1fadef 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -98,6 +98,7 @@ export enum SettingsTabs {
Storage = 'storage',
SystemTools = 'system-tools',
Tools = 'tools',
+ Trash = 'trash',
/** @deprecated Use ServiceModel instead */
TTS = 'tts',
Usage = 'usage',
diff --git a/src/store/trash/action.test.ts b/src/store/trash/action.test.ts
new file mode 100644
index 00000000000..34f73defbc3
--- /dev/null
+++ b/src/store/trash/action.test.ts
@@ -0,0 +1,232 @@
+import type { TrashItem } from '@lobechat/types';
+import { renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { mutate, useClientDataSWR } from '@/libs/swr';
+import { trashService } from '@/services/trash';
+
+import { trashSelectors } from './selectors';
+import { useTrashStore } from './store';
+
+vi.mock('@/libs/swr', () => ({
+ mutate: vi.fn(),
+ useClientDataSWR: vi.fn(),
+}));
+
+const scopeMock = vi.hoisted(() => ({ current: 'u1:personal' }));
+vi.mock('@/libs/swr/useCacheScope', () => ({
+ getCacheScope: () => scopeMock.current,
+ useCacheScope: () => scopeMock.current,
+}));
+
+const buildItem = (overrides: Partial<TrashItem> = {}): TrashItem => ({
+ deletedAt: new Date('2026-08-01T00:00:00Z'),
+ deletedByUserId: 'u1',
+ expiresAt: new Date('2026-08-31T00:00:00Z'),
+ id: 'trash_1',
+ meta: null,
+ resourceId: 'tpc_1',
+ resourceType: 'topic',
+ rootId: null,
+ title: 'A topic',
+ userId: 'u1',
+ workspaceId: null,
+ ...overrides,
+});
+
+describe('TrashAction', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(mutate).mockResolvedValue(undefined as never);
+ useTrashStore.setState({
+ activeType: undefined,
+ countByType: { agent: 1, topic: 2 },
+ isTrashInit: true,
+ items: [buildItem(), buildItem({ id: 'trash_2', resourceId: 'tpc_2' })],
+ isLoadingMore: false,
+ loadingIds: [],
+ nextCursor: null,
+ scope: 'u1:personal',
+ });
+ scopeMock.current = 'u1:personal';
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ describe('restore', () => {
+ it('drops restored rows, keeps blocked ones, and revalidates the lists a restore touches', async () => {
+ vi.spyOn(trashService, 'restore').mockResolvedValue({
+ failed: [{ code: 'parentTrashed', id: 'trash_2' }],
+ restored: [buildItem()],
+ });
+
+ const outcome = await useTrashStore.getState().restore(['trash_1', 'trash_2']);
+
+ expect(outcome.failed).toEqual([{ code: 'parentTrashed', id: 'trash_2' }]);
+ expect(useTrashStore.getState().items.map((i) => i.id)).toEqual(['trash_2']);
+ expect(useTrashStore.getState().loadingIds).toEqual([]);
+ // recycle-bin list + counts, plus a filter-based sweep of the affected namespaces
+ expect(mutate).toHaveBeenCalledWith(['trash:list', 'all']);
+ expect(mutate).toHaveBeenCalledWith(['trash:countByType']);
+ const filterCall = vi.mocked(mutate).mock.calls.find(([key]) => typeof key === 'function');
+ expect(filterCall).toBeTruthy();
+ const filter = filterCall![0] as (key: unknown) => boolean;
+ expect(filter(['topic:list', 'x', {}])).toBe(true);
+ expect(filter(['agent:list', true])).toBe(true);
+ expect(filter(['trash:list', 'all'])).toBe(false);
+ expect(filter('not-an-array')).toBe(false);
+ });
+
+ it('also drops rows the server reported as already gone', async () => {
+ vi.spyOn(trashService, 'restore').mockResolvedValue({
+ failed: [{ code: 'notFound', id: 'trash_1' }],
+ restored: [],
+ });
+ await useTrashStore.getState().restore(['trash_1']);
+ expect(useTrashStore.getState().items.map((i) => i.id)).toEqual(['trash_2']);
+ // nothing came back — no cross-store revalidation
+ expect(vi.mocked(mutate).mock.calls.some(([key]) => typeof key === 'function')).toBe(false);
+ });
+
+ it('marks rows as loading while the call is in flight', async () => {
+ let resolve!: () => void;
+ vi.spyOn(trashService, 'restore').mockReturnValue(
+ new Promise((r) => {
+ resolve = () => r({ failed: [], restored: [] });
+ }),
+ );
+ const pending = useTrashStore.getState().restore(['trash_1']);
+ expect(trashSelectors.isLoading('trash_1')(useTrashStore.getState())).toBe(true);
+ resolve();
+ await pending;
+ expect(trashSelectors.isLoading('trash_1')(useTrashStore.getState())).toBe(false);
+ });
+ });
+
+ describe('purge / emptyTrash', () => {
+ it('purge removes the rows locally and refreshes the bin', async () => {
+ vi.spyOn(trashService, 'purge').mockResolvedValue({ purged: 1 });
+ await useTrashStore.getState().purge(['trash_1']);
+ expect(trashService.purge).toHaveBeenCalledWith(['trash_1']);
+ expect(useTrashStore.getState().items.map((i) => i.id)).toEqual(['trash_2']);
+ });
+
+ it('emptyTrash honours the active type filter and clears the list', async () => {
+ vi.spyOn(trashService, 'emptyTrash').mockResolvedValue({ hasMore: false, purged: 2 });
+ useTrashStore.setState({ activeType: 'topic' });
+ await useTrashStore.getState().emptyTrash();
+ expect(trashService.emptyTrash).toHaveBeenCalledWith('topic');
+ expect(useTrashStore.getState().items).toEqual([]);
+ expect(mutate).toHaveBeenCalledWith(['trash:list', 'topic']);
+ });
+
+ it('emptyTrash keeps calling while the server reports more batches', async () => {
+ vi.spyOn(trashService, 'emptyTrash')
+ .mockResolvedValueOnce({ hasMore: true, purged: 50 })
+ .mockResolvedValueOnce({ hasMore: true, purged: 50 })
+ .mockResolvedValueOnce({ hasMore: false, purged: 7 });
+ await useTrashStore.getState().emptyTrash();
+ expect(trashService.emptyTrash).toHaveBeenCalledTimes(3);
+ expect(useTrashStore.getState().items).toEqual([]);
+ });
+ });
+
+ describe('paging / filter', () => {
+ it('setActiveType resets the list so the new filter starts from a fresh first page', () => {
+ useTrashStore.setState({ nextCursor: 'abc' });
+ useTrashStore.getState().setActiveType('agent');
+ expect(useTrashStore.getState()).toMatchObject({
+ activeType: 'agent',
+ isTrashInit: false,
+ items: [],
+ nextCursor: null,
+ });
+ });
+
+ it('loadMore appends the next page', async () => {
+ useTrashStore.setState({ nextCursor: 'cursor-1' });
+ vi.spyOn(trashService, 'list').mockResolvedValue({
+ items: [buildItem({ id: 'trash_3', resourceId: 'tpc_3' })],
+ nextCursor: null,
+ });
+ await useTrashStore.getState().loadMore();
+ expect(trashService.list).toHaveBeenCalledWith({
+ cursor: 'cursor-1',
+ resourceType: undefined,
+ });
+ expect(useTrashStore.getState().items.map((i) => i.id)).toEqual([
+ 'trash_1',
+ 'trash_2',
+ 'trash_3',
+ ]);
+ expect(useTrashStore.getState().nextCursor).toBeNull();
+ });
+
+ it('loadMore fetches a cursor once even when clicked twice', async () => {
+ useTrashStore.setState({ nextCursor: 'cursor-1' });
+ vi.spyOn(trashService, 'list').mockResolvedValue({
+ items: [buildItem({ id: 'trash_3', resourceId: 'tpc_3' })],
+ nextCursor: null,
+ });
+ await Promise.all([useTrashStore.getState().loadMore(), useTrashStore.getState().loadMore()]);
+ expect(trashService.list).toHaveBeenCalledTimes(1);
+ expect(useTrashStore.getState().items.map((i) => i.id)).toEqual([
+ 'trash_1',
+ 'trash_2',
+ 'trash_3',
+ ]);
+ });
+
+ it('loadMore drops a page that lands after the filter changed', async () => {
+ useTrashStore.setState({ nextCursor: 'cursor-1' });
+ let resolve!: (value: Awaited<ReturnType<typeof trashService.list>>) => void;
+ vi.spyOn(trashService, 'list').mockReturnValue(new Promise((r) => (resolve = r)));
+
+ const pending = useTrashStore.getState().loadMore();
+ useTrashStore.getState().setActiveType('agent');
+ resolve({ items: [buildItem({ id: 'trash_3', resourceId: 'tpc_3' })], nextCursor: null });
+ await pending;
+
+ expect(useTrashStore.getState().items).toEqual([]);
+ expect(useTrashStore.getState().isLoadingMore).toBe(false);
+ });
+ });
+
+ describe('workspace scope', () => {
+ it("clears the previous scope's rows when the workspace switches", () => {
+ const { rerender } = renderHook(() => useTrashStore.getState().useFetchTrash(true));
+ expect(useTrashStore.getState().items).toHaveLength(2);
+
+ scopeMock.current = 'u1:ws-2';
+ rerender();
+
+ expect(useTrashStore.getState()).toMatchObject({
+ countByType: {},
+ isTrashInit: false,
+ items: [],
+ nextCursor: null,
+ scope: 'u1:ws-2',
+ });
+ });
+
+ it('ignores a list response that belongs to a scope the user has left', () => {
+ renderHook(() => useTrashStore.getState().useFetchTrash(true));
+ const options = vi.mocked(useClientDataSWR).mock.calls.at(-1)![2] as {
+ onSuccess: (data: unknown) => void;
+ };
+
+ scopeMock.current = 'u1:ws-2';
+ options.onSuccess({ items: [buildItem({ id: 'stale' })], nextCursor: null });
+
+ expect(useTrashStore.getState().items.map((i) => i.id)).not.toContain('stale');
+ });
+ });
+
+ describe('selectors', () => {
+ it('totalCount sums the per-type counts', () => {
+ expect(trashSelectors.totalCount(useTrashStore.getState())).toBe(3);
+ });
+ });
+});
diff --git a/src/store/trash/action.ts b/src/store/trash/action.ts
new file mode 100644
index 00000000000..bfd40385a97
--- /dev/null
+++ b/src/store/trash/action.ts
@@ -0,0 +1,223 @@
+import type {
+ TrashCountByType,
+ TrashItem,
+ TrashListResult,
+ TrashResourceType,
+} from '@lobechat/types';
+import { useLayoutEffect } from 'react';
+import type { SWRResponse } from 'swr';
+
+import { mutate, useClientDataSWR } from '@/libs/swr';
+import { trashKeys } from '@/libs/swr/keys';
+import { getCacheScope, useCacheScope } from '@/libs/swr/useCacheScope';
+import { trashService } from '@/services/trash';
+import type { StoreSetter } from '@/store/types';
+
+import type { TrashStore } from './store';
+
+type Setter = StoreSetter<TrashStore>;
+
+/** SWR key roots whose lists can regain rows after a restore. */
+const RESTORE_AFFECTED_KEY_PREFIXES = [
+ 'agent:',
+ 'document:',
+ 'file:',
+ 'group:',
+ 'home:',
+ 'image:',
+ 'knowledgeBase:',
+ 'page',
+ 'project',
+ 'recent:',
+ 'resource:',
+ 'session:',
+ 'task:',
+ 'topic:',
+ 'video:',
+];
+
+export const trashSlice = (set: Setter, get: () => TrashStore, _api?: unknown) =>
+ new TrashActionImpl(set, get, _api);
+
+/**
+ * Recycle-bin store. Rows are removed optimistically on restore / purge and
+ * the list + counts are revalidated afterwards so a failed call self-corrects.
+ */
+export class TrashActionImpl {
+ readonly #get: () => TrashStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => TrashStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ setActiveType = (activeType?: TrashResourceType) => {
+ this.#set(
+ { activeType, isTrashInit: false, items: [], nextCursor: null },
+ false,
+ 'setActiveType',
+ );
+ };
+
+ refresh = async () => {
+ await Promise.all([
+ mutate(trashKeys.list(this.#get().activeType)),
+ mutate(trashKeys.countByType()),
+ ]);
+ };
+
+ /**
+ * A restore brings rows back into lists owned by other stores (sidebar
+ * agents, topics, pages, files, tasks …). Revalidate every mounted SWR key in
+ * those namespaces so a user returning from the recycle bin sees the row
+ * without a reload. `mutate` with a filter only re-fetches keys that have a
+ * mounted subscriber, so this is cheap.
+ */
+ revalidateRestoredScopes = async () => {
+ await mutate(
+ (key: unknown) =>
+ Array.isArray(key) &&
+ typeof key[0] === 'string' &&
+ RESTORE_AFFECTED_KEY_PREFIXES.some((prefix) => (key[0] as string).startsWith(prefix)),
+ );
+ };
+
+ loadMore = async () => {
+ const { activeType, isLoadingMore, nextCursor, scope } = this.#get();
+ if (!nextCursor || isLoadingMore) return;
+ this.#set({ isLoadingMore: true }, false, 'loadMore/start');
+ try {
+ const page = await trashService.list({ cursor: nextCursor, resourceType: activeType });
+ // The filter, cursor or workspace may have moved on while this page was
+ // in flight; appending it then would mix another list's rows in.
+ const current = this.#get();
+ if (
+ current.activeType !== activeType ||
+ current.nextCursor !== nextCursor ||
+ current.scope !== scope
+ )
+ return;
+ this.#set(
+ { items: [...current.items, ...page.items], nextCursor: page.nextCursor },
+ false,
+ 'loadMore',
+ );
+ } finally {
+ this.#set({ isLoadingMore: false }, false, 'loadMore/end');
+ }
+ };
+
+ #withLoading = async (ids: string[], run: () => Promise<void>) => {
+ this.#set({ loadingIds: [...this.#get().loadingIds, ...ids] }, false, 'loading/start');
+ try {
+ await run();
+ } finally {
+ const done = new Set(ids);
+ this.#set(
+ { loadingIds: this.#get().loadingIds.filter((id) => !done.has(id)) },
+ false,
+ 'loading/end',
+ );
+ await this.refresh();
+ }
+ };
+
+ /**
+ * Restore roots. Returns the server outcome so the caller can toast the
+ * partial failures (a topic whose agent is still in the bin, …). Only the
+ * successfully restored rows leave the list.
+ */
+ restore = async (ids: string[]) => {
+ let outcome: Awaited<ReturnType<typeof trashService.restore>> = { failed: [], restored: [] };
+ await this.#withLoading(ids, async () => {
+ outcome = await trashService.restore(ids);
+ const gone = new Set(outcome.restored.map((item) => item.id));
+ // `notFound` rows were dropped from the registry server-side.
+ for (const failure of outcome.failed) if (failure.code === 'notFound') gone.add(failure.id);
+ this.#set(
+ { items: this.#get().items.filter((item) => !gone.has(item.id)) },
+ false,
+ 'restore',
+ );
+ });
+ if (outcome.restored.length > 0) void this.revalidateRestoredScopes();
+ return outcome;
+ };
+
+ purge = async (ids: string[]) => {
+ await this.#withLoading(ids, async () => {
+ await trashService.purge(ids);
+ const gone = new Set(ids);
+ this.#set({ items: this.#get().items.filter((item) => !gone.has(item.id)) }, false, 'purge');
+ });
+ };
+
+ emptyTrash = async () => {
+ const { activeType, items } = this.#get();
+ await this.#withLoading(
+ items.map((item) => item.id),
+ async () => {
+ // The server purges one bounded batch per call so no single request
+ // runs away on a large bin; keep going until it reports nothing left.
+ for (;;) {
+ const { hasMore } = await trashService.emptyTrash(activeType);
+ if (!hasMore) break;
+ }
+ this.#set({ items: [], nextCursor: null }, false, 'emptyTrash');
+ },
+ );
+ };
+
+ useFetchTrash = (
+ enabled: boolean,
+ resourceType?: TrashResourceType,
+ ): SWRResponse<TrashListResult> => {
+ const scope = useCacheScope();
+
+ // A workspace (or user) switch inside the SPA: drop the previous scope's
+ // rows before paint instead of showing them until — or, if the fetch
+ // fails, instead of — the new scope's list.
+ useLayoutEffect(() => {
+ if (!enabled || this.#get().scope === scope) return;
+ this.#set(
+ { countByType: {}, isTrashInit: false, items: [], nextCursor: null, scope },
+ false,
+ 'fetchTrash/scope',
+ );
+ }, [enabled, scope]);
+
+ return useClientDataSWR<TrashListResult>(
+ enabled ? trashKeys.list(resourceType) : null,
+ () => trashService.list({ resourceType }),
+ {
+ onSuccess: (data) => {
+ if (scope !== getCacheScope()) return;
+ this.#set(
+ { isTrashInit: true, items: data.items, nextCursor: data.nextCursor, scope },
+ false,
+ 'fetchTrash',
+ );
+ },
+ },
+ );
+ };
+
+ useFetchTrashCount = (enabled: boolean): SWRResponse<TrashCountByType> => {
+ const scope = useCacheScope();
+ return useClientDataSWR<TrashCountByType>(
+ enabled ? trashKeys.countByType() : null,
+ () => trashService.countByType(),
+ {
+ onSuccess: (data) => {
+ if (scope !== getCacheScope()) return;
+ this.#set({ countByType: data }, false, 'fetchTrashCount');
+ },
+ },
+ );
+ };
+}
+
+export type TrashAction = Pick<TrashActionImpl, keyof TrashActionImpl>;
+export type { TrashItem };
diff --git a/src/store/trash/index.ts b/src/store/trash/index.ts
new file mode 100644
index 00000000000..669f05650eb
--- /dev/null
+++ b/src/store/trash/index.ts
@@ -0,0 +1,2 @@
+export * from './selectors';
+export * from './store';
diff --git a/src/store/trash/initialState.ts b/src/store/trash/initialState.ts
new file mode 100644
index 00000000000..f155913ba3d
--- /dev/null
+++ b/src/store/trash/initialState.ts
@@ -0,0 +1,31 @@
+import type { TrashCountByType, TrashItem, TrashResourceType } from '@lobechat/types';
+
+export interface TrashState {
+ /** Type filter the recycle-bin page is currently showing (`undefined` = everything). */
+ activeType?: TrashResourceType;
+ countByType: TrashCountByType;
+ /** A load-more page request is in flight — a second click must not fetch the same cursor. */
+ isLoadingMore: boolean;
+ isTrashInit: boolean;
+ items: TrashItem[];
+ /** Registry ids with an in-flight restore / purge — drives per-row spinners. */
+ loadingIds: string[];
+ nextCursor: string | null;
+ /**
+ * Cache scope (`user:workspace`) the list above was fetched for. SWR keys are
+ * partitioned per workspace but this list is not, so a scope switch resets
+ * it rather than showing the previous workspace's rows.
+ */
+ scope?: string;
+}
+
+export const initialState: TrashState = {
+ activeType: undefined,
+ countByType: {},
+ isLoadingMore: false,
+ isTrashInit: false,
+ items: [],
+ loadingIds: [],
+ nextCursor: null,
+ scope: undefined,
+};
diff --git a/src/store/trash/selectors.ts b/src/store/trash/selectors.ts
new file mode 100644
index 00000000000..369203ed163
--- /dev/null
+++ b/src/store/trash/selectors.ts
@@ -0,0 +1,10 @@
+import type { TrashState } from './initialState';
+
+const totalCount = (s: TrashState) =>
+ Object.values(s.countByType).reduce((sum, count) => sum + (count ?? 0), 0);
+
+const isEmpty = (s: TrashState) => s.isTrashInit && s.items.length === 0;
+
+const isLoading = (id: string) => (s: TrashState) => s.loadingIds.includes(id);
+
+export const trashSelectors = { isEmpty, isLoading, totalCount };
diff --git a/src/store/trash/store.ts b/src/store/trash/store.ts
new file mode 100644
index 00000000000..ac60b379c6d
--- /dev/null
+++ b/src/store/trash/store.ts
@@ -0,0 +1,26 @@
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn } from 'zustand/traditional';
+import type { StateCreator } from 'zustand/vanilla';
+
+import { createDevtools } from '../middleware/createDevtools';
+import { expose } from '../middleware/expose';
+import { flattenActions } from '../utils/flattenActions';
+import { type TrashAction, trashSlice } from './action';
+import { initialState, type TrashState } from './initialState';
+
+export interface TrashStore extends TrashState, TrashAction {
+ /* empty */
+}
+
+const createStore: StateCreator<TrashStore, [['zustand/devtools', never]]> = (...parameters) => ({
+ ...initialState,
+ ...flattenActions<TrashAction>([trashSlice(...parameters)]),
+});
+
+const devtools = createDevtools('trash');
+
+export const useTrashStore = createWithEqualityFn<TrashStore>()(devtools(createStore), shallow);
+
+expose('trash', useTrashStore);
+
+export const getTrashStoreState = () => useTrashStore.getState();