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: filter trash by project (#20739)

Bryan4a41d29760a5
diff --git a/apps/server/src/routers/lambda/__tests__/trash.projectFilter.test.ts b/apps/server/src/routers/lambda/__tests__/trash.projectFilter.test.ts
new file mode 100644
index 00000000000..108e659c3e9
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/trash.projectFilter.test.ts
@@ -0,0 +1,278 @@
+// @vitest-environment node
+import { TRASH_EMPTY_BATCH_SIZE } from '@lobechat/const';
+import type { LobeChatDatabase } from '@lobechat/database';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentModel } from '@/database/models/agent';
+import { ProjectModel } from '@/database/models/project';
+import { TopicModel } from '@/database/models/topic';
+import { topics, trashItems, users, workspaces } from '@/database/schemas';
+import { TrashService } from '@/server/services/trash';
+
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(() => testDB),
+}));
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(() => ({ deleteFile: vi.fn(), deleteFiles: vi.fn() })),
+}));
+
+const { trashRouter } = await import('../trash');
+
+const ownerId = 'trash-filter-owner';
+const memberId = 'trash-filter-member';
+const strangerId = 'trash-filter-stranger';
+const workspaceId = 'trash-filter-ws';
+const otherWorkspaceId = 'trash-filter-ws-2';
+
+const personalCtx = (userId: string) => ({ userId }) as any;
+const workspaceCtx = (userId: string, workspaceRole: 'member' | 'owner', ws = workspaceId) =>
+ ({ userId, workspaceId: ws, workspaceRole }) as any;
+
+const createProject = (
+ userId: string,
+ ws: string | undefined,
+ identifier: string,
+ visibility?: 'private' | 'public',
+) => new ProjectModel(testDB, userId, ws).create({ identifier, name: identifier, visibility });
+
+/** Create topics under a project (or none) and trash each as its own root, oldest first. */
+const trashTopics = async (
+ userId: string,
+ ws: string | undefined,
+ projectId: string | null,
+ count = 1,
+) => {
+ const topicModel = new TopicModel(testDB, userId, ws);
+ const service = new TrashService(testDB, userId, ws);
+ const ids: string[] = [];
+ for (let i = 0; i < count; i++) {
+ const topic = await topicModel.create({ projectId, title: `${projectId ?? 'none'} ${i}` });
+ await service.trashTopics([topic.id]);
+ ids.push(topic.id);
+ }
+ return ids;
+};
+
+/** Trash an agent whose cascade carries topics recorded under `projectId`. */
+const trashAgentWithProjectTopics = async (
+ userId: string,
+ ws: string | undefined,
+ projectId: string,
+) => {
+ const agent = await new AgentModel(testDB, userId, ws).create({ title: 'agent' });
+ const topic = await new TopicModel(testDB, userId, ws).create({ agentId: agent.id, projectId });
+ await new TrashService(testDB, userId, ws).trashAgent(agent.id);
+ return { agentId: agent.id, topicId: topic.id };
+};
+
+const listIds = async (ctx: any, input: Parameters<ReturnType<typeof caller>['list']>[0] = {}) => {
+ const ids: string[] = [];
+ let cursor: string | null = null;
+ do {
+ const page: Awaited<ReturnType<ReturnType<typeof caller>['list']>> = await caller(ctx).list({
+ ...input,
+ cursor,
+ limit: 3,
+ });
+ ids.push(...page.items.map((item) => item.resourceId));
+ cursor = page.nextCursor;
+ } while (cursor);
+ return ids;
+};
+
+const caller = (ctx: any) => trashRouter.createCaller(ctx);
+
+beforeEach(async () => {
+ testDB = await getTestDB();
+ await testDB.delete(users);
+ await testDB.insert(users).values([{ id: ownerId }, { id: memberId }, { id: strangerId }]);
+ await testDB.insert(workspaces).values([
+ { id: workspaceId, name: 'ws', primaryOwnerId: ownerId, slug: workspaceId },
+ { id: otherWorkspaceId, name: 'ws2', primaryOwnerId: ownerId, slug: otherWorkspaceId },
+ ]);
+});
+
+afterEach(async () => {
+ vi.clearAllMocks();
+ await testDB.delete(users);
+});
+
+describe('trashRouter project filter', () => {
+ it('lists and counts all, no project and one project across pages in personal scope', async () => {
+ const alpha = await createProject(ownerId, undefined, 'ALPHA');
+ const beta = await createProject(ownerId, undefined, 'BETA');
+ const alphaIds = await trashTopics(ownerId, undefined, alpha.id, 7);
+ const betaIds = await trashTopics(ownerId, undefined, beta.id, 2);
+ const noneIds = await trashTopics(ownerId, undefined, null, 2);
+ const { agentId, topicId } = await trashAgentWithProjectTopics(ownerId, undefined, alpha.id);
+ const ctx = personalCtx(ownerId);
+
+ const alphaListed = await listIds(ctx, { projectId: alpha.id });
+ expect(alphaListed.sort()).toEqual([...alphaIds].sort());
+ expect(await caller(ctx).countByType({ projectId: alpha.id })).toEqual({ topic: 7 });
+
+ // The agent root is never in a project, and its cascaded project topic is not a root.
+ const none = await listIds(ctx, { projectId: null });
+ expect(none.sort()).toEqual([...noneIds, agentId].sort());
+ expect(none).not.toContain(topicId);
+ expect(await caller(ctx).countByType({ projectId: null })).toEqual({ agent: 1, topic: 2 });
+
+ const all = await listIds(ctx);
+ expect(all).toHaveLength(alphaIds.length + betaIds.length + noneIds.length + 1);
+ expect(new Set(all).size).toBe(all.length);
+ expect(await caller(ctx).countByType()).toEqual({ agent: 1, topic: 11 });
+ expect(await listIds(ctx, { projectId: beta.id, resourceType: 'agent' })).toEqual([]);
+ });
+
+ it('keeps rows of a deleted project under All and refuses the deleted project as a filter', async () => {
+ const gone = await createProject(ownerId, undefined, 'GONE');
+ const [orphan] = await trashTopics(ownerId, undefined, gone.id);
+ await new ProjectModel(testDB, ownerId).delete(gone.id);
+ const ctx = personalCtx(ownerId);
+
+ expect(await listIds(ctx)).toEqual([orphan]);
+ // Recorded under a project, so it is not "no project" either.
+ expect(await listIds(ctx, { projectId: null })).toEqual([]);
+ for (const run of [
+ () => caller(ctx).list({ projectId: gone.id }),
+ () => caller(ctx).countByType({ projectId: gone.id }),
+ () => caller(ctx).emptyTrash({ projectId: gone.id, workspaceId: null }),
+ ]) {
+ await expect(run()).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ }
+ expect(await listIds(ctx)).toEqual([orphan]);
+ });
+
+ it('refuses projects outside the caller scope or visibility without revealing their rows', async () => {
+ const personal = await createProject(ownerId, undefined, 'MINE');
+ const strangers = await createProject(strangerId, undefined, 'THEIRS');
+ const shared = await createProject(ownerId, workspaceId, 'TEAM');
+ const memberPrivate = await createProject(memberId, workspaceId, 'SECRET', 'private');
+ const elsewhere = await createProject(ownerId, otherWorkspaceId, 'ELSE');
+ await trashTopics(memberId, workspaceId, memberPrivate.id);
+ await trashTopics(strangerId, undefined, strangers.id);
+
+ const forged: [any, string][] = [
+ // another user's personal project, and a workspace project, from personal scope
+ [personalCtx(ownerId), strangers.id],
+ [personalCtx(ownerId), shared.id],
+ // a personal project and another workspace's project from inside a workspace
+ [workspaceCtx(ownerId, 'owner'), personal.id],
+ [workspaceCtx(ownerId, 'owner'), elsewhere.id],
+ // the owner cannot read a member's private project, so cannot filter by it
+ [workspaceCtx(ownerId, 'owner'), memberPrivate.id],
+ [workspaceCtx(strangerId, 'member'), memberPrivate.id],
+ ['personal-stranger', personal.id],
+ ];
+ for (const [ctx, projectId] of forged) {
+ const resolved = ctx === 'personal-stranger' ? personalCtx(strangerId) : ctx;
+ await expect(caller(resolved).list({ projectId })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ await expect(caller(resolved).countByType({ projectId })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ await expect(
+ caller(resolved).emptyTrash({ projectId, workspaceId: resolved.workspaceId ?? null }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ }
+ // Nothing was swept by the refused calls.
+ expect(await testDB.select().from(trashItems)).toHaveLength(2);
+ // The member who owns the private project filters by it normally.
+ expect(
+ await caller(workspaceCtx(memberId, 'member')).countByType({ projectId: memberPrivate.id }),
+ ).toEqual({ topic: 1 });
+ });
+
+ it('applies the member actor filter inside a project while the owner sees every root', async () => {
+ const team = await createProject(ownerId, workspaceId, 'TEAM');
+ const ownerRoots = await trashTopics(ownerId, workspaceId, team.id, 2);
+ const memberRoots = await trashTopics(memberId, workspaceId, team.id, 2);
+ await trashTopics(memberId, workspaceId, null, 1);
+
+ const owner = workspaceCtx(ownerId, 'owner');
+ const member = workspaceCtx(memberId, 'member');
+ expect((await listIds(owner, { projectId: team.id })).sort()).toEqual(
+ [...ownerRoots, ...memberRoots].sort(),
+ );
+ expect((await listIds(member, { projectId: team.id })).sort()).toEqual([...memberRoots].sort());
+ expect(await caller(member).countByType({ projectId: team.id })).toEqual({ topic: 2 });
+ expect(await caller(owner).countByType({ projectId: null })).toEqual({ topic: 1 });
+ // The personal bin of the same user is a different scope.
+ expect(await listIds(personalCtx(ownerId), { projectId: null })).toEqual([]);
+ });
+
+ it('empties only the matching roots of type, actor and project, each with its whole cascade', async () => {
+ const team = await createProject(ownerId, workspaceId, 'TEAM');
+ const other = await createProject(ownerId, workspaceId, 'OTHER');
+ const ownerTeam = await trashTopics(ownerId, workspaceId, team.id, 1);
+ const memberTeam = await trashTopics(
+ memberId,
+ workspaceId,
+ team.id,
+ TRASH_EMPTY_BATCH_SIZE + 2,
+ );
+ const memberOther = await trashTopics(memberId, workspaceId, other.id, 1);
+ const memberAgent = await trashAgentWithProjectTopics(memberId, workspaceId, team.id);
+ const member = workspaceCtx(memberId, 'member');
+
+ // A type that matches nothing in the project leaves everything in place.
+ expect(
+ await caller(member).emptyTrash({ projectId: team.id, resourceType: 'agent', workspaceId }),
+ ).toEqual({ hasMore: false, purged: 0 });
+
+ let purged = 0;
+ for (;;) {
+ const batch = await caller(member).emptyTrash({
+ projectId: team.id,
+ resourceType: 'topic',
+ workspaceId,
+ });
+ purged += batch.purged;
+ if (!batch.hasMore) break;
+ }
+ expect(purged).toBe(memberTeam.length);
+ const remaining = (await listIds(workspaceCtx(ownerId, 'owner'))).sort();
+ expect(remaining).toEqual([...ownerTeam, ...memberOther, memberAgent.agentId].sort());
+ // The agent's cascaded team topic is not a root of the project, so it survived…
+ expect(
+ await testDB.select().from(topics).where(eq(topics.id, memberAgent.topicId)),
+ ).toHaveLength(1);
+ expect(await testDB.select().from(topics).where(inArray(topics.id, memberTeam))).toHaveLength(
+ 0,
+ );
+
+ // …and emptying "no project" takes the agent root with its whole cascade.
+ expect(await caller(member).emptyTrash({ projectId: null, workspaceId })).toEqual({
+ hasMore: false,
+ purged: 1,
+ });
+ expect(
+ await testDB.select().from(topics).where(eq(topics.id, memberAgent.topicId)),
+ ).toHaveLength(0);
+ expect((await listIds(workspaceCtx(ownerId, 'owner'))).sort()).toEqual(
+ [...ownerTeam, ...memberOther].sort(),
+ );
+ });
+
+ it('refuses a batch whose request scope no longer matches the scope the sweep started in', async () => {
+ const roots = await trashTopics(ownerId, undefined, null, 2);
+ await trashTopics(ownerId, workspaceId, null, 1);
+
+ await expect(
+ caller(workspaceCtx(ownerId, 'owner')).emptyTrash({ workspaceId: null }),
+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+ await expect(caller(personalCtx(ownerId)).emptyTrash({ workspaceId })).rejects.toMatchObject({
+ code: 'PRECONDITION_FAILED',
+ });
+ expect(await testDB.select().from(trashItems)).toHaveLength(3);
+
+ expect(await caller(personalCtx(ownerId)).emptyTrash({ workspaceId: null })).toEqual({
+ hasMore: false,
+ purged: roots.length,
+ });
+ });
+});
diff --git a/apps/server/src/routers/lambda/trash.ts b/apps/server/src/routers/lambda/trash.ts
index 90cda8b96cb..ff7a8808183 100644
--- a/apps/server/src/routers/lambda/trash.ts
+++ b/apps/server/src/routers/lambda/trash.ts
@@ -1,7 +1,10 @@
+import type { TrashProjectFilter } from '@lobechat/types';
import { TRASH_RESOURCE_TYPES } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { ProjectModel } from '@/database/models/project';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { TrashService } from '@/server/services/trash';
@@ -15,11 +18,16 @@ 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) },
+ ctx: {
+ projectModel: new ProjectModel(ctx.serverDB, ctx.userId, wsId),
+ trashService: new TrashService(ctx.serverDB, ctx.userId, wsId),
+ },
});
});
const resourceTypeSchema = z.enum(TRASH_RESOURCE_TYPES);
+/** `undefined` = every project, `null` = roots without a project, a string = that project. */
+const projectFilterSchema = z.string().min(1).nullable().optional();
/**
* Recycle bin. Personal mode lists the caller's own rows; in a workspace the
@@ -30,18 +38,46 @@ const resourceTypeSchema = z.enum(TRASH_RESOURCE_TYPES);
* 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) }),
- ),
+ countByType: trashProcedure
+ .input(z.object({ projectId: projectFilterSchema }).optional())
+ .query(async ({ input, ctx }) => {
+ await assertProjectFilterReadable(ctx, input?.projectId);
+ return ctx.trashService.countByType({
+ deletedByUserId: actorFilter(ctx),
+ projectId: input?.projectId,
+ });
+ }),
emptyTrash: trashProcedure
- .input(z.object({ resourceType: resourceTypeSchema.optional() }).optional())
+ .input(
+ z
+ .object({
+ projectId: projectFilterSchema,
+ resourceType: resourceTypeSchema.optional(),
+ /**
+ * Scope the client started emptying in (`null` = personal). The
+ * request's own workspace context still decides what is reachable;
+ * this only refuses a batch that would land in another scope after
+ * the user switched workspace mid-sweep, so a sweep never widens.
+ */
+ workspaceId: z.string().nullable().optional(),
+ })
+ .optional(),
+ )
.mutation(async ({ input, ctx }) => {
+ if (input?.workspaceId !== undefined && input.workspaceId !== (ctx.workspaceId ?? null)) {
+ throw new TRPCError({
+ code: 'PRECONDITION_FAILED',
+ message: 'The active workspace changed while emptying the trash',
+ });
+ }
+ await assertProjectFilterReadable(ctx, input?.projectId);
// 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),
+ projectId: input?.projectId,
resourceType: input?.resourceType,
});
}),
@@ -52,18 +88,21 @@ export const trashRouter = router({
.object({
cursor: z.string().nullish(),
limit: z.number().int().min(1).max(200).optional(),
+ projectId: projectFilterSchema,
resourceType: resourceTypeSchema.optional(),
})
.optional(),
)
- .query(async ({ input, ctx }) =>
- ctx.trashService.list({
+ .query(async ({ input, ctx }) => {
+ await assertProjectFilterReadable(ctx, input?.projectId);
+ return ctx.trashService.list({
cursor: input?.cursor,
deletedByUserId: actorFilter(ctx),
limit: input?.limit,
+ projectId: input?.projectId,
resourceType: input?.resourceType,
- }),
- ),
+ });
+ }),
purge: trashProcedure
.input(z.object({ ids: z.array(z.string()).min(1).max(200) }))
@@ -80,6 +119,23 @@ export const trashRouter = router({
}),
});
+/**
+ * A project filter must name a project the caller can read in the current
+ * scope — the same visibility the project list applies (scope, private
+ * projects of other members, deleted projects). Filtering by any other id
+ * would let the caller probe which roots belong to a project they cannot see,
+ * or sweep by it; a deleted or revoked project is reported as `NOT_FOUND` so
+ * the client can tell "project unavailable" from "nothing in it".
+ */
+const assertProjectFilterReadable = async (
+ ctx: { projectModel: ProjectModel },
+ projectId: TrashProjectFilter,
+) => {
+ if (typeof projectId !== 'string') return;
+ if (await ctx.projectModel.findById(projectId)) return;
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Project not found' });
+};
+
/** 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;
diff --git a/apps/server/src/services/trash/index.ts b/apps/server/src/services/trash/index.ts
index d8315fbddc4..d9d08df73f0 100644
--- a/apps/server/src/services/trash/index.ts
+++ b/apps/server/src/services/trash/index.ts
@@ -4,8 +4,8 @@ import type {
TrashItem,
TrashListParams,
TrashListResult,
- TrashResourceType,
TrashRestoreErrorCode,
+ TrashRootFilter,
} from '@lobechat/types';
import debug from 'debug';
@@ -203,8 +203,8 @@ export class TrashService {
list = (params?: TrashListParams): Promise<TrashListResult> => this.trashModel.list(params);
- countByType = (options?: { deletedByUserId?: string }): Promise<TrashCountByType> =>
- this.trashModel.countByType(options);
+ countByType = (filter?: Omit<TrashRootFilter, 'resourceType'>): Promise<TrashCountByType> =>
+ this.trashModel.countByType(filter);
findByIds = async (ids: string[]): Promise<TrashItem[]> =>
(await this.trashModel.findByIds(ids)).map(this.toItem);
@@ -288,22 +288,24 @@ export class TrashService {
};
/**
- * 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.
+ * Permanently delete one bounded batch of the roots a recycle-bin view
+ * covers (type / project / actor). Each purge is serial and may call
+ * storage, so a bin of thousands must not ride a single HTTP request: the
+ * caller repeats with the same filter while `hasMore` is true, and every
+ * call commits only what it finished. A matched root takes its whole
+ * cascade with it, whatever its children were recorded under.
*/
- emptyTrash = async (options?: {
+ emptyTrash = async (
/**
- * 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` restricts 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 }> => {
+ filter?: TrashRootFilter,
+ ): Promise<{ hasMore: boolean; purged: number }> => {
const ids = await this.trashModel.listAllRootIds({
- ...options,
+ ...filter,
limit: TRASH_EMPTY_BATCH_SIZE + 1,
});
const { purged } = await this.purge(ids.slice(0, TRASH_EMPTY_BATCH_SIZE));
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 9943ec7f0aa..1e571d2d61c 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -1968,6 +1968,8 @@
"tools.tabs.installed": "Enabled",
"tools.title": "Skills",
"trash.actions.empty": "Empty trash",
+ "trash.actions.emptyFiltered": "Empty filtered ({{count}})",
+ "trash.actions.emptyFilteredPending": "Empty filtered",
"trash.actions.emptyType": "Empty {{type}}",
"trash.actions.loadMore": "Load more",
"trash.actions.purge": "Delete forever",
@@ -1980,14 +1982,28 @@
"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.filteredTitle": "Empty filtered items",
+ "trash.emptyConfirm.scope": "Scope: {{type}} · {{project}}",
"trash.emptyConfirm.title": "Empty trash",
+ "trash.emptyFilter.desc": "Nothing deleted matches this filter.",
+ "trash.emptyStopped.scopeChanged": "Emptying stopped because the workspace changed. Nothing outside the original filter was deleted.",
"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.filter.project.all": "All projects",
+ "trash.filter.project.empty": "No projects yet",
+ "trash.filter.project.group": "Projects",
+ "trash.filter.project.label": "Filter by project",
+ "trash.filter.project.loadFailed": "Couldn't load projects",
+ "trash.filter.project.none": "No project",
+ "trash.filter.project.unavailable": "Project unavailable",
+ "trash.filter.type.all": "All types",
"trash.loadFailed.desc": "Check your connection and try again.",
"trash.loadFailed.title": "Could not load the trash",
"trash.meta.children": "{{count}} items inside",
+ "trash.projectUnavailable.desc": "It was deleted or you no longer have access. Choose All projects, No project or another project to continue.",
+ "trash.projectUnavailable.title": "This project is no longer available",
"trash.purge.success": "Deleted permanently",
"trash.purgeConfirm.content": "Permanently delete \"{{title}}\"? This cannot be undone.",
"trash.purgeConfirm.title": "Delete forever",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 4c93212946d..7a30a27065b 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -1968,6 +1968,8 @@
"tools.tabs.installed": "已启用",
"tools.title": "技能",
"trash.actions.empty": "清空回收站",
+ "trash.actions.emptyFiltered": "清空筛选结果({{count}})",
+ "trash.actions.emptyFilteredPending": "清空筛选结果",
"trash.actions.emptyType": "清空{{type}}",
"trash.actions.loadMore": "加载更多",
"trash.actions.purge": "彻底删除",
@@ -1980,14 +1982,28 @@
"trash.empty.desc": "你删除的会话、助手和消息会先进入这里,保留 {{days}} 天后才会被永久删除。",
"trash.empty.title": "回收站是空的",
"trash.emptyConfirm.content": "永久删除这 {{count}} 项?此操作无法撤销。",
+ "trash.emptyConfirm.filteredTitle": "清空筛选结果",
+ "trash.emptyConfirm.scope": "范围:{{type}} · {{project}}",
"trash.emptyConfirm.title": "清空回收站",
+ "trash.emptyFilter.desc": "没有符合当前筛选的已删除内容。",
+ "trash.emptyStopped.scopeChanged": "工作区已切换,清空已停止。原筛选范围之外的内容没有被删除。",
"trash.emptyType.desc": "目前没有已删除的{{type}}。",
"trash.expiresIn.days": "{{count}} 天后",
"trash.expiresIn.soon": "一天内",
"trash.filter.all": "全部",
+ "trash.filter.project.all": "全部项目",
+ "trash.filter.project.empty": "暂无项目",
+ "trash.filter.project.group": "项目",
+ "trash.filter.project.label": "按项目筛选",
+ "trash.filter.project.loadFailed": "项目加载失败",
+ "trash.filter.project.none": "无项目",
+ "trash.filter.project.unavailable": "项目不可用",
+ "trash.filter.type.all": "全部类型",
"trash.loadFailed.desc": "请检查网络连接后重试。",
"trash.loadFailed.title": "回收站加载失败",
"trash.meta.children": "内含 {{count}} 项",
+ "trash.projectUnavailable.desc": "它可能已被删除,或你已无权访问。请选择「全部项目」「无项目」或其他项目后继续。",
+ "trash.projectUnavailable.title": "该项目已不可用",
"trash.purge.success": "已永久删除",
"trash.purgeConfirm.content": "永久删除「{{title}}」?此操作无法撤销。",
"trash.purgeConfirm.title": "彻底删除",
diff --git a/packages/database/src/models/__tests__/trash.test.ts b/packages/database/src/models/__tests__/trash.test.ts
index ca8b72fa7c8..4a909ce6e75 100644
--- a/packages/database/src/models/__tests__/trash.test.ts
+++ b/packages/database/src/models/__tests__/trash.test.ts
@@ -273,6 +273,107 @@ describe('TrashModel', () => {
});
});
+ describe('project filter', () => {
+ const wsModel = new TrashModel(serverDB, userId, workspaceId);
+ const wsMember = new TrashModel(serverDB, otherUserId, workspaceId);
+
+ /** Roots across projects, newest first: p1 ×5, p2, null, a deleted project, and an agent cascade. */
+ const seedProjects = async (registry: TrashModel, prefix: string) => {
+ const day = (i: number) => at(`2026-08-${String(i + 1).padStart(2, '0')}T00:00:00Z`);
+ for (let i = 0; i < 5; i++) {
+ await registry.register({
+ deletedAt: day(i),
+ root: { projectId: 'p1', resourceId: `${prefix}p1_${i}`, resourceType: 'topic' },
+ });
+ }
+ await registry.register({
+ deletedAt: day(5),
+ root: { projectId: 'p2', resourceId: `${prefix}p2_0`, resourceType: 'topic' },
+ });
+ await registry.register({
+ deletedAt: day(6),
+ root: { projectId: null, resourceId: `${prefix}legacy`, resourceType: 'message' },
+ });
+ await registry.register({
+ deletedAt: day(7),
+ root: { projectId: 'gone', resourceId: `${prefix}orphan`, resourceType: 'topic' },
+ });
+ // An agent is never in a project, even when its cascade carries project topics.
+ await registry.register({
+ children: [
+ { projectId: 'p1', resourceId: `${prefix}agent_child_p1`, resourceType: 'topic' },
+ { projectId: 'p2', resourceId: `${prefix}agent_child_p2`, resourceType: 'topic' },
+ ],
+ deletedAt: day(8),
+ root: { projectId: null, resourceId: `${prefix}agent`, resourceType: 'agent' },
+ });
+ };
+
+ const listAll = async (
+ registry: TrashModel,
+ filter: Parameters<TrashModel['list']>[0] = {},
+ ) => {
+ const ids: string[] = [];
+ let cursor: string | null = null;
+ do {
+ const page: Awaited<ReturnType<TrashModel['list']>> = await registry.list({
+ ...filter,
+ cursor,
+ limit: 2,
+ });
+ ids.push(...page.items.map((item) => item.resourceId));
+ cursor = page.nextCursor;
+ } while (cursor);
+ return ids;
+ };
+
+ it('separates every project, no project and all with matching counts across pages', async () => {
+ await seedProjects(model, '');
+
+ const p1 = await listAll(model, { projectId: 'p1' });
+ expect(p1).toEqual(['p1_4', 'p1_3', 'p1_2', 'p1_1', 'p1_0']);
+ expect(await model.countByType({ projectId: 'p1' })).toEqual({ topic: 5 });
+
+ // `null` is "recorded without a project": legacy rows and agents, never their children.
+ expect(await listAll(model, { projectId: null })).toEqual(['agent', 'legacy']);
+ expect(await model.countByType({ projectId: null })).toEqual({ agent: 1, message: 1 });
+
+ // "All" keeps rows of deleted projects and lists each root once.
+ const all = await listAll(model);
+ expect(all).toEqual(['agent', 'orphan', 'legacy', 'p2_0', ...p1]);
+ expect(new Set(all).size).toBe(all.length);
+ expect(await model.countByType()).toEqual({ agent: 1, message: 1, topic: 7 });
+
+ expect(await listAll(model, { projectId: 'p2', resourceType: 'agent' })).toEqual([]);
+ expect(await model.listAllRootIds({ projectId: 'p2' })).toHaveLength(1);
+ });
+
+ it('keeps project filters inside the personal or workspace scope and the actor filter', async () => {
+ await seedProjects(model, 'personal_');
+ await seedProjects(wsModel, 'owner_');
+ await wsMember.register({
+ deletedAt: at('2026-08-20T00:00:00Z'),
+ root: { projectId: 'p1', resourceId: 'member_p1', resourceType: 'topic' },
+ });
+
+ // Same project id in another scope never leaks across.
+ expect(await listAll(model, { projectId: 'p1' })).not.toContain('owner_p1_0');
+ expect((await listAll(wsModel, { projectId: 'p1' })).sort()).toEqual(
+ ['member_p1', ...Array.from({ length: 5 }, (_, i) => `owner_p1_${i}`)].sort(),
+ );
+
+ // A member restricted to their own roots sees only those inside the project.
+ const own = { deletedByUserId: otherUserId, projectId: 'p1' } as const;
+ expect(await listAll(wsMember, own)).toEqual(['member_p1']);
+ expect(await wsMember.countByType(own)).toEqual({ topic: 1 });
+ expect(await wsMember.listAllRootIds({ ...own, resourceType: 'topic' })).toHaveLength(1);
+ expect(await wsMember.listAllRootIds({ ...own, resourceType: 'message' })).toEqual([]);
+ expect(await wsMember.countByType({ deletedByUserId: otherUserId, projectId: null })).toEqual(
+ {},
+ );
+ });
+ });
+
describe('removeByIds', () => {
it('drops the root and cascades its children', async () => {
const root = await model.register({
diff --git a/packages/database/src/models/trash.ts b/packages/database/src/models/trash.ts
index 1f74dd0c5aa..0bee435fcfb 100644
--- a/packages/database/src/models/trash.ts
+++ b/packages/database/src/models/trash.ts
@@ -6,6 +6,7 @@ import type {
TrashListParams,
TrashListResult,
TrashResourceType,
+ TrashRootFilter,
} from '@lobechat/types';
import { and, asc, count, desc, eq, inArray, isNull, lt, lte, or, sql } from 'drizzle-orm';
@@ -83,6 +84,26 @@ export class TrashModel {
private ownership = () =>
buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, trashItems);
+ /**
+ * The roots one recycle-bin view covers. The list, its counts and "empty
+ * trash" all build on this, so a filter can never show one set of rows and
+ * count or purge another. Children are never matched on their own: a
+ * cascade is listed, counted and purged through its root, whatever project
+ * its children were recorded under.
+ */
+ private rootsWhere = ({ deletedByUserId, projectId, resourceType }: TrashRootFilter = {}) =>
+ and(
+ this.ownership(),
+ isNull(trashItems.rootId),
+ resourceType ? eq(trashItems.resourceType, resourceType) : undefined,
+ deletedByUserId ? eq(trashItems.deletedByUserId, deletedByUserId) : undefined,
+ projectId === undefined
+ ? undefined
+ : projectId === null
+ ? isNull(trashItems.projectId)
+ : eq(trashItems.projectId, projectId),
+ );
+
// ─────────────────────────── writes ───────────────────────────
/**
@@ -280,12 +301,7 @@ export class TrashModel {
.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,
+ this.rootsWhere(params),
cursor
? or(
lt(trashItems.deletedAt, cursor.deletedAt),
@@ -305,18 +321,15 @@ export class TrashModel {
};
};
- countByType = async (options?: { deletedByUserId?: string }): Promise<TrashCountByType> => {
+ /** Roots per type under the same filter as `list` (the type filter itself aside). */
+ countByType = async (
+ filter: Omit<TrashRootFilter, 'resourceType'> = {},
+ ): 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,
- ),
+ this.rootsWhere({ deletedByUserId: filter.deletedByUserId, projectId: filter.projectId }),
)
.groupBy(trashItems.resourceType);
@@ -356,29 +369,19 @@ export class TrashModel {
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[]> => {
+ /** Roots matching a recycle-bin view, oldest first — used by "empty trash". */
+ listAllRootIds = async (
+ options: TrashRootFilter & {
+ /** Cap the ids returned — empty-trash works one bounded batch per request. */
+ limit?: number;
+ } = {},
+ ): 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,
- ),
- )
+ .where(this.rootsWhere(options))
.orderBy(asc(trashItems.deletedAt), asc(trashItems.id));
- const rows = await (options?.limit ? query.limit(options.limit) : query);
+ const rows = await (options.limit ? query.limit(options.limit) : query);
return rows.map((row) => row.id);
};
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 9b298351347..e5a4787c5e1 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -1848,6 +1848,8 @@ When I am ___, I need ___
'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.emptyFiltered': 'Empty filtered ({{count}})',
+ 'trash.actions.emptyFilteredPending': 'Empty filtered',
'trash.actions.emptyType': 'Empty {{type}}',
'trash.actions.loadMore': 'Load more',
'trash.actions.purge': 'Delete forever',
@@ -1862,14 +1864,30 @@ When I am ___, I need ___
'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.filteredTitle': 'Empty filtered items',
+ 'trash.emptyConfirm.scope': 'Scope: {{type}} · {{project}}',
'trash.emptyConfirm.title': 'Empty trash',
+ 'trash.emptyFilter.desc': 'Nothing deleted matches this filter.',
+ 'trash.emptyStopped.scopeChanged':
+ 'Emptying stopped because the workspace changed. Nothing outside the original filter was deleted.',
'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.filter.project.all': 'All projects',
+ 'trash.filter.project.empty': 'No projects yet',
+ 'trash.filter.project.group': 'Projects',
+ 'trash.filter.project.label': 'Filter by project',
+ 'trash.filter.project.loadFailed': "Couldn't load projects",
+ 'trash.filter.project.none': 'No project',
+ 'trash.filter.project.unavailable': 'Project unavailable',
+ 'trash.filter.type.all': 'All types',
'trash.loadFailed.desc': 'Check your connection and try again.',
'trash.loadFailed.title': 'Could not load the trash',
'trash.meta.children': '{{count}} items inside',
+ 'trash.projectUnavailable.desc':
+ 'It was deleted or you no longer have access. Choose All projects, No project or another project to continue.',
+ 'trash.projectUnavailable.title': 'This project is no longer available',
'trash.purgeConfirm.content': 'Permanently delete "{{title}}"? This cannot be undone.',
'trash.purgeConfirm.title': 'Delete forever',
'trash.restore.failed.notFound': 'This item no longer exists.',
diff --git a/packages/types/src/trash.ts b/packages/types/src/trash.ts
index bc77f270eb3..fc75afaecf5 100644
--- a/packages/types/src/trash.ts
+++ b/packages/types/src/trash.ts
@@ -65,18 +65,35 @@ export interface TrashItem {
workspaceId: string | null;
}
-export interface TrashListParams {
- cursor?: string | null;
+/**
+ * Project filter over the project recorded when a root was first trashed
+ * (`trash_items.project_id`):
+ *
+ * - `undefined` — every root, whatever its project (including projects that
+ * have since been deleted).
+ * - `null` — only roots recorded without a project: agents, project-less
+ * topics / messages, and rows trashed before project context was captured.
+ * - a project id — only roots recorded under that project.
+ */
+export type TrashProjectFilter = string | null | undefined;
+
+/** Filters shared by the recycle-bin list, its counts and "empty trash". */
+export interface TrashRootFilter {
/**
* 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;
+ projectId?: TrashProjectFilter;
resourceType?: TrashResourceType;
}
+export interface TrashListParams extends TrashRootFilter {
+ cursor?: string | null;
+ limit?: number;
+}
+
export interface TrashListResult {
items: TrashItem[];
nextCursor: string | null;
diff --git a/src/features/Settings/trash/features/ProjectFilter.tsx b/src/features/Settings/trash/features/ProjectFilter.tsx
new file mode 100644
index 00000000000..8c0a5b75ee1
--- /dev/null
+++ b/src/features/Settings/trash/features/ProjectFilter.tsx
@@ -0,0 +1,140 @@
+'use client';
+
+import type { TrashProjectFilter } from '@lobechat/types';
+import { Flexbox, Icon } from '@lobehub/ui';
+import { controlHeight, Select, type SelectOptions, Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { FolderKanbanIcon, LockIcon } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import type { ProjectListItem } from '@/store/project';
+
+import {
+ fromProjectFilterValue,
+ PROJECT_FILTER_ALL,
+ PROJECT_FILTER_NONE,
+ toProjectFilterValue,
+} from './projectFilterState';
+
+/**
+ * The picker sits beside the type Segmented in one filter row, so it takes
+ * that track's height (`controlHeight.middle`), radius and surface while
+ * keeping the small control's 12px text. Open / hover feedback stays.
+ */
+const styles = createStaticStyles(({ css }) => ({
+ trigger: css`
+ min-height: ${controlHeight.middle}px;
+ border-color: ${cssVar.colorFillQuaternary};
+ border-radius: ${cssVar.borderRadiusLG};
+ background: ${cssVar.colorBgLayout};
+
+ &:hover {
+ border-color: ${cssVar.colorBorderSecondary};
+ background: ${cssVar.colorBgLayout};
+ }
+ `,
+}));
+
+interface ProjectFilterProps {
+ error?: unknown;
+ isValidating: boolean;
+ onChange: (projectId: TrashProjectFilter) => void;
+ /** Re-read the live project list (names, access) whenever the picker opens. */
+ onOpen: () => void;
+ onRetry: () => void;
+ /** The live project list of the current scope; `undefined` until it loads. */
+ projects?: ProjectListItem[];
+ unavailable: boolean;
+ value: TrashProjectFilter;
+}
+
+export const ProjectFilter = ({
+ error,
+ isValidating,
+ onChange,
+ onOpen,
+ onRetry,
+ projects,
+ unavailable,
+ value,
+}: ProjectFilterProps) => {
+ const { t } = useTranslation('setting');
+
+ const projectOptions = (projects ?? []).map((project) => ({
+ label: (
+ <Flexbox horizontal align={'center'} gap={6} style={{ minWidth: 0 }}>
+ <Text ellipsis style={{ minWidth: 0 }}>
+ {project.name}
+ </Text>
+ {/* Names are not unique; the identifier tells same-named projects apart. */}
+ <Text fontSize={12} style={{ flex: 'none' }} type={'secondary'}>
+ {project.identifier}
+ </Text>
+ {project.visibility === 'private' && (
+ <Icon color={cssVar.colorTextTertiary} icon={LockIcon} size={12} />
+ )}
+ </Flexbox>
+ ),
+ // Search matches the name and the identifier.
+ title: `${project.name} ${project.identifier}`,
+ value: project.id,
+ }));
+
+ const options: SelectOptions = [
+ { label: t('trash.filter.project.all'), value: PROJECT_FILTER_ALL },
+ { label: t('trash.filter.project.none'), value: PROJECT_FILTER_NONE },
+ ];
+ // Until the list loads (or while it fails) there is no project group to show.
+ if (projects) {
+ options.push({
+ label: t('trash.filter.project.group'),
+ options:
+ projects.length === 0
+ ? [{ disabled: true, label: t('trash.filter.project.empty'), value: '__empty__' }]
+ : projectOptions,
+ });
+ }
+ // A selected project that is gone keeps the view restricted, without its name.
+ if (unavailable && typeof value === 'string') {
+ options.push({ disabled: true, label: t('trash.filter.project.unavailable'), value });
+ }
+
+ return (
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
+ <Select
+ showSearch
+ aria-label={t('trash.filter.project.label')}
+ className={styles.trigger}
+ loading={!projects && isValidating}
+ options={options}
+ popupMatchSelectWidth={280}
+ prefix={FolderKanbanIcon}
+ size={'small'}
+ style={{ maxWidth: 260, minWidth: 160 }}
+ // Not `virtual`: the virtual list counts the whole project group as one
+ // row and crashes once search shrinks the options; search is the way
+ // through a long list.
+ value={toProjectFilterValue(value)}
+ onChange={(next) => {
+ if (typeof next === 'string') onChange(fromProjectFilterValue(next));
+ }}
+ onOpenChange={(open) => {
+ if (open) onOpen();
+ }}
+ />
+ {!projects && !!error && (
+ // Keeps its own width: the filter row wraps before the message squeezes.
+ <div style={{ flex: 'none', whiteSpace: 'nowrap' }}>
+ <AsyncError
+ error={error}
+ retrying={isValidating}
+ title={t('trash.filter.project.loadFailed')}
+ variant={'inline'}
+ onRetry={onRetry}
+ />
+ </div>
+ )}
+ </Flexbox>
+ );
+};
diff --git a/src/features/Settings/trash/features/TrashList.tsx b/src/features/Settings/trash/features/TrashList.tsx
index 0e5fe889748..19b2f6dafd8 100644
--- a/src/features/Settings/trash/features/TrashList.tsx
+++ b/src/features/Settings/trash/features/TrashList.tsx
@@ -1,21 +1,48 @@
'use client';
import { TRASH_RETENTION_DAYS } from '@lobechat/const';
-import type { TrashCountByType, TrashItem, TrashResourceType } from '@lobechat/types';
+import type {
+ TrashCountByType,
+ TrashItem,
+ TrashProjectFilter,
+ 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 {
+ Avatar,
+ Button,
+ confirmModal,
+ controlHeight,
+ Segmented,
+ Tag,
+ Text,
+ toast,
+} from '@lobehub/ui/base-ui';
import { useSize } from 'ahooks';
import { createStaticStyles } from 'antd-style';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { Trash2Icon } from 'lucide-react';
-import { useRef } from 'react';
+import { useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import LiteTable, { type LiteTableColumn } from '@/components/LiteTable';
import { useIsMobile } from '@/hooks/useIsMobile';
+import { useCacheScope } from '@/libs/swr/useCacheScope';
+import type { TrashViewFilter } from '@/services/trash';
+import { useLoadedProjectList, useProjectStore } from '@/store/project';
import { trashSelectors, useTrashStore } from '@/store/trash';
+import { TrashEmptyScopeChangedError } from '@/store/trash/action';
+import { useUserStore } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/selectors';
+import { ProjectFilter } from './ProjectFilter';
+import {
+ canEmptyTrashView,
+ isProjectRefusedError,
+ isScopeChangedError,
+ resolveProjectAvailability,
+} from './projectFilterState';
import { TRASH_TYPE_ICON, TRASH_TYPE_ORDER } from './typeMeta';
dayjs.extend(relativeTime);
@@ -32,6 +59,14 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
border-radius: ${cssVar.borderRadius};
background: ${cssVar.colorBgContainer};
`,
+ /**
+ * Type chips on the small control height: with the track's 3px padding and
+ * 1px border the whole Segmented is `controlHeight.middle` tall, level with
+ * the project picker and the empty button beside it.
+ */
+ filterItem: css`
+ height: ${controlHeight.small}px;
+ `,
header: css`
display: flex;
flex-wrap: wrap;
@@ -87,9 +122,8 @@ const TrashList = () => {
const [
activeType,
- countByType,
loadingIds,
- setActiveType,
+ setFilter,
restore,
purge,
emptyTrash,
@@ -98,9 +132,8 @@ const TrashList = () => {
useFetchTrashCount,
] = useTrashStore((s) => [
s.activeType,
- s.trashCountMap.all ?? EMPTY_COUNTS,
s.loadingIds,
- s.setActiveType,
+ s.setFilter,
s.restore,
s.purge,
s.emptyTrash,
@@ -109,20 +142,82 @@ const TrashList = () => {
s.useFetchTrashCount,
]);
- // The active filter's local-first page: first frame paints from storage.
- const list = useTrashStore(trashSelectors.currentList(activeType));
- const items = list?.items ?? EMPTY_ITEMS;
- const nextCursor = list?.nextCursor ?? null;
- const isLoadingMore = !!list?.isLoadingMore;
- const isEmpty = useTrashStore(trashSelectors.isEmpty(activeType));
- const total = useTrashStore(trashSelectors.totalCount);
+ // Projects are a Labs feature: without it the bin is not filtered by project.
+ const scope = useCacheScope();
+ const projectsEnabled = useUserStore(labPreferSelectors.enableProjects);
+ const selectedProjectId = useTrashStore(trashSelectors.activeProjectId(scope));
+ const projectId: TrashProjectFilter = projectsEnabled ? selectedProjectId : undefined;
+ const filter: TrashViewFilter = { projectId, resourceType: activeType };
+
+ // The live project list of this scope is the only source of project options.
+ const projectSync = useProjectStore((s) => s.useFetchProjectList)(projectsEnabled);
+ const refreshProjectList = useProjectStore((s) => s.refreshProjectList);
+ const projects = useLoadedProjectList();
+ const listedAvailability = resolveProjectAvailability({ projectId, projects });
+ // A project the live list no longer holds is not asked for at all.
+ const canFetch = listedAvailability !== 'unavailable';
+
+ // The active view's local-first page: first frame paints from storage.
+ const list = useTrashStore(trashSelectors.currentList(filter));
+ const isEmpty = useTrashStore(trashSelectors.isEmpty(filter));
+ const counts = useTrashStore(trashSelectors.countByType(projectId));
+ const storedFilterCount = useTrashStore(trashSelectors.filterCount(filter));
+ const storedTotal = useTrashStore(trashSelectors.totalCount(projectId));
+
+ const { error, isValidating, revalidate } = useFetchTrash(canFetch, filter);
+ const countSync = useFetchTrashCount(canFetch, projectId);
+
+ // The server refuses a project that was deleted or whose access was revoked;
+ // re-read the project list so the picker drops it as well.
+ const refused = isProjectRefusedError(error) || isProjectRefusedError(countSync.error);
+ useEffect(() => {
+ if (refused) void refreshProjectList();
+ }, [refused, refreshProjectList]);
- const { error, isValidating, revalidate } = useFetchTrash(true, activeType);
- useFetchTrashCount(true);
+ const availability = resolveProjectAvailability({ projectId, projects, refused });
+ const projectUnavailable = availability === 'unavailable';
+ const listError = refused ? undefined : error;
- const isLoading = !isEmpty && items.length === 0 && isValidating;
+ // Counts cached for a project that is gone describe nothing the user can act on.
+ const countByType = (!projectUnavailable && counts) || EMPTY_COUNTS;
+ const filterCount = projectUnavailable ? undefined : storedFilterCount;
+ const total = projectUnavailable ? 0 : storedTotal;
+
+ // An unavailable project keeps the view restricted to it, showing nothing.
+ const items = (!projectUnavailable && list?.items) || EMPTY_ITEMS;
+ const nextCursor = projectUnavailable ? null : (list?.nextCursor ?? null);
+ const isLoadingMore = !!list?.isLoadingMore;
+ const isLoading = !isEmpty && items.length === 0 && isValidating && !projectUnavailable;
+
+ const canEmpty = canEmptyTrashView({
+ availability,
+ countsSettled: !countSync.isValidating,
+ filterCount,
+ hasError: !!error || !!countSync.error,
+ itemCount: items.length,
+ });
const typeLabel = (type: TrashResourceType) => t(`trash.type.${type}` as const);
+ const projectLabel = (id: TrashProjectFilter) => {
+ if (id === undefined) return t('trash.filter.project.all');
+ if (id === null) return t('trash.filter.project.none');
+ const project = projects?.find((item) => item.id === id);
+ return project
+ ? `${project.name} (${project.identifier})`
+ : t('trash.filter.project.unavailable');
+ };
+ const emptyLabel = (view: TrashViewFilter, count?: number) => {
+ if (view.projectId !== undefined)
+ // Never a confident zero while the counts are still unknown.
+ return count === undefined
+ ? t('trash.actions.emptyFilteredPending')
+ : t('trash.actions.emptyFiltered', { count });
+ if (view.resourceType)
+ return t('trash.actions.emptyType', { type: typeLabel(view.resourceType) });
+ return t('trash.actions.empty');
+ };
+
+ const changeFilter = (next: TrashViewFilter) => setFilter(next, scope);
// 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.
@@ -164,24 +259,44 @@ const TrashList = () => {
};
const handleEmpty = () => {
- const count = activeType ? (countByType[activeType] ?? items.length) : total;
+ // Fixed for the whole sweep: switching the view while it runs never widens it.
+ const view: TrashViewFilter = { ...filter };
+ const count = filterCount ?? 0;
+ const filtered = view.projectId !== undefined || !!view.resourceType;
confirmModal({
cancelText: tc('cancel'),
- content: t('trash.emptyConfirm.content', { count }),
+ content: (
+ <Flexbox gap={8}>
+ <span>{t('trash.emptyConfirm.content', { count })}</span>
+ {filtered && (
+ <Text type={'secondary'}>
+ {t('trash.emptyConfirm.scope', {
+ project: projectLabel(view.projectId),
+ type: view.resourceType ? typeLabel(view.resourceType) : t('trash.filter.type.all'),
+ })}
+ </Text>
+ )}
+ </Flexbox>
+ ),
okButtonProps: { danger: true },
- okText: activeType
- ? t('trash.actions.emptyType', { type: typeLabel(activeType) })
- : t('trash.actions.empty'),
+ okText: emptyLabel(view, count),
onOk: async () => {
try {
- await emptyTrash();
- } catch {
- reportFailure();
+ await emptyTrash(view);
+ } catch (error) {
+ if (error instanceof TrashEmptyScopeChangedError || isScopeChangedError(error)) {
+ toast.error(t('trash.emptyStopped.scopeChanged'));
+ } else if (isProjectRefusedError(error)) {
+ toast.error(t('trash.projectUnavailable.title'));
+ void refreshProjectList();
+ } else {
+ reportFailure();
+ }
return;
}
toast.success(t('trash.purge.success'));
},
- title: t('trash.emptyConfirm.title'),
+ title: filtered ? t('trash.emptyConfirm.filteredTitle') : t('trash.emptyConfirm.title'),
});
};
@@ -297,34 +412,57 @@ const TrashList = () => {
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]}`,
+ // The selected type stays listed at zero, so the active filter is always visible.
+ ...TRASH_TYPE_ORDER.filter((type) => countByType[type] || type === activeType).map((type) => ({
+ label: `${typeLabel(type)} · ${countByType[type] ?? 0}`,
value: type,
})),
];
+ const emptyDescription = () => {
+ if (filter.projectId !== undefined) return t('trash.emptyFilter.desc');
+ if (activeType) return t('trash.emptyType.desc', { type: typeLabel(activeType) });
+ return t('trash.empty.desc', { days: TRASH_RETENTION_DAYS });
+ };
+
return (
<div className={styles.container} ref={containerRef}>
<div className={styles.header}>
- <Segmented
- options={typeOptions}
- size={'small'}
- style={{ flexWrap: 'wrap', maxWidth: '100%' }}
- value={activeType ?? 'all'}
- onChange={(value) =>
- setActiveType(value === 'all' ? undefined : (value as TrashResourceType))
- }
- />
+ <Flexbox horizontal align={'center'} gap={8} style={{ flexWrap: 'wrap', minWidth: 0 }}>
+ <Segmented
+ classNames={{ item: styles.filterItem }}
+ options={typeOptions}
+ size={'small'}
+ style={{ flexWrap: 'wrap', maxWidth: '100%' }}
+ value={activeType ?? 'all'}
+ onChange={(value) =>
+ changeFilter({
+ projectId,
+ resourceType: value === 'all' ? undefined : (value as TrashResourceType),
+ })
+ }
+ />
+ {projectsEnabled && (
+ <ProjectFilter
+ error={projectSync.error}
+ isValidating={projectSync.isValidating}
+ projects={projects}
+ unavailable={projectUnavailable}
+ value={projectId}
+ onChange={(next) => changeFilter({ projectId: next, resourceType: activeType })}
+ onOpen={() => void refreshProjectList()}
+ onRetry={() => void refreshProjectList()}
+ />
+ )}
+ </Flexbox>
<Button
danger
- disabled={items.length === 0}
+ disabled={!canEmpty}
icon={Trash2Icon}
size={mobile ? 'small' : undefined}
onClick={handleEmpty}
>
- {activeType
- ? t('trash.actions.emptyType', { type: typeLabel(activeType) })
- : t('trash.actions.empty')}
+ {emptyLabel(filter, filterCount)}
</Button>
</div>
<LiteTable
@@ -337,7 +475,12 @@ const TrashList = () => {
tableLayout={'fixed'}
emptyText={
<Center height={240} width={'100%'}>
- {error ? (
+ {projectUnavailable ? (
+ <Empty
+ description={t('trash.projectUnavailable.desc')}
+ title={t('trash.projectUnavailable.title')}
+ />
+ ) : listError ? (
<Empty
description={t('trash.loadFailed.desc')}
title={t('trash.loadFailed.title')}
@@ -349,11 +492,9 @@ const TrashList = () => {
/>
) : (
<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 })
+ description={emptyDescription()}
+ title={
+ activeType || filter.projectId !== undefined ? undefined : t('trash.empty.title')
}
/>
)}
@@ -366,7 +507,7 @@ const TrashList = () => {
loading={isLoadingMore}
size={'small'}
type={'text'}
- onClick={() => loadMore().catch(reportFailure)}
+ onClick={() => loadMore(filter).catch(reportFailure)}
>
{t('trash.actions.loadMore')}
</Button>
diff --git a/src/features/Settings/trash/features/projectFilterState.test.ts b/src/features/Settings/trash/features/projectFilterState.test.ts
new file mode 100644
index 00000000000..885e4149e83
--- /dev/null
+++ b/src/features/Settings/trash/features/projectFilterState.test.ts
@@ -0,0 +1,78 @@
+import { TRPCClientError } from '@trpc/client';
+import { describe, expect, it } from 'vitest';
+
+import {
+ canEmptyTrashView,
+ fromProjectFilterValue,
+ isProjectRefusedError,
+ isScopeChangedError,
+ PROJECT_FILTER_ALL,
+ PROJECT_FILTER_NONE,
+ resolveProjectAvailability,
+ toProjectFilterValue,
+} from './projectFilterState';
+
+const trpcError = (code: string) =>
+ new TRPCClientError('refused', { result: { error: { data: { code } } } } as any);
+
+describe('trash project filter state', () => {
+ it('round-trips all, no project and a project through the picker value', () => {
+ for (const projectId of [undefined, null, 'proj_a']) {
+ expect(fromProjectFilterValue(toProjectFilterValue(projectId))).toBe(projectId);
+ }
+ expect(toProjectFilterValue(undefined)).toBe(PROJECT_FILTER_ALL);
+ expect(toProjectFilterValue(null)).toBe(PROJECT_FILTER_NONE);
+ });
+
+ it('never makes All or No project depend on the project list', () => {
+ for (const projectId of [undefined, null]) {
+ for (const projects of [undefined, []]) {
+ expect(resolveProjectAvailability({ projectId, projects, refused: true })).toBe(
+ 'available',
+ );
+ }
+ }
+ });
+
+ it('keeps a project unconfirmed while the list loads and unavailable once it is gone', () => {
+ const projects = [{ id: 'proj_a' }, { id: 'proj_b' }];
+ expect(resolveProjectAvailability({ projectId: 'proj_a', projects: undefined })).toBe(
+ 'unknown',
+ );
+ expect(resolveProjectAvailability({ projectId: 'proj_a', projects })).toBe('available');
+ // Deleted or access revoked: the live list no longer holds it.
+ expect(resolveProjectAvailability({ projectId: 'proj_c', projects })).toBe('unavailable');
+ expect(resolveProjectAvailability({ projectId: 'proj_a', projects: [] })).toBe('unavailable');
+ // The server refused it before the list caught up.
+ expect(resolveProjectAvailability({ projectId: 'proj_a', projects, refused: true })).toBe(
+ 'unavailable',
+ );
+ });
+
+ it('offers "empty" only on a settled, confirmed view', () => {
+ const settled = {
+ availability: 'available' as const,
+ countsSettled: true,
+ filterCount: 3,
+ hasError: false,
+ itemCount: 3,
+ };
+ expect(canEmptyTrashView(settled)).toBe(true);
+ expect(canEmptyTrashView({ ...settled, availability: 'unknown' })).toBe(false);
+ expect(canEmptyTrashView({ ...settled, availability: 'unavailable' })).toBe(false);
+ // A cached count still being revalidated may be stale.
+ expect(canEmptyTrashView({ ...settled, countsSettled: false })).toBe(false);
+ expect(canEmptyTrashView({ ...settled, filterCount: undefined })).toBe(false);
+ expect(canEmptyTrashView({ ...settled, filterCount: 0 })).toBe(false);
+ expect(canEmptyTrashView({ ...settled, hasError: true })).toBe(false);
+ expect(canEmptyTrashView({ ...settled, itemCount: 0 })).toBe(false);
+ });
+
+ it('recognizes the server refusals by their TRPC code', () => {
+ expect(isProjectRefusedError(trpcError('NOT_FOUND'))).toBe(true);
+ expect(isProjectRefusedError(trpcError('INTERNAL_SERVER_ERROR'))).toBe(false);
+ expect(isProjectRefusedError(undefined)).toBe(false);
+ expect(isScopeChangedError(trpcError('PRECONDITION_FAILED'))).toBe(true);
+ expect(isScopeChangedError(trpcError('NOT_FOUND'))).toBe(false);
+ });
+});
diff --git a/src/features/Settings/trash/features/projectFilterState.ts b/src/features/Settings/trash/features/projectFilterState.ts
new file mode 100644
index 00000000000..3f04c6da3a9
--- /dev/null
+++ b/src/features/Settings/trash/features/projectFilterState.ts
@@ -0,0 +1,77 @@
+import type { TrashProjectFilter } from '@lobechat/types';
+
+import { normalizeAsyncError } from '@/libs/swr/normalizeError';
+
+/** Picker values of the two filters that are not a project; project ids never look like these. */
+export const PROJECT_FILTER_ALL = '__all__';
+export const PROJECT_FILTER_NONE = '__none__';
+
+export const toProjectFilterValue = (projectId: TrashProjectFilter): string =>
+ projectId === undefined
+ ? PROJECT_FILTER_ALL
+ : projectId === null
+ ? PROJECT_FILTER_NONE
+ : projectId;
+
+export const fromProjectFilterValue = (value: string): TrashProjectFilter =>
+ value === PROJECT_FILTER_ALL ? undefined : value === PROJECT_FILTER_NONE ? null : value;
+
+/**
+ * Whether the selected project filter can be acted on:
+ *
+ * - `available` — All, No project, or a project the loaded project list holds.
+ * - `unknown` — a project while the project list has not loaded yet: the bin
+ * may be read (the server checks access on every request) but nothing may be
+ * swept on its behalf.
+ * - `unavailable` — the loaded project list no longer holds it (deleted, or
+ * access lost), or the server refused it as a filter.
+ */
+export type ProjectFilterAvailability = 'available' | 'unavailable' | 'unknown';
+
+export const resolveProjectAvailability = ({
+ projectId,
+ projects,
+ refused = false,
+}: {
+ projectId: TrashProjectFilter;
+ /** The live project list of the current scope; `undefined` until it loads. */
+ projects: { id: string }[] | undefined;
+ refused?: boolean;
+}): ProjectFilterAvailability => {
+ if (typeof projectId !== 'string') return 'available';
+ if (refused) return 'unavailable';
+ if (!projects) return 'unknown';
+ return projects.some((project) => project.id === projectId) ? 'available' : 'unavailable';
+};
+
+/**
+ * "Empty" sweeps every root the view covers, so it is only offered on a
+ * settled view: a confirmed project (never one that is still loading or gone),
+ * counts the server has just confirmed (not a cached copy still revalidating)
+ * to show what will be purged, and no failed request whose stale rows could
+ * misstate it.
+ */
+export const canEmptyTrashView = ({
+ availability,
+ countsSettled,
+ filterCount,
+ hasError,
+ itemCount,
+}: {
+ availability: ProjectFilterAvailability;
+ /** The counts are not being revalidated right now. */
+ countsSettled: boolean;
+ /** Roots the view covers; `undefined` while the counts are not loaded. */
+ filterCount: number | undefined;
+ hasError: boolean;
+ itemCount: number;
+}): boolean =>
+ availability === 'available' && countsSettled && !hasError && itemCount > 0 && !!filterCount;
+
+/** The server refused the project filter: the project is gone or no longer readable. */
+export const isProjectRefusedError = (error: unknown): boolean =>
+ !!error && normalizeAsyncError(error).code === 'NOT_FOUND';
+
+/** The server refused an "empty trash" batch because the active workspace changed mid-sweep. */
+export const isScopeChangedError = (error: unknown): boolean =>
+ !!error && normalizeAsyncError(error).code === 'PRECONDITION_FAILED';
diff --git a/src/services/project.test.ts b/src/services/project.test.ts
new file mode 100644
index 00000000000..7cfbfb0810a
--- /dev/null
+++ b/src/services/project.test.ts
@@ -0,0 +1,48 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { lambdaClient } from '@/libs/trpc/client';
+
+import { projectService } from './project';
+
+vi.mock('@/libs/trpc/client', () => ({
+ createWorkspaceLambdaClient: vi.fn(),
+ lambdaClient: { project: { list: { query: vi.fn() } } },
+}));
+
+const rows = (count: number) =>
+ Array.from({ length: count }, (_, i) => ({ id: `proj_${i}`, name: `Project ${i}` }));
+
+/** Serve `total` projects through the router's offset pagination. */
+const serve = (total: number) => {
+ const all = rows(total);
+ vi.mocked(lambdaClient.project.list.query).mockImplementation((async ({
+ limit,
+ offset,
+ }: {
+ limit: number;
+ offset: number;
+ }) => ({ data: all.slice(offset, offset + limit), success: true })) as any);
+ return all;
+};
+
+describe('projectService.listAll', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it.each([0, 99, 100, 250])(
+ 'returns every one of %i projects, past the router page limit',
+ async (total) => {
+ const all = serve(total);
+
+ const { data } = await projectService.listAll();
+
+ expect(data.map((project) => project.id)).toEqual(all.map((project) => project.id));
+ const pages = vi.mocked(lambdaClient.project.list.query).mock.calls.map(([input]) => input);
+ expect(pages.every((input) => input.limit === 100)).toBe(true);
+ expect(pages.map((input) => input.offset)).toEqual(
+ Array.from({ length: Math.floor(total / 100) + 1 }, (_, i) => i * 100),
+ );
+ },
+ );
+});
diff --git a/src/services/trash.ts b/src/services/trash.ts
index 889361fc203..00349346ba6 100644
--- a/src/services/trash.ts
+++ b/src/services/trash.ts
@@ -1,18 +1,26 @@
-import type { TrashListParams, TrashResourceType } from '@lobechat/types';
+import type { TrashListParams, TrashProjectFilter, TrashResourceType } from '@lobechat/types';
import { lambdaClient } from '@/libs/trpc/client';
+/** One recycle-bin view: `projectId` undefined = every project, `null` = no project. */
+export interface TrashViewFilter {
+ projectId?: TrashProjectFilter;
+ resourceType?: TrashResourceType;
+}
+
/**
* 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) {
+ list(params?: Omit<TrashListParams, 'deletedByUserId'>) {
return lambdaClient.trash.list.query(params ?? undefined);
}
- countByType() {
- return lambdaClient.trash.countByType.query();
+ countByType(projectId?: TrashProjectFilter) {
+ return lambdaClient.trash.countByType.query(
+ projectId === undefined ? undefined : { projectId },
+ );
}
restore(ids: string[]) {
@@ -23,8 +31,13 @@ class TrashService {
return lambdaClient.trash.purge.mutate({ ids });
}
- emptyTrash(resourceType?: TrashResourceType) {
- return lambdaClient.trash.emptyTrash.mutate(resourceType ? { resourceType } : undefined);
+ /**
+ * Purge one bounded batch of the roots `filter` covers. `workspaceId` is the
+ * scope the sweep started in (`null` = personal); the server refuses a batch
+ * that would run in any other scope.
+ */
+ emptyTrash(filter: TrashViewFilter, workspaceId: string | null) {
+ return lambdaClient.trash.emptyTrash.mutate({ ...filter, workspaceId });
}
}
diff --git a/src/store/project/index.ts b/src/store/project/index.ts
index 1028ac7ac17..69aad44a60d 100644
--- a/src/store/project/index.ts
+++ b/src/store/project/index.ts
@@ -1,2 +1,7 @@
export type { ProjectDetail, ProjectListItem } from './store';
-export { useCurrentProjectDetail, useCurrentProjectList, useProjectStore } from './store';
+export {
+ useCurrentProjectDetail,
+ useCurrentProjectList,
+ useLoadedProjectList,
+ useProjectStore,
+} from './store';
diff --git a/src/store/project/store.ts b/src/store/project/store.ts
index 7e68ffb598c..577b30973be 100644
--- a/src/store/project/store.ts
+++ b/src/store/project/store.ts
@@ -140,5 +140,12 @@ const EMPTY_PROJECTS: ProjectListItem[] = [];
export const useCurrentProjectList = () =>
useProjectStore((state) => state.projectListMap[PROJECT_LIST_KEY] ?? EMPTY_PROJECTS);
+/**
+ * Every project of the active scope, or `undefined` until the list first loads
+ * — for callers that must tell "not loaded" from "no projects".
+ */
+export const useLoadedProjectList = () =>
+ useProjectStore((state): ProjectListItem[] | undefined => state.projectListMap[PROJECT_LIST_KEY]);
+
export const useCurrentProjectDetail = (idOrSlug?: string) =>
useProjectStore((state) => (idOrSlug ? state.projectDetailMap[idOrSlug] : undefined));
diff --git a/src/store/trash/action.test.ts b/src/store/trash/action.test.ts
index 8df14215bd8..3dc4903f197 100644
--- a/src/store/trash/action.test.ts
+++ b/src/store/trash/action.test.ts
@@ -9,10 +9,11 @@
import type { TrashItem } from '@lobechat/types';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { createReplicaState } from '@/libs/replica';
+import { cacheScope, createReplicaState } from '@/libs/replica';
import { mutate } from '@/libs/swr';
-import { trashService } from '@/services/trash';
+import { trashService, type TrashViewFilter } from '@/services/trash';
+import { TrashEmptyScopeChangedError } from './action';
import type { TrashListData } from './initialState';
import { initialState } from './initialState';
import { trashListKey } from './projection';
@@ -65,17 +66,19 @@ const view = (items: TrashItem[]): TrashListData => ({
pages: [{ count: items.length, next: null }],
});
-const seed = (items: TrashItem[], activeType?: TrashItem['resourceType']) =>
+const seed = (items: TrashItem[], filter: TrashViewFilter = {}) =>
useTrashStore.setState({
...initialState,
- activeType,
+ activeType: filter.resourceType,
trashCountReplica: createReplicaState(),
- trashListMap: { [trashListKey(activeType)]: view(items) },
+ trashListMap: { [trashListKey(filter)]: view(items) },
trashListReplica: createReplicaState(),
});
-const ids = () =>
- useTrashStore.getState().trashListMap[trashListKey()]?.items.map((i) => i.id) ?? [];
+const ids = (filter: TrashViewFilter = {}) =>
+ useTrashStore.getState().trashListMap[trashListKey(filter)]?.items.map((i) => i.id) ?? [];
+
+const syncKey = (name: string, key: string) => ['replica:sync', name, 2, 'u1:personal', key, {}];
describe('TrashAction', () => {
beforeEach(() => {
@@ -102,12 +105,8 @@ describe('TrashAction', () => {
.mocked(mutate)
.mock.calls.map(([key]) => key as (k: unknown) => boolean);
// The list + the counts revalidate for the active identity.
- expect(
- predicates.some((p) => p(['replica:sync', 'trashList', 1, 'u1:personal', 'all', {}])),
- ).toBe(true);
- expect(
- predicates.some((p) => p(['replica:sync', 'trashCount', 1, 'u1:personal', 'all', {}])),
- ).toBe(true);
+ expect(predicates.some((p) => p(syncKey('trashList', trashListKey())))).toBe(true);
+ expect(predicates.some((p) => p(syncKey('trashCount', 'all')))).toBe(true);
// …plus a filter-based sweep of the namespaces a restore can repopulate.
const restored = predicates.find((p) => p(['topic:list', 'x', {}]) === true)!;
expect(restored).toBeTruthy();
@@ -130,9 +129,7 @@ describe('TrashAction', () => {
const predicates = vi
.mocked(mutate)
.mock.calls.map(([key]) => key as (k: unknown) => boolean);
- expect(
- predicates.some((p) => p(['replica:sync', 'trashList', 1, 'u1:personal', 'all', {}])),
- ).toBe(true);
+ expect(predicates.some((p) => p(syncKey('trashList', trashListKey())))).toBe(true);
expect(predicates.some((p) => p(['topic:list', 'x', {}]))).toBe(false);
});
@@ -159,12 +156,14 @@ describe('TrashAction', () => {
expect(ids()).toEqual(['trash_2']);
});
- it('emptyTrash honours the active type filter and clears the list', async () => {
+ it('emptyTrash sweeps the given view in the scope it started in and clears it', async () => {
vi.mocked(trashService.emptyTrash).mockResolvedValue({ hasMore: false, purged: 2 });
- seed([buildItem({ id: 'topic_only', resourceType: 'topic' })], 'topic');
- await useTrashStore.getState().emptyTrash();
- expect(trashService.emptyTrash).toHaveBeenCalledWith('topic');
- expect(useTrashStore.getState().trashListMap[trashListKey('topic')]?.items).toEqual([]);
+ const filter = { projectId: 'proj_a', resourceType: 'topic' } as const;
+ seed([buildItem({ id: 'topic_only', resourceType: 'topic' })], filter);
+ await useTrashStore.getState().emptyTrash(filter);
+ // `null`: the personal scope (no active workspace in the community build).
+ expect(trashService.emptyTrash).toHaveBeenCalledWith(filter, null);
+ expect(ids(filter)).toEqual([]);
});
it('emptyTrash keeps calling while the server reports more batches', async () => {
@@ -172,31 +171,140 @@ describe('TrashAction', () => {
.mockResolvedValueOnce({ hasMore: true, purged: 50 })
.mockResolvedValueOnce({ hasMore: true, purged: 50 })
.mockResolvedValueOnce({ hasMore: false, purged: 7 });
- await useTrashStore.getState().emptyTrash();
+ await useTrashStore.getState().emptyTrash({});
expect(trashService.emptyTrash).toHaveBeenCalledTimes(3);
expect(ids()).toEqual([]);
});
+
+ it('emptyTrash keeps every batch on the view it started with when the view switches', async () => {
+ const started = { projectId: 'proj_a' } as const;
+ useTrashStore.setState({
+ trashListMap: {
+ [trashListKey(started)]: view([buildItem({ id: 'in_a' })]),
+ // The same root also sits under "All"; an unrelated project's row stays.
+ [trashListKey()]: view([buildItem({ id: 'in_a' }), buildItem({ id: 'in_b' })]),
+ [trashListKey({ projectId: 'proj_b' })]: view([buildItem({ id: 'in_b' })]),
+ },
+ });
+ vi.mocked(trashService.emptyTrash)
+ .mockImplementationOnce(async () => {
+ // The user switches to another project (and type) while batches run.
+ useTrashStore
+ .getState()
+ .setFilter({ projectId: null, resourceType: 'agent' }, 'u1:personal');
+ return { hasMore: true, purged: 50 };
+ })
+ .mockResolvedValueOnce({ hasMore: false, purged: 1 });
+
+ await useTrashStore.getState().emptyTrash(started);
+
+ expect(vi.mocked(trashService.emptyTrash).mock.calls).toEqual([
+ [started, null],
+ [started, null],
+ ]);
+ // No view keeps rows the sweep may have reached; each reloads when shown.
+ expect(ids(started)).toEqual([]);
+ expect(ids()).toEqual([]);
+ expect(ids({ projectId: 'proj_b' })).toEqual([]);
+ });
+
+ it('drops the cached counts of other views after a write, and their rows after a sweep', async () => {
+ const active = { projectId: 'proj_a' } as const;
+ const other = { projectId: 'proj_b' } as const;
+ useTrashStore.setState({
+ projectSelection: { projectId: 'proj_a', scope: 'u1:personal' },
+ trashCountMap: {
+ 'all': { topic: 9 },
+ 'project:proj_a': { topic: 1 },
+ 'project:proj_b': { topic: 4 },
+ },
+ trashListMap: {
+ [trashListKey(active)]: view([buildItem({ id: 'in_a' })]),
+ [trashListKey(other)]: view([buildItem({ id: 'in_b' })]),
+ },
+ });
+ vi.mocked(trashService.purge).mockResolvedValue({ purged: 1 });
+
+ await useTrashStore.getState().purge(['in_a']);
+ // Other views' counts are unknown now (not stale numbers); their rows stay.
+ expect(Object.keys(useTrashStore.getState().trashCountMap)).toEqual(['project:proj_a']);
+ expect(ids(other)).toEqual(['in_b']);
+
+ vi.mocked(trashService.emptyTrash).mockResolvedValue({ hasMore: false, purged: 1 });
+ await useTrashStore.getState().emptyTrash(active);
+ expect(Object.keys(useTrashStore.getState().trashListMap)).toEqual([trashListKey(active)]);
+ });
+
+ it('emptyTrash stops, without touching the new scope, when the scope switches mid-sweep', async () => {
+ let scope = 'u1:personal';
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ seed([buildItem()], { projectId: null });
+ vi.mocked(trashService.emptyTrash).mockImplementationOnce(async () => {
+ scope = 'u1:ws_2';
+ return { hasMore: true, purged: 50 };
+ });
+
+ await expect(useTrashStore.getState().emptyTrash({ projectId: null })).rejects.toBeInstanceOf(
+ TrashEmptyScopeChangedError,
+ );
+ expect(trashService.emptyTrash).toHaveBeenCalledTimes(1);
+ expect(useTrashStore.getState().loadingIds).toEqual([]);
+ vi.restoreAllMocks();
+ });
});
describe('filter / refresh', () => {
- it('setActiveType switches the active filter without dropping loaded views', () => {
- useTrashStore.getState().setActiveType('agent');
+ it('setFilter switches the view without dropping the other loaded views', () => {
+ useTrashStore.getState().setFilter({ resourceType: 'agent' }, 'u1:personal');
expect(useTrashStore.getState().activeType).toBe('agent');
- // The previous filter's page is still there — switching back is instant.
+ // The previous view's page is still there — switching back is instant.
expect(ids()).toEqual(['trash_1', 'trash_2']);
});
+ it('setFilter restarts the view it switches to from its head page', () => {
+ const project = { projectId: 'proj_a' } as const;
+ useTrashStore.setState({
+ trashListMap: {
+ [trashListKey(project)]: {
+ currentPage: 1,
+ hasMore: false,
+ items: [buildItem({ id: 'head' }), buildItem({ id: 'older' })],
+ nextCursor: null,
+ pageSize: 1,
+ pages: [
+ { count: 1, next: 'cursor-1' },
+ { count: 1, next: null },
+ ],
+ },
+ },
+ });
+
+ useTrashStore.getState().setFilter(project, 'u1:personal');
+
+ const list = useTrashStore.getState().trashListMap[trashListKey(project)];
+ expect(list?.items.map((item) => item.id)).toEqual(['head']);
+ expect(list?.currentPage).toBe(0);
+ expect(list?.nextCursor).toBe('cursor-1');
+ });
+
+ it('binds a project filter to the scope it was chosen in', () => {
+ useTrashStore.getState().setFilter({ projectId: 'proj_a' }, 'u1:personal');
+ const state = useTrashStore.getState();
+ expect(trashSelectors.activeProjectId('u1:personal')(state)).toBe('proj_a');
+ // Another workspace (or account) starts on every project, not on a foreign id.
+ expect(trashSelectors.activeProjectId('u1:ws_2')(state)).toBeUndefined();
+
+ useTrashStore.getState().setFilter({ projectId: null }, 'u1:personal');
+ expect(trashSelectors.activeProjectId('u1:personal')(useTrashStore.getState())).toBeNull();
+ });
+
it('refresh revalidates the list(s) and the counts', async () => {
await useTrashStore.getState().refresh();
const predicates = vi
.mocked(mutate)
.mock.calls.map(([key]) => key as (k: unknown) => boolean);
- expect(
- predicates.some((p) => p(['replica:sync', 'trashList', 1, 'u1:personal', 'all', {}])),
- ).toBe(true);
- expect(
- predicates.some((p) => p(['replica:sync', 'trashCount', 1, 'u1:personal', 'all', {}])),
- ).toBe(true);
+ expect(predicates.some((p) => p(syncKey('trashList', trashListKey())))).toBe(true);
+ expect(predicates.some((p) => p(syncKey('trashCount', 'all')))).toBe(true);
});
});
});
diff --git a/src/store/trash/action.ts b/src/store/trash/action.ts
index 715b2b9d955..fedf60f4fe9 100644
--- a/src/store/trash/action.ts
+++ b/src/store/trash/action.ts
@@ -1,18 +1,21 @@
-import type { TrashCountByType, TrashItem, TrashResourceType } from '@lobechat/types';
+import type { TrashCountByType, TrashItem, TrashProjectFilter } from '@lobechat/types';
+import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import {
+ cacheScope,
createReplicaSlice,
recordLens,
type ReplicaPageResult,
type ReplicaSyncResult,
} from '@/libs/replica';
import { mutate } from '@/libs/swr';
-import { trashService } from '@/services/trash';
+import { trashService, type TrashViewFilter } from '@/services/trash';
import type { StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
import type { TrashListData } from './initialState';
import {
+ trashCountKey,
trashCountResource,
trashListKey,
type TrashListParams,
@@ -48,7 +51,17 @@ const RESTORE_AFFECTED_KEY_PREFIXES = [
'video:',
];
-const COUNT_PARAMS = {} as Record<string, never>;
+/**
+ * "Empty trash" stopped because the user switched to another scope (account /
+ * workspace) while it was running. Every batch already sent ran in the scope
+ * the sweep started in; nothing was purged anywhere else.
+ */
+export class TrashEmptyScopeChangedError extends Error {
+ constructor() {
+ super('The active scope changed while emptying the trash');
+ this.name = 'TrashEmptyScopeChangedError';
+ }
+}
export const trashSlice = (set: Setter, get: () => TrashStore, _api?: unknown) =>
new TrashActionImpl(set, get, _api);
@@ -79,7 +92,7 @@ export class TrashActionImpl {
});
this.#trashCount = createReplicaSlice(trashCountResource, {
actionPrefix: n('trashCount'),
- fetcher: () => trashService.countByType(),
+ fetcher: ({ projectId }) => trashService.countByType(projectId),
get,
set,
stateKey: 'trashCountReplica',
@@ -89,18 +102,29 @@ export class TrashActionImpl {
/** One recycle-bin page: `cursor` undefined = the head (newest first). */
#fetchPage = async (
- { resourceType }: TrashListParams,
+ { projectId, resourceType }: TrashListParams,
cursor?: string,
): Promise<ReplicaPageResult<TrashItem, string>> => {
const { items, nextCursor } = await trashService.list(
- cursor ? { cursor, resourceType } : { resourceType },
+ cursor ? { cursor, projectId, resourceType } : { projectId, resourceType },
);
return { items, nextCursor };
};
- /** Switching filter just selects another already-keyed view; no reset needed. */
- setActiveType = (activeType?: TrashResourceType) => {
- this.#set({ activeType }, false, n('setActiveType'));
+ /**
+ * Switch the view. Each view is its own keyed entry, so a late response for
+ * the previous one lands in that entry and never repaints this one; the
+ * entry switched to starts again from its head page instead of the pages
+ * loaded on an earlier visit. `scope` binds the project to the scope it was
+ * chosen in (see `trashSelectors.activeProjectId`).
+ */
+ setFilter = ({ projectId, resourceType }: TrashViewFilter, scope: string) => {
+ this.#set(
+ { activeType: resourceType, projectSelection: { projectId, scope } },
+ false,
+ n('setFilter'),
+ );
+ this.#trashList.collapse(trashListKey({ projectId, resourceType }));
};
/** Re-fetch the list(s) and the counts of the active identity. */
@@ -124,10 +148,9 @@ export class TrashActionImpl {
);
};
- /** Next page of the active filter, using the loaded head page's params. */
- loadMore = async () => {
- const { activeType } = this.#get();
- await this.#trashList.loadMore(trashListKey(activeType), { resourceType: activeType });
+ /** Next page of one view, using its loaded head page's params. */
+ loadMore = async (filter: TrashViewFilter) => {
+ await this.#trashList.loadMore(trashListKey(filter), filter);
};
/** Drop a row from every loaded filter (the engine also patches persisted rows). */
@@ -135,7 +158,34 @@ export class TrashActionImpl {
for (const id of ids) this.#trashList.updateEntity(id, () => undefined);
};
- #withLoading = async (ids: string[], run: () => Promise<void>) => {
+ /**
+ * After a write, the counts of every view but the one on screen are stale,
+ * and so are their rows after a sweep (it reaches past the loaded pages).
+ * Drop them, memory and persisted copy, so a later visit loads them instead
+ * of painting numbers or rows that no longer exist. The view on screen is
+ * revalidated in place by `refresh`.
+ */
+ #dropOtherViews = ({ rows }: { rows: boolean }) => {
+ const { activeType, projectSelection, trashCountMap, trashListMap } = this.#get();
+ const projectId =
+ projectSelection?.scope === cacheScope.get() ? projectSelection.projectId : undefined;
+ const countKey = trashCountKey(projectId);
+ for (const key of Object.keys(trashCountMap)) {
+ if (key !== countKey) this.#trashCount.remove(key);
+ }
+ if (!rows) return;
+ const listKey = trashListKey({ projectId, resourceType: activeType });
+ for (const key of Object.keys(trashListMap)) {
+ if (key !== listKey) this.#trashList.remove(key);
+ }
+ };
+
+ #withLoading = async (
+ ids: string[],
+ run: () => Promise<void>,
+ { sweep = false }: { sweep?: boolean } = {},
+ ) => {
+ const scope = cacheScope.get();
this.#set({ loadingIds: [...this.#get().loadingIds, ...ids] }, false, n('loading/start'));
try {
await run();
@@ -146,6 +196,8 @@ export class TrashActionImpl {
false,
n('loading/end'),
);
+ // Views of another scope are not ours to drop (a switch resets them anyway).
+ if (cacheScope.get() === scope) this.#dropOtherViews({ rows: sweep });
await this.refresh();
}
};
@@ -175,46 +227,63 @@ export class TrashActionImpl {
});
};
- emptyTrash = async () => {
- const { activeType, trashListMap } = this.#get();
- const key = trashListKey(activeType);
- const ids = trashListMap[key]?.items.map((item) => item.id) ?? [];
- await this.#withLoading(ids, 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;
- }
- // The filter is swept server-side across every page, so the whole view
- // collapses to an empty head page rather than dropping only loaded rows.
- this.#trashList.update(key, (data) =>
- data
- ? {
- ...data,
- currentPage: 0,
- hasMore: false,
- items: [],
- nextCursor: null,
- pages: [{ count: 0, next: null }],
- total: 0,
- }
- : data,
- );
- });
+ /**
+ * Purge every root `filter` covers, across all pages, in the scope the call
+ * starts in. The filter and scope are fixed for the whole sweep: switching
+ * the view (or the workspace) while batches run never widens what is
+ * purged — a scope switch stops the sweep with `TrashEmptyScopeChangedError`.
+ */
+ emptyTrash = async (filter: TrashViewFilter) => {
+ const scope = cacheScope.get();
+ const workspaceId = getActiveWorkspaceId();
+ const key = trashListKey(filter);
+ const ids = this.#get().trashListMap[key]?.items.map((item) => item.id) ?? [];
+ await this.#withLoading(
+ ids,
+ 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 (;;) {
+ if (cacheScope.get() !== scope) throw new TrashEmptyScopeChangedError();
+ const { hasMore } = await trashService.emptyTrash(filter, workspaceId);
+ if (!hasMore) break;
+ }
+ // The view lives in the scope the sweep ran in; do not touch another's.
+ if (cacheScope.get() !== scope) return;
+ // Its rows are gone from every other loaded view too (the same root can
+ // sit under "All", its type and its project).
+ this.#dropRows(ids);
+ // The view is swept server-side across every page, so it collapses to an
+ // empty head page rather than dropping only loaded rows.
+ this.#trashList.update(key, (data) =>
+ data
+ ? {
+ ...data,
+ currentPage: 0,
+ hasMore: false,
+ items: [],
+ nextCursor: null,
+ pages: [{ count: 0, next: null }],
+ total: 0,
+ }
+ : data,
+ );
+ },
+ { sweep: true },
+ );
};
/**
- * Fetch orchestration for one filter's recycle-bin page. Hydrates the
+ * Fetch orchestration for one view's recycle-bin page. Hydrates the
* persisted projection, then revalidates; rows land in `trashListMap` — read
* them through `trashSelectors`, never from this hook.
*/
- useFetchTrash = (enabled: boolean, resourceType?: TrashResourceType): ReplicaSyncResult =>
- this.#trashList.useSync(enabled ? { resourceType } : null);
+ useFetchTrash = (enabled: boolean, filter: TrashViewFilter): ReplicaSyncResult =>
+ this.#trashList.useSync(enabled ? filter : null);
- /** Fetch orchestration for the per-type counts; read them via `trashSelectors`. */
- useFetchTrashCount = (enabled: boolean): ReplicaSyncResult =>
- this.#trashCount.useSync(enabled ? COUNT_PARAMS : null);
+ /** Fetch orchestration for one project filter's per-type counts; read them via `trashSelectors`. */
+ useFetchTrashCount = (enabled: boolean, projectId?: TrashProjectFilter): ReplicaSyncResult =>
+ this.#trashCount.useSync(enabled ? { projectId } : null);
}
export type TrashAction = Pick<TrashActionImpl, keyof TrashActionImpl>;
diff --git a/src/store/trash/initialState.ts b/src/store/trash/initialState.ts
index 2dc1b42f1b5..9f2e8e7504c 100644
--- a/src/store/trash/initialState.ts
+++ b/src/store/trash/initialState.ts
@@ -1,20 +1,38 @@
-import type { TrashCountByType, TrashItem, TrashResourceType } from '@lobechat/types';
+import type {
+ TrashCountByType,
+ TrashItem,
+ TrashProjectFilter,
+ TrashResourceType,
+} from '@lobechat/types';
import { createReplicaState, type ReplicaPagedData, type ReplicaState } from '@/libs/replica';
-/** One type-filter's recycle-bin page: the generic local-first paged view. */
+/** One recycle-bin view's page: the generic local-first paged view. */
export type TrashListData = ReplicaPagedData<TrashItem, string>;
+/**
+ * The project filter and the cache scope (user + workspace) it was chosen in.
+ * A project belongs to one scope, so the filter only applies there: after a
+ * scope switch the bin opens on every project instead of asking another scope
+ * for a project it does not have.
+ */
+export interface TrashProjectSelection {
+ projectId: TrashProjectFilter;
+ scope: string;
+}
+
export interface TrashState {
/** Type filter the recycle-bin page is currently showing (`undefined` = everything). */
activeType?: TrashResourceType;
/** Registry ids with an in-flight restore / purge — drives per-row spinners. */
loadingIds: string[];
- /** Per-type counts (`trashCountMap.all`): the filter chips and the empty total. */
+ /** Project filter, bound to its scope (`undefined` = every project). */
+ projectSelection?: TrashProjectSelection;
+ /** Per-type counts per project filter (`trashCountMap[trashCountKey(projectId)]`). */
trashCountMap: Record<string, TrashCountByType>;
/** Local-first bookkeeping for `trashCountMap`. */
trashCountReplica: ReplicaState<TrashCountByType>;
- /** Recycle-bin rows per filter (`trashListMap[resourceType ?? 'all']`). */
+ /** Recycle-bin rows per view (`trashListMap[trashListKey(filter)]`). */
trashListMap: Record<string, TrashListData>;
/** Local-first bookkeeping for `trashListMap`. */
trashListReplica: ReplicaState<TrashListData>;
@@ -23,6 +41,7 @@ export interface TrashState {
export const initialState: TrashState = {
activeType: undefined,
loadingIds: [],
+ projectSelection: undefined,
trashCountMap: {},
trashCountReplica: createReplicaState(),
trashListMap: {},
diff --git a/src/store/trash/projection.ts b/src/store/trash/projection.ts
index 24858b8bbd4..4d4c70d07a5 100644
--- a/src/store/trash/projection.ts
+++ b/src/store/trash/projection.ts
@@ -1,22 +1,36 @@
-import type { TrashCountByType, TrashItem, TrashResourceType } from '@lobechat/types';
+import type { TrashCountByType, TrashItem, TrashProjectFilter } from '@lobechat/types';
import { definePagedReplica, defineReplica } from '@/libs/replica';
+import type { TrashViewFilter } from '@/services/trash';
import type { TrashListData } from './initialState';
-export interface TrashListParams {
- resourceType?: TrashResourceType;
+export type TrashListParams = TrashViewFilter;
+
+export interface TrashCountParams {
+ projectId?: TrashProjectFilter;
}
-/** Entry key of the "everything" filter — not a `TrashResourceType`, so it never collides. */
+/** Key segment of the "everything" filter — not a type or a project id, so it never collides. */
export const TRASH_ALL_KEY = 'all';
-/** Entry key of one recycle-bin filter (`trashListMap[resourceType ?? 'all']`). */
-export const trashListKey = (resourceType?: TrashResourceType): string =>
- resourceType ?? TRASH_ALL_KEY;
+/** Key segment of a project filter: every project, no project, or one project. */
+export const trashProjectKey = (projectId?: TrashProjectFilter): string =>
+ projectId === undefined ? TRASH_ALL_KEY : projectId === null ? 'none' : `project:${projectId}`;
+
+/**
+ * Entry key of one recycle-bin view (`trashListMap[key]`): every dimension the
+ * server filters on. The scope (user + workspace) partitions the replica
+ * itself, and the acting member is the scope's user.
+ */
+export const trashListKey = ({ projectId, resourceType }: TrashListParams = {}): string =>
+ `${resourceType ?? TRASH_ALL_KEY}|${trashProjectKey(projectId)}`;
+
+/** Entry key of the per-type counts under one project filter (`trashCountMap[key]`). */
+export const trashCountKey = (projectId?: TrashProjectFilter): string => trashProjectKey(projectId);
/**
- * Recycle-bin rows, one local-first entry per type filter (`trashListMap[key]`).
+ * Recycle-bin rows, one local-first entry per view (`trashListMap[key]`).
*
* The server pages by an opaque cursor over `(deleted_at, id)`, newest first,
* so the view walks `nextCursor` forward. Rows are read through
@@ -28,7 +42,7 @@ export const trashListResource = definePagedReplica<
string,
TrashListData
>({
- key: ({ resourceType }) => trashListKey(resourceType),
+ key: trashListKey,
name: 'trashList',
paging: {
direction: 'forward',
@@ -38,13 +52,15 @@ export const trashListResource = definePagedReplica<
persist: { pages: 1 },
},
storage: 'indexedDB',
- version: 1,
+ // v2: entries are keyed by type and project.
+ version: 2,
});
-/** Per-type counts (`trashCountMap.all`) that drive the filter chips and empty total. */
-export const trashCountResource = defineReplica<Record<string, never>, TrashCountByType>({
- key: () => TRASH_ALL_KEY,
+/** Per-type counts of one project filter: the type chips, the totals and the empty-trash scope. */
+export const trashCountResource = defineReplica<TrashCountParams, TrashCountByType>({
+ key: ({ projectId }) => trashCountKey(projectId),
name: 'trashCount',
storage: 'indexedDB',
- version: 1,
+ // v2: entries are keyed by project.
+ version: 2,
});
diff --git a/src/store/trash/replica.test.ts b/src/store/trash/replica.test.ts
index 679b2a763e0..049bcbb969d 100644
--- a/src/store/trash/replica.test.ts
+++ b/src/store/trash/replica.test.ts
@@ -7,7 +7,7 @@
*/
import { randomUUID } from 'node:crypto';
-import type { TrashItem, TrashListParams } from '@lobechat/types';
+import type { TrashItem, TrashListParams, TrashProjectFilter } from '@lobechat/types';
import { act, renderHook, waitFor } from '@testing-library/react';
import type { PropsWithChildren } from 'react';
import { createElement, useEffect } from 'react';
@@ -20,7 +20,7 @@ import { trashService } from '@/services/trash';
import type { TrashListData } from './initialState';
import { initialState } from './initialState';
-import { trashCountResource, trashListKey, trashListResource } from './projection';
+import { trashCountKey, trashCountResource, trashListKey, trashListResource } from './projection';
import { trashSelectors } from './selectors';
import { useTrashStore } from './store';
@@ -82,17 +82,32 @@ const pending = () => new Promise<never>(() => {});
/** Route `trashService.list` by the requested filter. */
const listFor = (
- byType: (resourceType: TrashItem['resourceType'] | undefined) => {
+ byType: (
+ resourceType: TrashItem['resourceType'] | undefined,
+ projectId: TrashProjectFilter,
+ ) => {
items: TrashItem[];
nextCursor: string | null;
},
) =>
vi
.mocked(trashService.list)
- .mockImplementation(async (params?: TrashListParams) => byType(params?.resourceType));
+ .mockImplementation(async (params?: Omit<TrashListParams, 'deletedByUserId'>) =>
+ byType(params?.resourceType, params?.projectId),
+ );
-const itemIds = (resourceType?: TrashItem['resourceType']) =>
- useTrashStore.getState().trashListMap[trashListKey(resourceType)]?.items.map((i) => i.id);
+const itemIds = (resourceType?: TrashItem['resourceType'], projectId?: TrashProjectFilter) =>
+ useTrashStore
+ .getState()
+ .trashListMap[trashListKey({ projectId, resourceType })]?.items.map((i) => i.id);
+
+const deferred = <T>() => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+};
describe('trash replicas', () => {
const scopes = new Set<string>();
@@ -107,6 +122,7 @@ describe('trash replicas', () => {
const storageKeyOf = (resourceType?: TrashItem['resourceType']) =>
trashListResource.storageKey({ resourceType });
+ const projectKeys: TrashProjectFilter[] = [undefined, null, 'proj_a', 'proj_b'];
beforeEach(() => {
useScope(`trash-user-${randomUUID()}:personal`);
@@ -117,11 +133,19 @@ describe('trash replicas', () => {
afterEach(async () => {
await Promise.all(
- [...scopes].flatMap((value) => [
- trashListResource.storage!.remove({ queryKey: trashListKey(), scope: value }),
- trashListResource.storage!.remove({ queryKey: trashListKey('topic'), scope: value }),
- trashCountResource.storage!.remove({ queryKey: trashListKey(), scope: value }),
- ]),
+ [...scopes].flatMap((value) =>
+ projectKeys.flatMap((projectId) => [
+ trashListResource.storage!.remove({
+ queryKey: trashListKey({ projectId }),
+ scope: value,
+ }),
+ trashListResource.storage!.remove({
+ queryKey: trashListKey({ projectId, resourceType: 'topic' }),
+ scope: value,
+ }),
+ trashCountResource.storage!.remove({ queryKey: trashCountKey(projectId), scope: value }),
+ ]),
+ ),
);
scopes.clear();
vi.restoreAllMocks();
@@ -135,8 +159,8 @@ describe('trash replicas', () => {
);
vi.mocked(trashService.list).mockImplementation(pending);
- const sync = renderHook(() => useTrashStore((s) => s.useFetchTrash)(true), { wrapper });
- const list = renderHook(() => useTrashStore(trashSelectors.currentList(undefined)));
+ const sync = renderHook(() => useTrashStore((s) => s.useFetchTrash)(true, {}), { wrapper });
+ const list = renderHook(() => useTrashStore(trashSelectors.currentList({})));
await waitFor(() => expect(list.result.current?.items.map((i) => i.title)).toEqual(['Cached']));
expect(sync.result.current.isHydrated).toBe(true);
@@ -149,7 +173,7 @@ describe('trash replicas', () => {
nextCursor: null,
});
- renderHook(() => useTrashStore((s) => s.useFetchTrash)(true), { wrapper });
+ renderHook(() => useTrashStore((s) => s.useFetchTrash)(true, {}), { wrapper });
await waitFor(() => expect(itemIds()).toEqual(['t1']));
await waitFor(async () =>
@@ -167,8 +191,10 @@ describe('trash replicas', () => {
: { items: [item('agent_1', 'An agent', 'agent')], nextCursor: null },
);
- renderHook(() => useTrashStore((s) => s.useFetchTrash)(true, 'topic'), { wrapper });
- renderHook(() => useTrashStore((s) => s.useFetchTrash)(true), { wrapper });
+ renderHook(() => useTrashStore((s) => s.useFetchTrash)(true, { resourceType: 'topic' }), {
+ wrapper,
+ });
+ renderHook(() => useTrashStore((s) => s.useFetchTrash)(true, {}), { wrapper });
await waitFor(() => expect(itemIds('topic')).toEqual(['topic_1']));
await waitFor(() => expect(itemIds()).toEqual(['agent_1']));
@@ -179,19 +205,20 @@ describe('trash replicas', () => {
.mockResolvedValueOnce({ items: [item('t1'), item('t2')], nextCursor: 'cursor-1' })
.mockResolvedValueOnce({ items: [item('t3')], nextCursor: null });
- renderHook(() => useTrashStore((s) => s.useFetchTrash)(true), { wrapper });
+ renderHook(() => useTrashStore((s) => s.useFetchTrash)(true, {}), { wrapper });
await waitFor(() =>
- expect(useTrashStore.getState().trashListMap.all?.nextCursor).toBe('cursor-1'),
+ expect(useTrashStore.getState().trashListMap[trashListKey()]?.nextCursor).toBe('cursor-1'),
);
- await act(() => useTrashStore.getState().loadMore());
+ await act(() => useTrashStore.getState().loadMore({}));
expect(trashService.list).toHaveBeenLastCalledWith({
cursor: 'cursor-1',
+ projectId: undefined,
resourceType: undefined,
});
expect(itemIds()).toEqual(['t1', 't2', 't3']);
- expect(useTrashStore.getState().trashListMap.all?.nextCursor).toBeNull();
+ expect(useTrashStore.getState().trashListMap[trashListKey()]?.nextCursor).toBeNull();
});
it('drops a restored row from the loaded view', async () => {
@@ -199,7 +226,7 @@ describe('trash replicas', () => {
items: [item('t1'), item('t2')],
nextCursor: null,
});
- renderHook(() => useTrashStore((s) => s.useFetchTrash)(true), { wrapper });
+ renderHook(() => useTrashStore((s) => s.useFetchTrash)(true, {}), { wrapper });
await waitFor(() => expect(itemIds()).toEqual(['t1', 't2']));
vi.mocked(trashService.restore).mockResolvedValue({ failed: [], restored: [item('t1')] });
@@ -224,8 +251,8 @@ describe('trash replicas', () => {
renderHook(
() => {
- useTrashStore((s) => s.useFetchTrash)(true, 'topic');
- useTrashStore((s) => s.useFetchTrash)(true);
+ useTrashStore((s) => s.useFetchTrash)(true, { resourceType: 'topic' });
+ useTrashStore((s) => s.useFetchTrash)(true, {});
},
{ wrapper },
);
@@ -254,15 +281,17 @@ describe('trash replicas', () => {
nextCursor: null,
});
act(() => useTrashStore.setState({ activeType: 'topic' }));
- renderHook(() => useTrashStore((s) => s.useFetchTrash)(true, 'topic'), { wrapper });
+ renderHook(() => useTrashStore((s) => s.useFetchTrash)(true, { resourceType: 'topic' }), {
+ wrapper,
+ });
await waitFor(() => expect(itemIds('topic')).toEqual(['t1']));
vi.mocked(trashService.emptyTrash).mockResolvedValue({ hasMore: false, purged: 1 });
vi.mocked(trashService.list).mockResolvedValue({ items: [], nextCursor: null });
- await act(() => useTrashStore.getState().emptyTrash());
+ await act(() => useTrashStore.getState().emptyTrash({ resourceType: 'topic' }));
- expect(trashService.emptyTrash).toHaveBeenCalledWith('topic');
+ expect(trashService.emptyTrash).toHaveBeenCalledWith({ resourceType: 'topic' }, null);
expect(itemIds('topic')).toEqual([]);
});
@@ -275,13 +304,13 @@ describe('trash replicas', () => {
);
vi.mocked(trashService.list).mockImplementation(pending);
- renderHook(() => useTrashStore((s) => s.useFetchTrash)(true), { wrapper });
+ renderHook(() => useTrashStore((s) => s.useFetchTrash)(true, {}), { wrapper });
// Give hydration a chance to (wrongly) land, then assert the view is empty.
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 20));
});
- expect(useTrashStore.getState().trashListMap.all).toBeUndefined();
+ expect(useTrashStore.getState().trashListMap[trashListKey()]).toBeUndefined();
});
it('drops the previous identity’s list before the next one paints', async () => {
@@ -289,26 +318,98 @@ describe('trash replicas', () => {
items: [item('t1', 'Mine')],
nextCursor: null,
});
- const sync = renderHook(() => useTrashStore((s) => s.useFetchTrash)(true), { wrapper });
+ const sync = renderHook(() => useTrashStore((s) => s.useFetchTrash)(true, {}), { wrapper });
await waitFor(() => expect(itemIds()).toEqual(['t1']));
vi.mocked(trashService.list).mockImplementation(pending);
useScope(`trash-user-${randomUUID()}:personal`);
sync.rerender();
- await waitFor(() => expect(useTrashStore.getState().trashListMap.all).toBeUndefined());
+ await waitFor(() =>
+ expect(useTrashStore.getState().trashListMap[trashListKey()]).toBeUndefined(),
+ );
+ });
+
+ it('keys every project filter as its own view and asks the server for it', async () => {
+ listFor((_, projectId) => ({
+ items: [item(projectId === undefined ? 'all' : projectId === null ? 'none' : projectId)],
+ nextCursor: null,
+ }));
+
+ renderHook(
+ () => {
+ useTrashStore((s) => s.useFetchTrash)(true, {});
+ useTrashStore((s) => s.useFetchTrash)(true, { projectId: null });
+ useTrashStore((s) => s.useFetchTrash)(true, { projectId: 'proj_a' });
+ },
+ { wrapper },
+ );
+
+ await waitFor(() => expect(itemIds(undefined, 'proj_a')).toEqual(['proj_a']));
+ expect(itemIds(undefined, null)).toEqual(['none']);
+ expect(itemIds()).toEqual(['all']);
+ expect(vi.mocked(trashService.list).mock.calls.map(([params]) => params?.projectId)).toEqual(
+ expect.arrayContaining([undefined, null, 'proj_a']),
+ );
+ });
+
+ it('a late response for the previous project never repaints the current one', async () => {
+ const slow = deferred<{ items: TrashItem[]; nextCursor: string | null }>();
+ listFor((_, projectId) =>
+ projectId === 'proj_a' ? (slow.promise as never) : { items: [item('b1')], nextCursor: null },
+ );
+
+ const { rerender } = renderHook(
+ ({ projectId }: { projectId: TrashProjectFilter }) =>
+ useTrashStore((s) => s.useFetchTrash)(true, { projectId }),
+ { initialProps: { projectId: 'proj_a' as TrashProjectFilter }, wrapper },
+ );
+ rerender({ projectId: 'proj_b' });
+ await waitFor(() => expect(itemIds(undefined, 'proj_b')).toEqual(['b1']));
+
+ await act(async () => {
+ slow.resolve({ items: [item('a1')], nextCursor: null });
+ await slow.promise;
+ });
+
+ // The late page belongs to project A's own entry; B's view is untouched.
+ expect(itemIds(undefined, 'proj_b')).toEqual(['b1']);
+ expect(itemIds(undefined, 'proj_a') ?? []).not.toContain('b1');
});
describe('selectors', () => {
- it('totalCount sums the per-type counts', async () => {
- vi.mocked(trashService.countByType).mockResolvedValue({ agent: 1, topic: 2 });
- renderHook(() => useTrashStore((s) => s.useFetchTrashCount)(true), { wrapper });
+ it('totalCount sums the per-type counts of one project filter', async () => {
+ vi.mocked(trashService.countByType).mockImplementation(async (projectId) =>
+ projectId === 'proj_a' ? { topic: 4 } : { agent: 1, topic: 2 },
+ );
+ renderHook(
+ () => {
+ useTrashStore((s) => s.useFetchTrashCount)(true);
+ useTrashStore((s) => s.useFetchTrashCount)(true, 'proj_a');
+ },
+ { wrapper },
+ );
await waitFor(() =>
- expect(useTrashStore.getState().trashCountMap.all).toEqual({ agent: 1, topic: 2 }),
+ expect(useTrashStore.getState().trashCountMap[trashCountKey()]).toEqual({
+ agent: 1,
+ topic: 2,
+ }),
+ );
+ await waitFor(() =>
+ expect(useTrashStore.getState().trashCountMap[trashCountKey('proj_a')]).toEqual({
+ topic: 4,
+ }),
);
- expect(trashSelectors.totalCount(useTrashStore.getState())).toBe(3);
- expect(trashSelectors.countByType(useTrashStore.getState())).toEqual({ agent: 1, topic: 2 });
+ const state = useTrashStore.getState();
+ expect(trashSelectors.totalCount()(state)).toBe(3);
+ expect(trashSelectors.countByType()(state)).toEqual({ agent: 1, topic: 2 });
+ expect(trashSelectors.filterCount({ projectId: 'proj_a' })(state)).toBe(4);
+ expect(
+ trashSelectors.filterCount({ projectId: 'proj_a', resourceType: 'agent' })(state),
+ ).toBe(0);
+ // Not loaded yet: unknown, never a confident zero.
+ expect(trashSelectors.filterCount({ projectId: null })(state)).toBeUndefined();
});
});
});
diff --git a/src/store/trash/selectors.ts b/src/store/trash/selectors.ts
index 5da8b11988e..71a05d60c3f 100644
--- a/src/store/trash/selectors.ts
+++ b/src/store/trash/selectors.ts
@@ -1,23 +1,54 @@
-import type { TrashResourceType } from '@lobechat/types';
+import type { TrashCountByType, TrashProjectFilter } from '@lobechat/types';
import type { TrashState } from './initialState';
-import { trashListKey } from './projection';
+import { trashCountKey, trashListKey, type TrashListParams } from './projection';
-/** The loaded page of one filter, or `undefined` before its first paint. */
-const currentList = (activeType?: TrashResourceType) => (s: TrashState) =>
- s.trashListMap[trashListKey(activeType)];
+/** The project filter that applies in `scope`; a selection made in another scope does not. */
+const activeProjectId =
+ (scope: string) =>
+ (s: TrashState): TrashProjectFilter =>
+ s.projectSelection?.scope === scope ? s.projectSelection.projectId : undefined;
-const countByType = (s: TrashState) => s.trashCountMap[trashListKey()] ?? {};
+/** The loaded page of one view, or `undefined` before its first paint. */
+const currentList = (filter: TrashListParams) => (s: TrashState) =>
+ s.trashListMap[trashListKey(filter)];
-const totalCount = (s: TrashState) =>
- Object.values(countByType(s)).reduce((sum, count) => sum + (count ?? 0), 0);
+/** Per-type counts of one project filter, or `undefined` before they first load. */
+const countByType =
+ (projectId?: TrashProjectFilter) =>
+ (s: TrashState): TrashCountByType | undefined =>
+ s.trashCountMap[trashCountKey(projectId)];
-/** The active filter's page is loaded and empty (not merely un-fetched). */
-const isEmpty = (activeType?: TrashResourceType) => (s: TrashState) => {
- const list = s.trashListMap[trashListKey(activeType)];
+const sumCounts = (counts: TrashCountByType | undefined) =>
+ Object.values(counts ?? {}).reduce((sum, count) => sum + (count ?? 0), 0);
+
+const totalCount = (projectId?: TrashProjectFilter) => (s: TrashState) =>
+ sumCounts(countByType(projectId)(s));
+
+/**
+ * Roots one view covers — what "empty" would purge — or `undefined` while
+ * its counts are not loaded yet.
+ */
+const filterCount = (filter: TrashListParams) => (s: TrashState) => {
+ const counts = countByType(filter.projectId)(s);
+ if (!counts) return undefined;
+ return filter.resourceType ? (counts[filter.resourceType] ?? 0) : sumCounts(counts);
+};
+
+/** The view's page is loaded and empty (not merely un-fetched). */
+const isEmpty = (filter: TrashListParams) => (s: TrashState) => {
+ const list = s.trashListMap[trashListKey(filter)];
return !!list && list.items.length === 0;
};
const isLoading = (id: string) => (s: TrashState) => s.loadingIds.includes(id);
-export const trashSelectors = { countByType, currentList, isEmpty, isLoading, totalCount };
+export const trashSelectors = {
+ activeProjectId,
+ countByType,
+ currentList,
+ filterCount,
+ isEmpty,
+ isLoading,
+ totalCount,
+};