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.

♻️ refactor(trash): move the recycle bin onto @lobechat/replica (#20609)

Arvin Xufe6f03078124
diff --git a/src/features/Settings/trash/features/TrashList.tsx b/src/features/Settings/trash/features/TrashList.tsx
index 7172faf20c9..9923813f2c6 100644
--- a/src/features/Settings/trash/features/TrashList.tsx
+++ b/src/features/Settings/trash/features/TrashList.tsx
@@ -1,7 +1,7 @@
'use client';
import { TRASH_RETENTION_DAYS } from '@lobechat/const';
-import type { TrashItem, TrashResourceType } from '@lobechat/types';
+import type { TrashCountByType, TrashItem, TrashResourceType } from '@lobechat/types';
import { Center, Empty, Flexbox, Icon } from '@lobehub/ui';
import { Avatar, Button, confirmModal, Segmented, Tag, Text, toast } from '@lobehub/ui/base-ui';
import { createStaticStyles } from 'antd-style';
@@ -18,6 +18,10 @@ import { TRASH_TYPE_ICON, TRASH_TYPE_ORDER } from './typeMeta';
dayjs.extend(relativeTime);
+/** Stable empties so the replicated views never trip the store's shallow equality. */
+const EMPTY_ITEMS: TrashItem[] = [];
+const EMPTY_COUNTS: TrashCountByType = {};
+
const styles = createStaticStyles(({ css, cssVar }) => ({
container: css`
overflow: hidden;
@@ -52,11 +56,8 @@ const TrashList = () => {
const mobile = useIsMobile();
const [
- items,
- nextCursor,
activeType,
countByType,
- isLoadingMore,
loadingIds,
setActiveType,
restore,
@@ -66,11 +67,8 @@ const TrashList = () => {
useFetchTrash,
useFetchTrashCount,
] = useTrashStore((s) => [
- s.items,
- s.nextCursor,
s.activeType,
- s.countByType,
- s.isLoadingMore,
+ s.trashCountMap.all ?? EMPTY_COUNTS,
s.loadingIds,
s.setActiveType,
s.restore,
@@ -80,12 +78,20 @@ const TrashList = () => {
s.useFetchTrash,
s.useFetchTrashCount,
]);
- const isEmpty = useTrashStore(trashSelectors.isEmpty);
+
+ // 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);
- const { error, isLoading, isValidating, mutate: retry } = useFetchTrash(true, activeType);
+ const { error, isValidating, revalidate } = useFetchTrash(true, activeType);
useFetchTrashCount(true);
+ const isLoading = !isEmpty && items.length === 0 && isValidating;
+
const typeLabel = (type: TrashResourceType) => t(`trash.type.${type}` as const);
// A rejected call (network / server) must not end in a silent spinner stop:
@@ -274,7 +280,7 @@ const TrashList = () => {
<LiteTable
columns={columns}
dataSource={items}
- loading={isLoading && !isEmpty && items.length === 0}
+ loading={isLoading}
rowKey={(item) => item.id}
emptyText={
<Center height={240} width={'100%'}>
@@ -283,7 +289,7 @@ const TrashList = () => {
description={t('trash.loadFailed.desc')}
title={t('trash.loadFailed.title')}
action={
- <Button loading={isValidating} size={'small'} onClick={() => retry()}>
+ <Button loading={isValidating} size={'small'} onClick={() => revalidate()}>
{tc('retry')}
</Button>
}
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 7e7fa4ad3d8..9d9bffa1a73 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -722,11 +722,6 @@ export const ragEvalKeys = {
};
// ---- device -------------------------------------------------------------
-export const trashKeys = {
- countByType: def('trash:countByType', () => ['trash:countByType']),
- list: def('trash:list', (resourceType?: string | null) => ['trash:list', resourceType ?? 'all']),
-};
-
export const deviceKeys = {
cliUpdateState: def('device:cliUpdateState', (workspaceId: string | null, deviceId: string) => [
'device:cliUpdateState',
@@ -1490,7 +1485,6 @@ export const swrKeys = {
documentComment: documentCommentKeys,
documentLike: documentLikeKeys,
topicAction: topicActionKeys,
- trash: trashKeys,
user: userKeys,
userMemory: userMemoryKeys,
verify: verifyKeys,
diff --git a/src/store/trash/action.test.ts b/src/store/trash/action.test.ts
index e4feca5ffbb..8df14215bd8 100644
--- a/src/store/trash/action.test.ts
+++ b/src/store/trash/action.test.ts
@@ -1,10 +1,21 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * Imperative recycle-bin behaviour: restore / purge / empty drop rows from the
+ * local-first views, per-row loading flags settle, and a restore revalidates
+ * the other stores' lists. The replica wiring itself is covered by
+ * `replica.test.ts`.
+ */
import type { TrashItem } from '@lobechat/types';
-import { renderHook } from '@testing-library/react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { mutate, useClientDataSWR } from '@/libs/swr';
+import { createReplicaState } from '@/libs/replica';
+import { mutate } from '@/libs/swr';
import { trashService } from '@/services/trash';
+import type { TrashListData } from './initialState';
+import { initialState } from './initialState';
+import { trashListKey } from './projection';
import { trashSelectors } from './selectors';
import { useTrashStore } from './store';
@@ -13,10 +24,20 @@ vi.mock('@/libs/swr', () => ({
useClientDataSWR: vi.fn(),
}));
-const scopeMock = vi.hoisted(() => ({ current: 'u1:personal' }));
vi.mock('@/libs/swr/useCacheScope', () => ({
- getCacheScope: () => scopeMock.current,
- useCacheScope: () => scopeMock.current,
+ getCacheScope: () => 'u1:personal',
+ isScopeTrusted: () => true,
+ useCacheScope: () => 'u1:personal',
+}));
+
+vi.mock('@/services/trash', () => ({
+ trashService: {
+ countByType: vi.fn(),
+ emptyTrash: vi.fn(),
+ list: vi.fn(),
+ purge: vi.fn(),
+ restore: vi.fn(),
+ },
}));
const buildItem = (overrides: Partial<TrashItem> = {}): TrashItem => ({
@@ -34,30 +55,39 @@ const buildItem = (overrides: Partial<TrashItem> = {}): TrashItem => ({
...overrides,
});
+/** A loaded page seeded straight into the view (no network needed). */
+const view = (items: TrashItem[]): TrashListData => ({
+ currentPage: 0,
+ hasMore: false,
+ items,
+ nextCursor: null,
+ pageSize: items.length,
+ pages: [{ count: items.length, next: null }],
+});
+
+const seed = (items: TrashItem[], activeType?: TrashItem['resourceType']) =>
+ useTrashStore.setState({
+ ...initialState,
+ activeType,
+ trashCountReplica: createReplicaState(),
+ trashListMap: { [trashListKey(activeType)]: view(items) },
+ trashListReplica: createReplicaState(),
+ });
+
+const ids = () =>
+ useTrashStore.getState().trashListMap[trashListKey()]?.items.map((i) => i.id) ?? [];
+
describe('TrashAction', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(mutate).mockResolvedValue(undefined as never);
- useTrashStore.setState({
- activeType: undefined,
- countByType: { agent: 1, topic: 2 },
- isTrashInit: true,
- items: [buildItem(), buildItem({ id: 'trash_2', resourceId: 'tpc_2' })],
- isLoadingMore: false,
- loadingIds: [],
- nextCursor: null,
- scope: 'u1:personal',
- });
- scopeMock.current = 'u1:personal';
- });
-
- afterEach(() => {
- vi.restoreAllMocks();
+ vi.mocked(trashService.countByType).mockResolvedValue({});
+ seed([buildItem(), buildItem({ id: 'trash_2', resourceId: 'tpc_2' })]);
});
describe('restore', () => {
it('drops restored rows, keeps blocked ones, and revalidates the lists a restore touches', async () => {
- vi.spyOn(trashService, 'restore').mockResolvedValue({
+ vi.mocked(trashService.restore).mockResolvedValue({
failed: [{ code: 'parentTrashed', id: 'trash_2' }],
restored: [buildItem()],
});
@@ -65,38 +95,50 @@ describe('TrashAction', () => {
const outcome = await useTrashStore.getState().restore(['trash_1', 'trash_2']);
expect(outcome.failed).toEqual([{ code: 'parentTrashed', id: 'trash_2' }]);
- expect(useTrashStore.getState().items.map((i) => i.id)).toEqual(['trash_2']);
+ expect(ids()).toEqual(['trash_2']);
expect(useTrashStore.getState().loadingIds).toEqual([]);
- // recycle-bin list + counts, plus a filter-based sweep of the affected namespaces
- expect(mutate).toHaveBeenCalledWith(['trash:list', 'all']);
- expect(mutate).toHaveBeenCalledWith(['trash:countByType']);
- const filterCall = vi.mocked(mutate).mock.calls.find(([key]) => typeof key === 'function');
- expect(filterCall).toBeTruthy();
- const filter = filterCall![0] as (key: unknown) => boolean;
- expect(filter(['topic:list', 'x', {}])).toBe(true);
- expect(filter(['agent:list', true])).toBe(true);
- // Local-first sync keys (topic list) and the agent sidebar sync key
- expect(filter(['replica:sync', 'topicList', 1, 'scope', 'agent_x', {}])).toBe(true);
- expect(filter(['agentSync:list', true, 'scope'])).toBe(true);
- expect(filter(['message:list', { agentId: 'a', topicId: 't' }, 1])).toBe(true);
- expect(filter(['trash:list', 'all'])).toBe(false);
- expect(filter('not-an-array')).toBe(false);
+
+ const predicates = vi
+ .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);
+ // …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();
+ expect(restored(['agent:list', true])).toBe(true);
+ expect(restored(['replica:sync', 'topicList', 1, 'scope', 'agent_x', {}])).toBe(true);
+ expect(restored(['agentSync:list', true, 'scope'])).toBe(true);
+ expect(restored(['message:list', { agentId: 'a', topicId: 't' }, 1])).toBe(true);
+ expect(restored(['trash:list', 'all'])).toBe(false);
+ expect(restored('not-an-array')).toBe(false);
});
it('also drops rows the server reported as already gone', async () => {
- vi.spyOn(trashService, 'restore').mockResolvedValue({
+ vi.mocked(trashService.restore).mockResolvedValue({
failed: [{ code: 'notFound', id: 'trash_1' }],
restored: [],
});
await useTrashStore.getState().restore(['trash_1']);
- expect(useTrashStore.getState().items.map((i) => i.id)).toEqual(['trash_2']);
- // nothing came back — no cross-store revalidation
- expect(vi.mocked(mutate).mock.calls.some(([key]) => typeof key === 'function')).toBe(false);
+ expect(ids()).toEqual(['trash_2']);
+ // Nothing came back — the trash list/counts refresh, but no cross-store sweep.
+ 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(['topic:list', 'x', {}]))).toBe(false);
});
it('marks rows as loading while the call is in flight', async () => {
let resolve!: () => void;
- vi.spyOn(trashService, 'restore').mockReturnValue(
+ vi.mocked(trashService.restore).mockReturnValue(
new Promise((r) => {
resolve = () => r({ failed: [], restored: [] });
}),
@@ -110,127 +152,51 @@ describe('TrashAction', () => {
});
describe('purge / emptyTrash', () => {
- it('purge removes the rows locally and refreshes the bin', async () => {
- vi.spyOn(trashService, 'purge').mockResolvedValue({ purged: 1 });
+ it('purge removes the rows from the active view', async () => {
+ vi.mocked(trashService.purge).mockResolvedValue({ purged: 1 });
await useTrashStore.getState().purge(['trash_1']);
expect(trashService.purge).toHaveBeenCalledWith(['trash_1']);
- expect(useTrashStore.getState().items.map((i) => i.id)).toEqual(['trash_2']);
+ expect(ids()).toEqual(['trash_2']);
});
it('emptyTrash honours the active type filter and clears the list', async () => {
- vi.spyOn(trashService, 'emptyTrash').mockResolvedValue({ hasMore: false, purged: 2 });
- useTrashStore.setState({ activeType: 'topic' });
+ 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().items).toEqual([]);
- expect(mutate).toHaveBeenCalledWith(['trash:list', 'topic']);
+ expect(useTrashStore.getState().trashListMap[trashListKey('topic')]?.items).toEqual([]);
});
it('emptyTrash keeps calling while the server reports more batches', async () => {
- vi.spyOn(trashService, 'emptyTrash')
+ vi.mocked(trashService.emptyTrash)
.mockResolvedValueOnce({ hasMore: true, purged: 50 })
.mockResolvedValueOnce({ hasMore: true, purged: 50 })
.mockResolvedValueOnce({ hasMore: false, purged: 7 });
await useTrashStore.getState().emptyTrash();
expect(trashService.emptyTrash).toHaveBeenCalledTimes(3);
- expect(useTrashStore.getState().items).toEqual([]);
+ expect(ids()).toEqual([]);
});
});
- describe('paging / filter', () => {
- it('setActiveType resets the list so the new filter starts from a fresh first page', () => {
- useTrashStore.setState({ nextCursor: 'abc' });
- useTrashStore.getState().setActiveType('agent');
- expect(useTrashStore.getState()).toMatchObject({
- activeType: 'agent',
- isTrashInit: false,
- items: [],
- nextCursor: null,
- });
- });
-
- it('loadMore appends the next page', async () => {
- useTrashStore.setState({ nextCursor: 'cursor-1' });
- vi.spyOn(trashService, 'list').mockResolvedValue({
- items: [buildItem({ id: 'trash_3', resourceId: 'tpc_3' })],
- nextCursor: null,
- });
- await useTrashStore.getState().loadMore();
- expect(trashService.list).toHaveBeenCalledWith({
- cursor: 'cursor-1',
- resourceType: undefined,
- });
- expect(useTrashStore.getState().items.map((i) => i.id)).toEqual([
- 'trash_1',
- 'trash_2',
- 'trash_3',
- ]);
- expect(useTrashStore.getState().nextCursor).toBeNull();
- });
-
- it('loadMore fetches a cursor once even when clicked twice', async () => {
- useTrashStore.setState({ nextCursor: 'cursor-1' });
- vi.spyOn(trashService, 'list').mockResolvedValue({
- items: [buildItem({ id: 'trash_3', resourceId: 'tpc_3' })],
- nextCursor: null,
- });
- await Promise.all([useTrashStore.getState().loadMore(), useTrashStore.getState().loadMore()]);
- expect(trashService.list).toHaveBeenCalledTimes(1);
- expect(useTrashStore.getState().items.map((i) => i.id)).toEqual([
- 'trash_1',
- 'trash_2',
- 'trash_3',
- ]);
- });
-
- it('loadMore drops a page that lands after the filter changed', async () => {
- useTrashStore.setState({ nextCursor: 'cursor-1' });
- let resolve!: (value: Awaited<ReturnType<typeof trashService.list>>) => void;
- vi.spyOn(trashService, 'list').mockReturnValue(new Promise((r) => (resolve = r)));
-
- const pending = useTrashStore.getState().loadMore();
+ describe('filter / refresh', () => {
+ it('setActiveType switches the active filter without dropping loaded views', () => {
useTrashStore.getState().setActiveType('agent');
- resolve({ items: [buildItem({ id: 'trash_3', resourceId: 'tpc_3' })], nextCursor: null });
- await pending;
-
- expect(useTrashStore.getState().items).toEqual([]);
- expect(useTrashStore.getState().isLoadingMore).toBe(false);
- });
- });
-
- describe('workspace scope', () => {
- it("clears the previous scope's rows when the workspace switches", () => {
- const { rerender } = renderHook(() => useTrashStore.getState().useFetchTrash(true));
- expect(useTrashStore.getState().items).toHaveLength(2);
-
- scopeMock.current = 'u1:ws-2';
- rerender();
-
- expect(useTrashStore.getState()).toMatchObject({
- countByType: {},
- isTrashInit: false,
- items: [],
- nextCursor: null,
- scope: 'u1:ws-2',
- });
+ expect(useTrashStore.getState().activeType).toBe('agent');
+ // The previous filter's page is still there — switching back is instant.
+ expect(ids()).toEqual(['trash_1', 'trash_2']);
});
- it('ignores a list response that belongs to a scope the user has left', () => {
- renderHook(() => useTrashStore.getState().useFetchTrash(true));
- const options = vi.mocked(useClientDataSWR).mock.calls.at(-1)![2] as {
- onSuccess: (data: unknown) => void;
- };
-
- scopeMock.current = 'u1:ws-2';
- options.onSuccess({ items: [buildItem({ id: 'stale' })], nextCursor: null });
-
- expect(useTrashStore.getState().items.map((i) => i.id)).not.toContain('stale');
- });
- });
-
- describe('selectors', () => {
- it('totalCount sums the per-type counts', () => {
- expect(trashSelectors.totalCount(useTrashStore.getState())).toBe(3);
+ 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);
});
});
});
diff --git a/src/store/trash/action.ts b/src/store/trash/action.ts
index c0dd02a1534..715b2b9d955 100644
--- a/src/store/trash/action.ts
+++ b/src/store/trash/action.ts
@@ -1,20 +1,27 @@
-import type {
- TrashCountByType,
- TrashItem,
- TrashListResult,
- TrashResourceType,
-} from '@lobechat/types';
-import { useLayoutEffect } from 'react';
-import type { SWRResponse } from 'swr';
-
-import { mutate, useClientDataSWR } from '@/libs/swr';
-import { trashKeys } from '@/libs/swr/keys';
-import { getCacheScope, useCacheScope } from '@/libs/swr/useCacheScope';
+import type { TrashCountByType, TrashItem, TrashResourceType } from '@lobechat/types';
+
+import {
+ createReplicaSlice,
+ recordLens,
+ type ReplicaPageResult,
+ type ReplicaSyncResult,
+} from '@/libs/replica';
+import { mutate } from '@/libs/swr';
import { trashService } from '@/services/trash';
import type { StoreSetter } from '@/store/types';
-
+import { setNamespace } from '@/utils/storeDebug';
+
+import type { TrashListData } from './initialState';
+import {
+ trashCountResource,
+ trashListKey,
+ type TrashListParams,
+ trashListResource,
+} from './projection';
import type { TrashStore } from './store';
+const n = setNamespace('trash');
+
type Setter = StoreSetter<TrashStore>;
/** SWR key roots whose lists can regain rows after a restore. */
@@ -41,36 +48,64 @@ const RESTORE_AFFECTED_KEY_PREFIXES = [
'video:',
];
+const COUNT_PARAMS = {} as Record<string, never>;
+
export const trashSlice = (set: Setter, get: () => TrashStore, _api?: unknown) =>
new TrashActionImpl(set, get, _api);
/**
- * Recycle-bin store. Rows are removed optimistically on restore / purge and
- * the list + counts are revalidated afterwards so a failed call self-corrects.
+ * Recycle-bin store. The list and the per-type counts are local-first replicas:
+ * each filter keeps its own persisted page (first frame paints from storage,
+ * the network confirms), and a restore / purge drops the row from every loaded
+ * filter before the counts revalidate.
*/
export class TrashActionImpl {
readonly #get: () => TrashStore;
readonly #set: Setter;
+ readonly #trashCount;
+ readonly #trashList;
constructor(set: Setter, get: () => TrashStore, _api?: unknown) {
void _api;
this.#set = set;
this.#get = get;
+ this.#trashList = createReplicaSlice(trashListResource, {
+ actionPrefix: n('trashList'),
+ fetcher: this.#fetchPage,
+ get,
+ set,
+ stateKey: 'trashListReplica',
+ view: recordLens<TrashStore, TrashListData>('trashListMap'),
+ });
+ this.#trashCount = createReplicaSlice(trashCountResource, {
+ actionPrefix: n('trashCount'),
+ fetcher: () => trashService.countByType(),
+ get,
+ set,
+ stateKey: 'trashCountReplica',
+ view: recordLens<TrashStore, TrashCountByType>('trashCountMap'),
+ });
}
- setActiveType = (activeType?: TrashResourceType) => {
- this.#set(
- { activeType, isTrashInit: false, items: [], nextCursor: null },
- false,
- 'setActiveType',
+ /** One recycle-bin page: `cursor` undefined = the head (newest first). */
+ #fetchPage = async (
+ { resourceType }: TrashListParams,
+ cursor?: string,
+ ): Promise<ReplicaPageResult<TrashItem, string>> => {
+ const { items, nextCursor } = await trashService.list(
+ cursor ? { cursor, resourceType } : { resourceType },
);
+ return { items, nextCursor };
+ };
+
+ /** Switching filter just selects another already-keyed view; no reset needed. */
+ setActiveType = (activeType?: TrashResourceType) => {
+ this.#set({ activeType }, false, n('setActiveType'));
};
+ /** Re-fetch the list(s) and the counts of the active identity. */
refresh = async () => {
- await Promise.all([
- mutate(trashKeys.list(this.#get().activeType)),
- mutate(trashKeys.countByType()),
- ]);
+ await Promise.all([this.#trashList.revalidate(), this.#trashCount.revalidate()]);
};
/**
@@ -89,33 +124,19 @@ export class TrashActionImpl {
);
};
+ /** Next page of the active filter, using the loaded head page's params. */
loadMore = async () => {
- const { activeType, isLoadingMore, nextCursor, scope } = this.#get();
- if (!nextCursor || isLoadingMore) return;
- this.#set({ isLoadingMore: true }, false, 'loadMore/start');
- try {
- const page = await trashService.list({ cursor: nextCursor, resourceType: activeType });
- // The filter, cursor or workspace may have moved on while this page was
- // in flight; appending it then would mix another list's rows in.
- const current = this.#get();
- if (
- current.activeType !== activeType ||
- current.nextCursor !== nextCursor ||
- current.scope !== scope
- )
- return;
- this.#set(
- { items: [...current.items, ...page.items], nextCursor: page.nextCursor },
- false,
- 'loadMore',
- );
- } finally {
- this.#set({ isLoadingMore: false }, false, 'loadMore/end');
- }
+ const { activeType } = this.#get();
+ await this.#trashList.loadMore(trashListKey(activeType), { resourceType: activeType });
+ };
+
+ /** Drop a row from every loaded filter (the engine also patches persisted rows). */
+ #dropRows = (ids: Iterable<string>) => {
+ for (const id of ids) this.#trashList.updateEntity(id, () => undefined);
};
#withLoading = async (ids: string[], run: () => Promise<void>) => {
- this.#set({ loadingIds: [...this.#get().loadingIds, ...ids] }, false, 'loading/start');
+ this.#set({ loadingIds: [...this.#get().loadingIds, ...ids] }, false, n('loading/start'));
try {
await run();
} finally {
@@ -123,7 +144,7 @@ export class TrashActionImpl {
this.#set(
{ loadingIds: this.#get().loadingIds.filter((id) => !done.has(id)) },
false,
- 'loading/end',
+ n('loading/end'),
);
await this.refresh();
}
@@ -141,11 +162,7 @@ export class TrashActionImpl {
const gone = new Set(outcome.restored.map((item) => item.id));
// `notFound` rows were dropped from the registry server-side.
for (const failure of outcome.failed) if (failure.code === 'notFound') gone.add(failure.id);
- this.#set(
- { items: this.#get().items.filter((item) => !gone.has(item.id)) },
- false,
- 'restore',
- );
+ this.#dropRows(gone);
});
if (outcome.restored.length > 0) void this.revalidateRestoredScopes();
return outcome;
@@ -154,74 +171,50 @@ export class TrashActionImpl {
purge = async (ids: string[]) => {
await this.#withLoading(ids, async () => {
await trashService.purge(ids);
- const gone = new Set(ids);
- this.#set({ items: this.#get().items.filter((item) => !gone.has(item.id)) }, false, 'purge');
+ this.#dropRows(ids);
});
};
emptyTrash = async () => {
- const { activeType, items } = this.#get();
- await this.#withLoading(
- items.map((item) => item.id),
- async () => {
- // The server purges one bounded batch per call so no single request
- // runs away on a large bin; keep going until it reports nothing left.
- for (;;) {
- const { hasMore } = await trashService.emptyTrash(activeType);
- if (!hasMore) break;
- }
- this.#set({ items: [], nextCursor: null }, false, 'emptyTrash');
- },
- );
- };
-
- useFetchTrash = (
- enabled: boolean,
- resourceType?: TrashResourceType,
- ): SWRResponse<TrashListResult> => {
- const scope = useCacheScope();
-
- // A workspace (or user) switch inside the SPA: drop the previous scope's
- // rows before paint instead of showing them until — or, if the fetch
- // fails, instead of — the new scope's list.
- useLayoutEffect(() => {
- if (!enabled || this.#get().scope === scope) return;
- this.#set(
- { countByType: {}, isTrashInit: false, items: [], nextCursor: null, scope },
- false,
- 'fetchTrash/scope',
+ 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,
);
- }, [enabled, scope]);
-
- return useClientDataSWR<TrashListResult>(
- enabled ? trashKeys.list(resourceType) : null,
- () => trashService.list({ resourceType }),
- {
- onSuccess: (data) => {
- if (scope !== getCacheScope()) return;
- this.#set(
- { isTrashInit: true, items: data.items, nextCursor: data.nextCursor, scope },
- false,
- 'fetchTrash',
- );
- },
- },
- );
+ });
};
- useFetchTrashCount = (enabled: boolean): SWRResponse<TrashCountByType> => {
- const scope = useCacheScope();
- return useClientDataSWR<TrashCountByType>(
- enabled ? trashKeys.countByType() : null,
- () => trashService.countByType(),
- {
- onSuccess: (data) => {
- if (scope !== getCacheScope()) return;
- this.#set({ countByType: data }, false, 'fetchTrashCount');
- },
- },
- );
- };
+ /**
+ * Fetch orchestration for one filter'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);
+
+ /** Fetch orchestration for the per-type counts; read them via `trashSelectors`. */
+ useFetchTrashCount = (enabled: boolean): ReplicaSyncResult =>
+ this.#trashCount.useSync(enabled ? COUNT_PARAMS : null);
}
export type TrashAction = Pick<TrashActionImpl, keyof TrashActionImpl>;
diff --git a/src/store/trash/initialState.ts b/src/store/trash/initialState.ts
index f155913ba3d..2dc1b42f1b5 100644
--- a/src/store/trash/initialState.ts
+++ b/src/store/trash/initialState.ts
@@ -1,31 +1,30 @@
import type { TrashCountByType, TrashItem, 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. */
+export type TrashListData = ReplicaPagedData<TrashItem, string>;
+
export interface TrashState {
/** Type filter the recycle-bin page is currently showing (`undefined` = everything). */
activeType?: TrashResourceType;
- countByType: TrashCountByType;
- /** A load-more page request is in flight — a second click must not fetch the same cursor. */
- isLoadingMore: boolean;
- isTrashInit: boolean;
- items: TrashItem[];
/** Registry ids with an in-flight restore / purge — drives per-row spinners. */
loadingIds: string[];
- nextCursor: string | null;
- /**
- * Cache scope (`user:workspace`) the list above was fetched for. SWR keys are
- * partitioned per workspace but this list is not, so a scope switch resets
- * it rather than showing the previous workspace's rows.
- */
- scope?: string;
+ /** Per-type counts (`trashCountMap.all`): the filter chips and the empty total. */
+ trashCountMap: Record<string, TrashCountByType>;
+ /** Local-first bookkeeping for `trashCountMap`. */
+ trashCountReplica: ReplicaState<TrashCountByType>;
+ /** Recycle-bin rows per filter (`trashListMap[resourceType ?? 'all']`). */
+ trashListMap: Record<string, TrashListData>;
+ /** Local-first bookkeeping for `trashListMap`. */
+ trashListReplica: ReplicaState<TrashListData>;
}
export const initialState: TrashState = {
activeType: undefined,
- countByType: {},
- isLoadingMore: false,
- isTrashInit: false,
- items: [],
loadingIds: [],
- nextCursor: null,
- scope: undefined,
+ trashCountMap: {},
+ trashCountReplica: createReplicaState(),
+ trashListMap: {},
+ trashListReplica: createReplicaState(),
};
diff --git a/src/store/trash/projection.ts b/src/store/trash/projection.ts
new file mode 100644
index 00000000000..24858b8bbd4
--- /dev/null
+++ b/src/store/trash/projection.ts
@@ -0,0 +1,50 @@
+import type { TrashCountByType, TrashItem, TrashResourceType } from '@lobechat/types';
+
+import { definePagedReplica, defineReplica } from '@/libs/replica';
+
+import type { TrashListData } from './initialState';
+
+export interface TrashListParams {
+ resourceType?: TrashResourceType;
+}
+
+/** Entry key of the "everything" filter — not a `TrashResourceType`, 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;
+
+/**
+ * Recycle-bin rows, one local-first entry per type filter (`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
+ * `trashSelectors`, never from the sync hook.
+ */
+export const trashListResource = definePagedReplica<
+ TrashListParams,
+ TrashItem,
+ string,
+ TrashListData
+>({
+ key: ({ resourceType }) => trashListKey(resourceType),
+ name: 'trashList',
+ paging: {
+ direction: 'forward',
+ getId: (item) => item.id,
+ mode: 'cursor',
+ // A reload repaints what the first network page would show, not a stale tail.
+ persist: { pages: 1 },
+ },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** 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,
+ name: 'trashCount',
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/trash/replica.test.ts b/src/store/trash/replica.test.ts
new file mode 100644
index 00000000000..679b2a763e0
--- /dev/null
+++ b/src/store/trash/replica.test.ts
@@ -0,0 +1,314 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The recycle-bin list and its per-type counts are replicas: the list paints
+ * from the persisted copy on the first frame, the network only confirms, and a
+ * restore / purge / empty drops the row from every loaded filter.
+ */
+import { randomUUID } from 'node:crypto';
+
+import type { TrashItem, TrashListParams } from '@lobechat/types';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { trashService } from '@/services/trash';
+
+import type { TrashListData } from './initialState';
+import { initialState } from './initialState';
+import { trashCountResource, trashListKey, trashListResource } from './projection';
+import { trashSelectors } from './selectors';
+import { useTrashStore } from './store';
+
+vi.mock('@/services/trash', () => ({
+ trashService: {
+ countByType: vi.fn(),
+ emptyTrash: vi.fn(),
+ list: vi.fn(),
+ purge: vi.fn(),
+ restore: vi.fn(),
+ },
+}));
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
+
+const item = (
+ id: string,
+ title = id,
+ resourceType: TrashItem['resourceType'] = 'topic',
+): TrashItem =>
+ ({
+ deletedAt: new Date('2026-08-01T00:00:00Z'),
+ deletedByUserId: 'u1',
+ expiresAt: new Date('2026-08-31T00:00:00Z'),
+ id,
+ meta: null,
+ resourceId: `res_${id}`,
+ resourceType,
+ rootId: null,
+ title,
+ userId: 'u1',
+ workspaceId: null,
+ }) as TrashItem;
+
+/** A persisted paged view as `toPersistedPage` writes it. */
+const paged = (items: TrashItem[], nextCursor: string | null = null): TrashListData => ({
+ currentPage: 0,
+ hasMore: nextCursor !== null,
+ items,
+ nextCursor,
+ pageSize: items.length,
+ pages: [{ count: items.length, next: nextCursor }],
+});
+
+/** Never-resolving fetch: the first frame can only come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+/** Route `trashService.list` by the requested filter. */
+const listFor = (
+ byType: (resourceType: TrashItem['resourceType'] | undefined) => {
+ items: TrashItem[];
+ nextCursor: string | null;
+ },
+) =>
+ vi
+ .mocked(trashService.list)
+ .mockImplementation(async (params?: TrashListParams) => byType(params?.resourceType));
+
+const itemIds = (resourceType?: TrashItem['resourceType']) =>
+ useTrashStore.getState().trashListMap[trashListKey(resourceType)]?.items.map((i) => i.id);
+
+describe('trash replicas', () => {
+ const scopes = new Set<string>();
+ let scope = '';
+ const useScope = (next: string) => {
+ scope = next;
+ scopes.add(next);
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ };
+
+ const storageKeyOf = (resourceType?: TrashItem['resourceType']) =>
+ trashListResource.storageKey({ resourceType });
+
+ beforeEach(() => {
+ useScope(`trash-user-${randomUUID()}:personal`);
+ act(() => useTrashStore.setState({ ...initialState }));
+ vi.clearAllMocks();
+ vi.mocked(trashService.countByType).mockResolvedValue({});
+ });
+
+ 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.clear();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('paints the persisted list before the network answers', async () => {
+ await trashListResource.storage!.set(
+ { queryKey: storageKeyOf(), scope },
+ { data: paged([item('t1', 'Cached')]), updatedAt: 1 },
+ );
+ vi.mocked(trashService.list).mockImplementation(pending);
+
+ const sync = renderHook(() => useTrashStore((s) => s.useFetchTrash)(true), { wrapper });
+ const list = renderHook(() => useTrashStore(trashSelectors.currentList(undefined)));
+
+ await waitFor(() => expect(list.result.current?.items.map((i) => i.title)).toEqual(['Cached']));
+ expect(sync.result.current.isHydrated).toBe(true);
+ expect(sync.result.current.isValidating).toBe(true);
+ });
+
+ it('replaces the list with the server response and persists it', async () => {
+ vi.mocked(trashService.list).mockResolvedValue({
+ items: [item('t1', 'Server')],
+ nextCursor: null,
+ });
+
+ renderHook(() => useTrashStore((s) => s.useFetchTrash)(true), { wrapper });
+
+ await waitFor(() => expect(itemIds()).toEqual(['t1']));
+ await waitFor(async () =>
+ expect(
+ (await trashListResource.storage!.get({ queryKey: storageKeyOf(), scope }))?.data.items[0]
+ ?.title,
+ ).toBe('Server'),
+ );
+ });
+
+ it('keys each type filter as its own view', async () => {
+ listFor((resourceType) =>
+ resourceType === 'topic'
+ ? { items: [item('topic_1', 'A topic', 'topic')], nextCursor: null }
+ : { items: [item('agent_1', 'An agent', 'agent')], nextCursor: null },
+ );
+
+ renderHook(() => useTrashStore((s) => s.useFetchTrash)(true, 'topic'), { wrapper });
+ renderHook(() => useTrashStore((s) => s.useFetchTrash)(true), { wrapper });
+
+ await waitFor(() => expect(itemIds('topic')).toEqual(['topic_1']));
+ await waitFor(() => expect(itemIds()).toEqual(['agent_1']));
+ });
+
+ it('appends the next cursor page on loadMore', async () => {
+ vi.mocked(trashService.list)
+ .mockResolvedValueOnce({ items: [item('t1'), item('t2')], nextCursor: 'cursor-1' })
+ .mockResolvedValueOnce({ items: [item('t3')], nextCursor: null });
+
+ renderHook(() => useTrashStore((s) => s.useFetchTrash)(true), { wrapper });
+ await waitFor(() =>
+ expect(useTrashStore.getState().trashListMap.all?.nextCursor).toBe('cursor-1'),
+ );
+
+ await act(() => useTrashStore.getState().loadMore());
+
+ expect(trashService.list).toHaveBeenLastCalledWith({
+ cursor: 'cursor-1',
+ resourceType: undefined,
+ });
+ expect(itemIds()).toEqual(['t1', 't2', 't3']);
+ expect(useTrashStore.getState().trashListMap.all?.nextCursor).toBeNull();
+ });
+
+ it('drops a restored row from the loaded view', async () => {
+ vi.mocked(trashService.list).mockResolvedValue({
+ items: [item('t1'), item('t2')],
+ nextCursor: null,
+ });
+ renderHook(() => useTrashStore((s) => s.useFetchTrash)(true), { wrapper });
+ await waitFor(() => expect(itemIds()).toEqual(['t1', 't2']));
+
+ vi.mocked(trashService.restore).mockResolvedValue({ failed: [], restored: [item('t1')] });
+ // The follow-up refresh sees the server's post-restore list.
+ vi.mocked(trashService.list).mockResolvedValue({ items: [item('t2')], nextCursor: null });
+
+ await act(() => useTrashStore.getState().restore(['t1']));
+
+ expect(itemIds()).toEqual(['t2']);
+ expect(useTrashStore.getState().loadingIds).toEqual([]);
+ });
+
+ it('drops restored rows from every loaded filter', async () => {
+ listFor((resourceType) =>
+ resourceType === 'topic'
+ ? { items: [item('shared_1', 'A topic'), item('topic_2')], nextCursor: null }
+ : {
+ items: [item('shared_1', 'A topic'), item('agent_1', 'An agent', 'agent')],
+ nextCursor: null,
+ },
+ );
+
+ renderHook(
+ () => {
+ useTrashStore((s) => s.useFetchTrash)(true, 'topic');
+ useTrashStore((s) => s.useFetchTrash)(true);
+ },
+ { wrapper },
+ );
+ await waitFor(() => expect(itemIds('topic')).toEqual(['shared_1', 'topic_2']));
+ await waitFor(() => expect(itemIds()).toEqual(['shared_1', 'agent_1']));
+
+ vi.mocked(trashService.restore).mockResolvedValue({
+ failed: [],
+ restored: [item('shared_1', 'A topic')],
+ });
+ listFor((resourceType) =>
+ resourceType === 'topic'
+ ? { items: [item('topic_2')], nextCursor: null }
+ : { items: [item('agent_1', 'An agent', 'agent')], nextCursor: null },
+ );
+
+ await act(() => useTrashStore.getState().restore(['shared_1']));
+
+ expect(itemIds('topic')).toEqual(['topic_2']);
+ expect(itemIds()).toEqual(['agent_1']);
+ });
+
+ it('emptyTrash collapses the active filter’s view', async () => {
+ vi.mocked(trashService.list).mockResolvedValue({
+ items: [item('t1', 'A topic', 'topic')],
+ nextCursor: null,
+ });
+ act(() => useTrashStore.setState({ activeType: 'topic' }));
+ renderHook(() => useTrashStore((s) => s.useFetchTrash)(true, '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());
+
+ expect(trashService.emptyTrash).toHaveBeenCalledWith('topic');
+ expect(itemIds('topic')).toEqual([]);
+ });
+
+ it('never hydrates another identity’s persisted list', async () => {
+ const other = `trash-user-${randomUUID()}:personal`;
+ scopes.add(other);
+ await trashListResource.storage!.set(
+ { queryKey: storageKeyOf(), scope: other },
+ { data: paged([item('stale', 'Other user')]), updatedAt: 1 },
+ );
+ vi.mocked(trashService.list).mockImplementation(pending);
+
+ 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();
+ });
+
+ it('drops the previous identity’s list before the next one paints', async () => {
+ vi.mocked(trashService.list).mockResolvedValue({
+ items: [item('t1', 'Mine')],
+ nextCursor: null,
+ });
+ 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());
+ });
+
+ 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 });
+
+ await waitFor(() =>
+ expect(useTrashStore.getState().trashCountMap.all).toEqual({ agent: 1, topic: 2 }),
+ );
+ expect(trashSelectors.totalCount(useTrashStore.getState())).toBe(3);
+ expect(trashSelectors.countByType(useTrashStore.getState())).toEqual({ agent: 1, topic: 2 });
+ });
+ });
+});
diff --git a/src/store/trash/selectors.ts b/src/store/trash/selectors.ts
index 369203ed163..5da8b11988e 100644
--- a/src/store/trash/selectors.ts
+++ b/src/store/trash/selectors.ts
@@ -1,10 +1,23 @@
+import type { TrashResourceType } from '@lobechat/types';
+
import type { TrashState } from './initialState';
+import { trashListKey } from './projection';
+
+/** The loaded page of one filter, or `undefined` before its first paint. */
+const currentList = (activeType?: TrashResourceType) => (s: TrashState) =>
+ s.trashListMap[trashListKey(activeType)];
+
+const countByType = (s: TrashState) => s.trashCountMap[trashListKey()] ?? {};
const totalCount = (s: TrashState) =>
- Object.values(s.countByType).reduce((sum, count) => sum + (count ?? 0), 0);
+ Object.values(countByType(s)).reduce((sum, count) => sum + (count ?? 0), 0);
-const isEmpty = (s: TrashState) => s.isTrashInit && s.items.length === 0;
+/** 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)];
+ return !!list && list.items.length === 0;
+};
const isLoading = (id: string) => (s: TrashState) => s.loadingIds.includes(id);
-export const trashSelectors = { isEmpty, isLoading, totalCount };
+export const trashSelectors = { countByType, currentList, isEmpty, isLoading, totalCount };