π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β»οΈ refactor(resourceManager): move the resource search lists onto @lobechat/replica (#20636)
Arvin Xu14f80dba1b3c
diff --git a/apps/workbench/app/stubs/fileStore.ts b/apps/workbench/app/stubs/fileStore.tsindex ab124af9a29..68173d80f2a 100644--- a/apps/workbench/app/stubs/fileStore.ts+++ b/apps/workbench/app/stubs/fileStore.ts@@ -1,5 +1,10 @@+// `src/store/tree/actions.ts` reaches the ResourceManager store when it refreshes+// the sidebar's hierarchy search, and that store reads these fields off the file+// store state. On the server there is no query / folder to scope, so they are inert.const emptyState = {+ queryParams: undefined,uploadWithProgress: async () => undefined,+ useFetchFolderBreadcrumb: () => undefined,};export const useFileStore = <T = unknown>(selector?: (state: typeof emptyState) => T): T =>@@ -12,6 +17,9 @@ useFileStore.subscribe = () => () => {};export const documentSelectors = {};export const fileChatSelectors = {};-export const fileManagerSelectors = {};+export const fileManagerSelectors = {+ // `selectors.getCurrentFile` resolves the previewed row through this selector.+ getFileById: () => () => undefined,+};export const filesSelectors = {};export const getChunkTargetId = () => undefined;diff --git a/apps/workbench/app/stubs/surface.test.ts b/apps/workbench/app/stubs/surface.test.tsindex 998c93b2d12..6ef007850fa 100644--- a/apps/workbench/app/stubs/surface.test.ts+++ b/apps/workbench/app/stubs/surface.test.ts@@ -86,6 +86,19 @@ describe('workbench stub surface', () => {expect(stubUsageGaps(surface, usage!)).toEqual(['fileChatSelectors.chatUploadFileList']);});+ it('covers the file-store surface the tree store reaches through the ResourceManager store', () => {+ // The tree store imports the ResourceManager store barrel to refresh the+ // sidebar search, which pulls these modules into the workbench SSR graph.+ const stub = readFileSync(path.join(stubDir, 'fileStore.ts'), 'utf8');+ const storeDir = path.resolve(stubDir, '../../../../src/features/ResourceManager/store');+ const files = ['action.ts', 'index.ts', 'selectors.ts'].map((name) => ({+ rel: `src/features/ResourceManager/store/${name}`,+ source: readFileSync(path.join(storeDir, name), 'utf8'),+ }));++ expect(reportStubSurfaceGaps(files, [{ source: stub, specifier: '@/store/file' }])).toEqual([]);+ });+it('formats graph gaps with the importer path', () => {expect(reportStubSurfaceGaps(diff --git a/packages/replica/src/core/engine.ts b/packages/replica/src/core/engine.tsindex 5f3ce0ab9cf..f07fb452571 100644--- a/packages/replica/src/core/engine.ts+++ b/packages/replica/src/core/engine.ts@@ -198,7 +198,11 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(if (!writeQueue) return;const known = indexed.get(scope) ?? new Set<string>();indexed.set(scope, known);- if (known.has(queryKey) === present) return;+ // `known` only holds the keys THIS instance wrote. A row an earlier session+ // persisted is absent from it yet still listed in the index, so an addition+ // already made needs no second write, but a removal must always reach the+ // index β the updater leaves it alone when the key is genuinely gone.+ if (present && known.has(queryKey)) return;if (present) known.add(queryKey);else known.delete(queryKey);writeQueue.update(indexKey(scope), (current) => {diff --git a/packages/replica/src/zustand/createReplicaSlice.test.ts b/packages/replica/src/zustand/createReplicaSlice.test.tsindex 80c0ea24b48..d1df76cc712 100644--- a/packages/replica/src/zustand/createReplicaSlice.test.ts+++ b/packages/replica/src/zustand/createReplicaSlice.test.ts@@ -51,7 +51,7 @@ const createMemoryStorage = (delays: Record<string, number> = {}) => {rows.set(`${scope}|${queryKey}`, projection);},};- return { rows, storage, writes };+ return { indexRows, rows, storage, writes };};const setup = ({@@ -561,6 +561,42 @@ describe('createReplicaSlice', () => {});});+ describe('remove', () => {+ it('does not let an in-flight response resurrect a removed entry', async () => {+ let resolveFetch!: (value: string[]) => void;+ const fetcher = vi.fn(() => new Promise<string[]>((resolve) => (resolveFetch = resolve)));+ const { slice, store } = setup({ fetcher });++ renderHook(() => slice.useSync({ id: 'a' }), { wrapper });+ await waitFor(() => expect(fetcher).toHaveBeenCalled());++ // The entry is invalidated while its own request is still in flight.+ act(() => {+ slice.remove('a');+ });+ await act(async () => resolveFetch(['late']));++ expect(store.getState().lists.a).toBeUndefined();+ });+ });++ describe('persisted index', () => {+ it('removes a key this instance never wrote from the stored index', async () => {+ const storage = createMemoryStorage();+ // An earlier session persisted this row and listed it in the index. This+ // instance has no memory of the key β the eviction / invalidation case+ // where the index write must still reach storage.+ storage.rows.set('user-1:personal|a', { data: ['stale'], updatedAt: 1 });+ storage.indexRows.set('user-1:personal', { data: ['a'], updatedAt: 1 });+ const { slice } = setup({ storage });++ act(() => slice.remove('a'));++ await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());+ await waitFor(() => expect(storage.indexRows.get('user-1:personal')?.data).toEqual([]));+ });+ });+describe('scope isolation', () => {it('clears the previous identity and drops its late results', async () => {const { slice, store, storage } = setup();diff --git a/packages/replica/src/zustand/createReplicaSlice.ts b/packages/replica/src/zustand/createReplicaSlice.tsindex de14c89963b..82ed35756b4 100644--- a/packages/replica/src/zustand/createReplicaSlice.ts+++ b/packages/replica/src/zustand/createReplicaSlice.ts@@ -205,7 +205,20 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(};};- return { ...engine, useSync };+ return {+ ...engine,+ /**+ * Forget the key's head query as well as the entry. A request already in+ * flight for it would otherwise pass the `onSuccess` guard below (the marker+ * still matches), `replace` the entry and persist pre-mutation rows back over+ * an invalidation that has already completed.+ */+ remove: (key: string) => {+ headQuery.delete(key);+ return engine.remove(key);+ },+ useSync,+ };};export type ReplicaSlice<TStore, TParams, TData, TFetched = TData> = ReturnType<diff --git a/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx b/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsxindex 1e3ee5052c1..1e2016e9db8 100644--- a/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx+++ b/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx@@ -12,20 +12,22 @@ import { Virtuoso } from 'react-virtuoso';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import AsyncError from '@/components/AsyncError';import { useResourceManagerStore } from '@/features/ResourceManager/store';+import {+ DEFAULT_SEARCH_PAGE_SIZE,+ type ExplorerSearchParams,+ explorerSearchResource,+} from '@/features/ResourceManager/store/projection';import {getResourceQueryVisibility,getResourceSourceFilter,} from '@/features/ResourceManager/store/selectors';-import { useClientDataSWR } from '@/libs/swr';-import { resourceKeys } from '@/libs/swr/keys';-import { resourceService } from '@/services/resource';import { useGlobalStore } from '@/store/global';import {DEFAULT_RESOURCE_MANAGER_COLUMN_WIDTHS,INITIAL_STATUS,} from '@/store/global/initialState';import type { AsyncTaskStatus } from '@/types/asyncTask';-import { type FileListItem, type ResourceSourceFilter } from '@/types/files';+import { type FileListItem } from '@/types/files';import { useExplorerSelectionEligibility } from './hooks/useExplorerSelection';import FileListItemComponent from './ListView/ListItem';@@ -61,51 +63,41 @@ const SearchResultsOverlay = memo(() => {const showUploader = !!activeWorkspaceId && (!!libraryId || listVisibility !== 'private');const visibility = getResourceQueryVisibility(libraryId, listVisibility);- const {- data: rawData,- isLoading,- error,- mutate,- } = useClientDataSWR(- isActive- ? resourceKeys.search(- {+ // Search results are a `@lobechat/replica` entry owned by the ResourceManager+ // store: the head page is persisted, so re-opening a search paints the rows it+ // had before the request lands. The keyword is part of the query identity, so+ // the painted rows are only used while they still answer the request on screen.+ const searchParams = useMemo<ExplorerSearchParams | null>(+ () =>+ isActive+ ? {category: libraryId ? undefined : category,includeContentPreview: viewMode === 'masonry',libraryId,- q: searchQuery,- // Search narrows the list the user is looking at, so it has to honour- // the source they picked. Omitting it left the chip visibly selected- // while results came back from every non-hidden source β and made- // `Acceptance` search unusable, since that source is hidden unless- // explicitly asked for.+ pageSize: DEFAULT_SEARCH_PAGE_SIZE,+ q: searchQuery!,sourceFilter,visibility,- },- activeWorkspaceId ?? null,- )- : null,- async ([, params]: [- string,- {- category?: string;- includeContentPreview?: boolean;- libraryId?: string;- q: string;- sourceFilter?: ResourceSourceFilter;- visibility?: 'private' | 'public';- },- ]) => {- const response = await resourceService.queryResources({- ...params,- limit: 50,- offset: 0,- showFilesInKnowledgeBase: false,- } as any);- return response.items;- },+ }+ : null,+ [isActive, category, libraryId, searchQuery, sourceFilter, viewMode, visibility],);+ const { error, revalidate } = useResourceManagerStore((s) => s.useFetchExplorerSearch)(+ searchParams,+ );+ const explorerSearchEntries = useResourceManagerStore((s) => s.explorerSearchEntries);++ // One entry per query: the entry key IS the query identity, so the rows read+ // here always answer the request on screen.+ const current = searchParams+ ? explorerSearchEntries[explorerSearchResource.key(searchParams)]+ : undefined;++ const rawData = current?.items;+ const isLoading = !current && !error;+ const mutate = revalidate;+const data: FileListItem[] | undefined = useMemo(() =>rawData?.map((item) => ({diff --git a/src/features/ResourceManager/components/LibraryHierarchy/SearchResults.tsx b/src/features/ResourceManager/components/LibraryHierarchy/SearchResults.tsxindex 9797673f837..5714a5c3a79 100644--- a/src/features/ResourceManager/components/LibraryHierarchy/SearchResults.tsx+++ b/src/features/ResourceManager/components/LibraryHierarchy/SearchResults.tsx@@ -5,25 +5,26 @@ import { Text } from '@lobehub/ui/base-ui';import { useDebounce } from 'ahooks';import { cssVar } from 'antd-style';import { SearchXIcon } from 'lucide-react';-import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { memo, useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';import { VList, type VListHandle } from 'virtua';-import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import AsyncBoundary from '@/components/AsyncBoundary';+import AsyncError from '@/components/AsyncError';import { useFolderPath } from '@/features/ResourceManager/hooks/useFolderPath';import { useResourceManagerStore } from '@/features/ResourceManager/store';-import { useClientDataSWR } from '@/libs/swr';-import { resourceKeys } from '@/libs/swr/keys';-import { resourceService } from '@/services/resource';+import {+ DEFAULT_SEARCH_PAGE_SIZE,+ type HierarchySearchParams,+ hierarchySearchResource,+} from '@/features/ResourceManager/store/projection';import { toTreeItem } from '@/store/tree';import { HierarchyNode } from './HierarchyNode';+import { resolveSearchViewState } from './searchViewState';import { resolveHierarchySelectedKey } from './selection';import TreeSkeleton from './TreeSkeleton';-/** Rows fetched per step; the list grows by this much each time the end is reached. */-const SEARCH_PAGE_SIZE = 50;const noop = () => {};interface SearchResultsProps {@@ -36,80 +37,73 @@ interface SearchResultsProps {* sidebar while the user has a query typed. Rows reuse `HierarchyNode` so a* hit opens exactly like its tree counterpart (folder β navigate, page β page* editor, file β file editor) and keeps the same context menu.+ *+ * The rows are a `@lobechat/replica` entry owned by the ResourceManager store:+ * the head page is persisted, so coming back to the same search paints it+ * before the request lands, and "load more" appends further pages through the+ * engine instead of re-fetching a widening window.*/const SearchResults = memo<SearchResultsProps>(({ libraryId, query }) => {const { t } = useTranslation('file');const { currentFolderSlug } = useFolderPath();const currentViewItemId = useResourceManagerStore((s) => s.currentViewItemId);const selectedKey = resolveHierarchySelectedKey({ currentFolderSlug, currentViewItemId });- const activeWorkspaceId = useActiveWorkspaceId();// Debounce here rather than in the input so the store always holds what the// user sees; only the network request lags behind the keystrokes.const debouncedQuery = useDebounce(query.trim(), { wait: 300 });- // Incremental loading: the requested window grows from the start each time- // the user scrolls to the end, so the whole result set stays one SWR entry- // (one key to revalidate after a rename/move/delete) and the tree-store- // revalidation can find it by the `hierarchy` scope. A new query starts over.- const [limit, setLimit] = useState(SEARCH_PAGE_SIZE);- useEffect(() => {- setLimit(SEARCH_PAGE_SIZE);- }, [debouncedQuery, libraryId]);-- const { data, error, isValidating, mutate } = useClientDataSWR(- debouncedQuery- ? resourceKeys.search(- { libraryId, limit, q: debouncedQuery, scope: 'hierarchy' },- activeWorkspaceId ?? null,- )- : null,- async ([, params]: [string, { libraryId: string; limit: number; q: string }]) => {- const response = await resourceService.queryResources({- libraryId: params.libraryId,- limit: params.limit,- offset: 0,- q: params.q,- showFilesInKnowledgeBase: false,- });- // Echo the scope so retained data from a previous key can be told apart.- return {- hasMore: response.hasMore,- items: response.items,- libraryId: params.libraryId,- q: params.q,- };- },- // Growing the window must not flash the skeleton over rows already shown.- // The trade-off is that a *new* query also keeps the old rows around, so- // only data that echoes the current query/library counts as current below.- { keepPreviousData: true },+ // The keyword is part of the query identity, so a projection taken under+ // another search never paints and a new query starts its own head page.+ const searchParams = useMemo<HierarchySearchParams | null>(+ () =>+ debouncedQuery ? { libraryId, pageSize: DEFAULT_SEARCH_PAGE_SIZE, q: debouncedQuery } : null,+ [debouncedQuery, libraryId],+ );++ const { error, revalidate } = useResourceManagerStore((s) => s.useFetchHierarchySearch)(+ searchParams,);+ const loadMore = useResourceManagerStore((s) => s.loadMoreHierarchySearch);+ const hierarchySearchEntries = useResourceManagerStore((s) => s.hierarchySearchEntries);++ // One entry per (library, keyword): the entry key IS the query identity, so+ // the rows read here always answer the request on screen.+ const entryKey = searchParams ? hierarchySearchResource.key(searchParams) : undefined;+ const current = entryKey ? hierarchySearchEntries[entryKey] : undefined;- const current = data?.q === debouncedQuery && data.libraryId === libraryId ? data : undefined;const rows = useMemo(() =>current?.items.map((row) => ({ item: toTreeItem(row), parentKey: row.parentId ?? '' })) ?? [],[current],);const hasMore = current?.hasMore ?? false;- // `current` may still be the previous window while the larger one is in flight.- const isLoadingMore = isValidating && rows.length > 0 && rows.length < limit;+ const isLoadingMore = current?.isLoadingMore ?? false;+ // A page past the head can fail on its own; the head error never covers it.+ const loadMoreError = current?.loadMoreError;++ const retryLoadMore = useCallback(() => {+ if (entryKey) void loadMore(entryKey);+ }, [entryKey, loadMore]);const listRef = useRef<VListHandle>(null);const handleScroll = useCallback(() => {- if (!hasMore || isValidating) return;+ if (!entryKey || !hasMore || isLoadingMore || loadMoreError) return;const list = listRef.current;if (!list) return;- // Within roughly one viewport of the bottom: fetch the next window early+ // Within roughly one viewport of the bottom: fetch the next page early// enough that the user rarely hits the end of the list.const remaining = list.scrollSize - (list.scrollOffset + list.viewportSize);- if (remaining <= list.viewportSize) setLimit((current) => current + SEARCH_PAGE_SIZE);- }, [hasMore, isValidating]);+ if (remaining <= list.viewportSize) void loadMore(entryKey);+ }, [entryKey, hasMore, isLoadingMore, loadMore, loadMoreError]);// Bridge the debounce gap: the query is already non-empty but the fetch for// it has not been issued yet, so treat it as loading instead of "no results".const isWaitingForDebounce = !debouncedQuery || debouncedQuery !== query.trim();+ // A persisted head paints before the refresh lands, and a non-empty one is+ // content worth keeping; an empty one is not (see `resolveSearchViewState`).+ const viewState = resolveSearchViewState({ entry: current, error, isWaitingForDebounce });+const emptyState = (<Center gap={12} padding={24} style={{ height: '100%', textAlign: 'center' }}><Icon color={cssVar.colorTextQuaternary} icon={SearchXIcon} size={32} />@@ -121,16 +115,14 @@ const SearchResults = memo<SearchResultsProps>(({ libraryId, query }) => {return (<AsyncBoundary- data={current}+ data={viewState.data}empty={emptyState}error={error}errorVariant={'block'}- isEmpty={rows.length === 0}- // No current-key data yet (initial load or a query change) counts as loading- // unless the request already failed, so the error state can show.- isLoading={(!current && !error) || isWaitingForDebounce}+ isEmpty={viewState.isEmpty}+ isLoading={viewState.isLoading}loading={<TreeSkeleton />}- onRetry={() => mutate()}+ onRetry={() => revalidate()}><Flexbox paddingInline={4} style={{ height: '100%' }}><VList@@ -157,6 +149,16 @@ const SearchResults = memo<SearchResultsProps>(({ libraryId, query }) => {<TreeSkeleton count={3} /></div>)}+ {loadMoreError ? (+ <div key={'__load_more_error__'} style={{ paddingBottom: 2, paddingTop: 4 }}>+ <AsyncError+ error={loadMoreError}+ retrying={isLoadingMore}+ variant={'inline'}+ onRetry={retryLoadMore}+ />+ </div>+ ) : null}</VList></Flexbox></AsyncBoundary>diff --git a/src/features/ResourceManager/components/LibraryHierarchy/searchViewState.test.ts b/src/features/ResourceManager/components/LibraryHierarchy/searchViewState.test.tsnew file mode 100644index 00000000000..e4657f385cf--- /dev/null+++ b/src/features/ResourceManager/components/LibraryHierarchy/searchViewState.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it } from 'vitest';++import { resolveSearchViewState } from './searchViewState';++const params = { libraryId: 'kb-1', pageSize: 50, q: 'report' };+const page = (items: unknown[]) =>+ ({+ currentPage: 0,+ hasMore: false,+ items,+ pageSize: 50,+ searchParams: params,+ total: items.length,+ }) as any;+const row = { id: 'file-1', name: 'Report', parentId: null };++describe('resolveSearchViewState', () => {+ it('does not hand an EMPTY persisted page to the boundary, so a failed reopen can show the error', () => {+ const state = resolveSearchViewState({+ entry: page([]),+ error: new Error('offline'),+ isWaitingForDebounce: false,+ });++ expect(state.data).toBeUndefined();+ expect(state.isEmpty).toBe(false);+ expect(state.isLoading).toBe(false);+ });++ it('keeps a non-empty persisted page on screen while a background refresh fails', () => {+ const cached = page([row]);+ const state = resolveSearchViewState({+ entry: cached,+ error: new Error('offline'),+ isWaitingForDebounce: false,+ });++ expect(state.data).toBe(cached);+ expect(state.isEmpty).toBe(false);+ });++ it('reports no results only once the request settled with nothing', () => {+ const state = resolveSearchViewState({+ entry: page([]),+ error: undefined,+ isWaitingForDebounce: false,+ });++ expect(state.data).toBeUndefined();+ expect(state.isEmpty).toBe(true);+ expect(state.isLoading).toBe(false);+ });++ it('loads while the first request is in flight, and across the debounce gap', () => {+ expect(+ resolveSearchViewState({ entry: undefined, error: undefined, isWaitingForDebounce: false })+ .isLoading,+ ).toBe(true);+ expect(+ resolveSearchViewState({+ entry: page([row]),+ error: undefined,+ isWaitingForDebounce: true,+ }).isLoading,+ ).toBe(true);+ });++ it('shows a failed first load as an error, not as loading or no results', () => {+ const state = resolveSearchViewState({+ entry: undefined,+ error: new Error('offline'),+ isWaitingForDebounce: false,+ });++ expect(state.data).toBeUndefined();+ expect(state.isEmpty).toBe(false);+ expect(state.isLoading).toBe(false);+ });+});diff --git a/src/features/ResourceManager/components/LibraryHierarchy/searchViewState.ts b/src/features/ResourceManager/components/LibraryHierarchy/searchViewState.tsnew file mode 100644index 00000000000..75bcb118699--- /dev/null+++ b/src/features/ResourceManager/components/LibraryHierarchy/searchViewState.ts@@ -0,0 +1,41 @@+import type { HierarchySearchValue } from '@/features/ResourceManager/store/projection';++export interface SearchViewStateInput {+ /** The entry this query owns, if it has one yet. */+ entry?: HierarchySearchValue;+ error?: unknown;+ /** The keyword is typed but its fetch has not been issued yet (debounce gap). */+ isWaitingForDebounce: boolean;+}++export interface SearchViewState {+ /** Content the boundary may keep on screen while a refresh runs or fails. */+ data?: HierarchySearchValue;+ /** The query matched nothing, once the request settled β never while it failed. */+ isEmpty: boolean;+ /** First load, or the debounce gap before it. */+ isLoading: boolean;+}++/**+ * What the sidebar search should show for the query on screen.+ *+ * A persisted head paints before the refresh lands, and a NON-EMPTY one is+ * content worth keeping: a background refresh that fails must not replace the+ * rows on screen with a full-surface error. An EMPTY persisted page is not β it+ * cannot be told apart from "never loaded", so treating it as settled would let+ * a failed reopen report "no results" and hide the retry instead of the error.+ */+export const resolveSearchViewState = ({+ entry,+ error,+ isWaitingForDebounce,+}: SearchViewStateInput): SearchViewState => {+ const hasRows = (entry?.items.length ?? 0) > 0;++ return {+ data: hasRows ? entry : undefined,+ isEmpty: !hasRows && !error,+ isLoading: (!entry && !error) || isWaitingForDebounce,+ };+};diff --git a/src/features/ResourceManager/store/action.test.ts b/src/features/ResourceManager/store/action.test.tsindex 4bab743c33f..b8aeff49ad6 100644--- a/src/features/ResourceManager/store/action.test.ts+++ b/src/features/ResourceManager/store/action.test.ts@@ -2,9 +2,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { initialState as fileInitialState } from '@/store/file/initialState';import { useFileStore } from '@/store/file/store';+import type { ResourceItem } from '@/types/resource';import { useResourceManagerStore } from '.';import { initialState } from './initialState';+import { explorerSearchResource } from './projection';const { mockDeleteResourcesByQuery, mockDropNodes, mockResolveSelectionIds, mockRevalidateTree } =vi.hoisted(() => ({@@ -178,6 +180,72 @@ describe('resource manager store actions', () => {expect(mockDropNodes).toHaveBeenCalledWith(['file-1', 'file-2'], 'folder-a');});+ // Regression: the explorer's search overlay mirrors cached replica pages, so+ // a deleted hit kept showing there (and came back after a reload) until the+ // row was dropped from the cache as part of the delete.+ it('should drop the deleted rows from the cached explorer searches', async () => {+ const params = { pageSize: 50, q: 'report' } as any;+ const key = explorerSearchResource.key(params);+ const row = (id: string): ResourceItem => ({ fileType: 'custom/document', id, name: id });++ useResourceManagerStore.setState({+ explorerSearchEntries: {+ [key]: {+ currentPage: 0,+ hasMore: false,+ items: [row('file-1'), row('file-2')],+ pageSize: 50,+ searchParams: params,+ total: 2,+ },+ },+ selectAllState: 'loaded',+ selectedFileIds: ['file-1'],+ });+ useFileStore.setState({+ deleteResources: vi.fn().mockResolvedValue(undefined),+ queryParams: { parentId: 'folder-a' } as any,+ } as any);++ await useResourceManagerStore.getState().onActionClick('delete');++ const entry = useResourceManagerStore.getState().explorerSearchEntries[key];+ expect(entry?.items.map((item) => item.id)).toEqual(['file-2']);+ expect(entry?.total).toBe(1);+ });++ it('should drop the cached explorer searches when the deleted set is server-only', async () => {+ const params = { pageSize: 50, q: 'report' } as any;+ const key = explorerSearchResource.key(params);++ useResourceManagerStore.setState({+ explorerSearchEntries: {+ [key]: {+ currentPage: 0,+ hasMore: false,+ items: [{ fileType: 'custom/document', id: 'file-1', name: 'file-1' }],+ pageSize: 50,+ searchParams: params,+ total: 1,+ },+ },+ selectAllState: 'all',+ selectedFileIds: [],+ });+ useFileStore.setState({+ clearCurrentQueryResources: vi.fn(),+ deleteResources: vi.fn(),+ queryParams: { parentId: 'folder-a' } as any,+ } as any);+ mockDeleteResourcesByQuery.mockResolvedValue({ count: 1 });++ await useResourceManagerStore.getState().onActionClick('delete');++ // No id is known client-side, so the cached searches are dropped whole and+ // the refetch paints whatever survived.+ expect(useResourceManagerStore.getState().explorerSearchEntries[key]).toBeUndefined();+ });+it('should refresh the listed folder when the deleted set is only known to the server', async () => {useResourceManagerStore.setState({ selectAllState: 'all', selectedFileIds: [] });useFileStore.setState({diff --git a/src/features/ResourceManager/store/action.ts b/src/features/ResourceManager/store/action.tsindex a504a7b125f..80f7975383f 100644--- a/src/features/ResourceManager/store/action.ts+++ b/src/features/ResourceManager/store/action.ts@@ -1,14 +1,36 @@+import { useLayoutEffect } from 'react';import type { StateCreator } from 'zustand/vanilla';import type { ResourceManagerMode } from '@/features/ResourceManager';+import {+ createReplicaSlice,+ readReplicaStoredKeys,+ recordLens,+ type ReplicaPageResult,+ type ReplicaSyncResult,+ revalidateReplica,+} from '@/libs/replica';import { useFileStore } from '@/store/file';import type { StoreSetter } from '@/store/types';import { flattenActions } from '@/store/utils/flattenActions';import type { FilesTabs, ResourceSourceFilter, SortType } from '@/types/files';+import type { ResourceItem } from '@/types/resource';+import { setNamespace } from '@/utils/storeDebug';import type { ResourceListVisibilityFilter, SelectAllState, State, ViewMode } from './initialState';import { DEFAULT_WORKSPACE_LIST_VISIBILITY, initialState } from './initialState';import { readPersistedResourceMode, writePersistedResourceMode } from './modePersistence';+import {+ DEFAULT_SEARCH_PAGE_SIZE,+ type ExplorerSearchParams,+ explorerSearchResource,+ type ExplorerSearchValue,+ type HierarchySearchParams,+ hierarchySearchResource,+ type HierarchySearchValue,+} from './projection';++const n = setNamespace('resourceManager');export type MultiSelectActionType =| 'addToKnowledgeBase'@@ -28,16 +50,269 @@ export type Store = Action & State;type Setter = StoreSetter<Store>;+/**+ * One page of a search list. `cursor` is the page index (0 = head), so the+ * replica owns the offset and a query change repaints from its own head page.+ */+/**+ * A search page as the replica needs it.+ *+ * The endpoint also reports `hasMore`, which the replica cannot read: it infers+ * "another page" from a full page when `total` is unknown. So an exact multiple+ * of the page size β the endpoint then answers `hasMore: false` with no `total` β+ * would keep a dead "load more" and fire one request for an empty page. Recording+ * the terminal count the flag implies is how that signal survives.+ */+const toSearchPageResult = (+ response: { hasMore: boolean; items: ResourceItem[]; total?: number },+ cursor: number | undefined,+ pageSize: number,+): ReplicaPageResult<ResourceItem, number> => ({+ items: response.items,+ total:+ response.total ??+ (response.hasMore ? undefined : (cursor ?? 0) * pageSize + response.items.length),+});++const fetchExplorerSearchPage = async (+ params: ExplorerSearchParams,+ cursor?: number,+): Promise<ReplicaPageResult<ResourceItem, number>> => {+ const { resourceService } = await import('@/services/resource');+ const pageSize = params.pageSize ?? DEFAULT_SEARCH_PAGE_SIZE;++ const response = await resourceService.queryResources({+ category: params.category,+ includeContentPreview: params.includeContentPreview,+ libraryId: params.libraryId,+ limit: pageSize,+ offset: (cursor ?? 0) * pageSize,+ q: params.q,+ showFilesInKnowledgeBase: false,+ sourceFilter: params.sourceFilter,+ visibility: params.visibility,+ });++ return toSearchPageResult(response, cursor, pageSize);+};++const fetchHierarchySearchPage = async (+ params: HierarchySearchParams,+ cursor?: number,+): Promise<ReplicaPageResult<ResourceItem, number>> => {+ const { resourceService } = await import('@/services/resource');+ const pageSize = params.pageSize ?? DEFAULT_SEARCH_PAGE_SIZE;++ const response = await resourceService.queryResources({+ libraryId: params.libraryId,+ limit: pageSize,+ offset: (cursor ?? 0) * pageSize,+ q: params.q,+ showFilesInKnowledgeBase: false,+ });++ return toSearchPageResult(response, cursor, pageSize);+};++/**+ * How many distinct queries per search surface keep a replica entry. The one+ * the user is on is always the most recent, so bounding the list bounds memory+ * and IndexedDB together: searching all day cannot grow either without limit,+ * and the queries just used still paint from their own rows when revisited.+ */+export const MAX_RECENT_SEARCHES = 8;++/** Where the explorer search views live in the store β one entry per query. */+const explorerSearchLens = recordLens<Store, ExplorerSearchValue>('explorerSearchEntries');++/** Where the library sidebar search views live β one entry per (library, keyword). */+const hierarchySearchLens = recordLens<Store, HierarchySearchValue>('hierarchySearchEntries');++/**+ * Either search surface. Both key their persisted rows by the entry key alone+ * (neither sets a replica `query`), so the stored index holds entry keys.+ */+type SearchReplicaResource = typeof explorerSearchResource | typeof hierarchySearchResource;++/** The invalidation surface both search slices expose. */+type SearchReplicaSlice = {+ collapse: (key: string) => unknown;+ remove: (key: string) => unknown;+};+export class ResourceManagerStoreActionImpl {readonly #get: () => Store;readonly #set: Setter;+ readonly #explorerSearch;+ readonly #hierarchySearch;+ /** Query entry keys each surface has used, oldest first (see `#trackRecentSearch`). */+ readonly #recentExplorerSearches: string[] = [];+ readonly #recentHierarchySearches: string[] = [];+ /** Identity each recency list currently belongs to (see `#seedRecentSearches`). */+ readonly #recentSearchScope = new WeakMap<string[], string>();+ /** Recency lists whose persisted keys are already folded in. */+ readonly #seededRecentSearches = new WeakSet<string[]>();+ /**+ * The search entry on screen per surface, if any. The sync driver revalidates+ * only mounted queries, so these are the entries whose head a refresh can+ * repair (see `#invalidateSearchSurface`).+ */+ #activeExplorerSearchKey?: string;+ #activeHierarchySearchKey?: string;constructor(set: Setter, get: () => Store, _api?: unknown) {void _api;this.#set = set;this.#get = get;++ this.#explorerSearch = createReplicaSlice(explorerSearchResource, {+ actionPrefix: n('explorerSearch'),+ fetcher: fetchExplorerSearchPage,+ get,+ set,+ stateKey: 'explorerSearchReplica',+ view: explorerSearchLens,+ // The keyword is part of the entry identity, so the mounted surface can+ // tell whether the painted rows still answer the request on screen.+ viewFields: (params) => ({ searchParams: params }),+ });++ this.#hierarchySearch = createReplicaSlice(hierarchySearchResource, {+ actionPrefix: n('hierarchySearch'),+ fetcher: fetchHierarchySearchPage,+ get,+ set,+ stateKey: 'hierarchySearchReplica',+ view: hierarchySearchLens,+ viewFields: (params) => ({ searchParams: params }),+ });}+ /**+ * Fold the keys an earlier session persisted into a surface's recency list,+ * once per list per scope.+ *+ * {@link MAX_RECENT_SEARCHES} only bounds what the list knows about, and a+ * list that starts empty on every page load bounds nothing across reloads:+ * each session would persist up to the cap again while the rows of every+ * session before it stayed in IndexedDB. Seeding the list from the persisted+ * index makes the window β and with it what eviction drops β span sessions.+ */+ #seedRecentSearches = (+ recents: string[],+ resource: SearchReplicaResource,+ drop: (key: string) => void,+ ): void => {+ const scope = resource.scope.get();+ if (this.#recentSearchScope.get(recents) !== scope) {+ // Another identity owns the partition: the keys this list learned stood+ // for the previous scope's rows, so start the window over for this one.+ recents.length = 0;+ this.#recentSearchScope.set(recents, scope);+ this.#seededRecentSearches.delete(recents);+ }+ if (this.#seededRecentSearches.has(recents)) return;+ this.#seededRecentSearches.add(recents);++ void readReplicaStoredKeys(resource).then((persisted) => {+ // A scope switch while the index was read voids this seed.+ if (this.#recentSearchScope.get(recents) !== scope) return;+ // The index is append-ordered (oldest first); prepending keeps that order,+ // so eviction β which takes from the front β drops the least recently used+ // persisted query first.+ for (const persistedKey of [...persisted].reverse()) {+ if (!recents.includes(persistedKey)) recents.unshift(persistedKey);+ }+ this.#evictOldestSearches(recents, drop);+ });+ };++ #evictOldestSearches = (recents: string[], drop: (key: string) => void): void => {+ while (recents.length > MAX_RECENT_SEARCHES) {+ const oldest = recents.shift();+ if (oldest) drop(oldest);+ }+ };++ /**+ * Remember a query the user is looking at, and drop the oldest ones past+ * {@link MAX_RECENT_SEARCHES}. Dropping removes the replica entry (memory)+ * *and* its persisted projection, so both stay bounded no matter how many+ * keywords are tried. Called from a layout effect, never during render.+ */+ #trackRecentSearch = (+ recents: string[],+ key: string,+ drop: (key: string) => void,+ resource: SearchReplicaResource,+ ): void => {+ this.#seedRecentSearches(recents, resource, drop);+ const existing = recents.indexOf(key);+ if (existing !== -1) recents.splice(existing, 1);+ recents.push(key);+ this.#evictOldestSearches(recents, drop);+ };++ /**+ * Invalidate one search surface.+ *+ * A rename / move / delete can touch a row a search had loaded beyond its head+ * page. Revalidating only re-runs the head request and the replica keeps the+ * rows the user already scrolled to, so a stale hit would linger in that tail;+ * dropping the loaded pages first means the head that comes back is the only+ * thing left to show.+ *+ * Only the entry on screen gets that treatment. The driver revalidates just+ * mounted queries, so every other entry β a search left behind in memory, or+ * one only an earlier session had persisted β would keep its stale head+ * forever (and offline, indefinitely). Those are dropped outright: a revisit+ * then has nothing stale to hydrate.+ */+ #invalidateSearchSurface = async (+ resource: SearchReplicaResource,+ entries: Record<string, unknown>,+ activeKey: string | undefined,+ slice: SearchReplicaSlice,+ ): Promise<void> => {+ const loaded = new Set(Object.keys(entries));+ for (const key of loaded) {+ if (key === activeKey) slice.collapse(key);+ else slice.remove(key);+ }++ const scope = resource.scope.get();+ const persisted = await readReplicaStoredKeys(resource);+ // The identity can change while the index is read; those rows are not ours+ // to touch, and `remove` resolves against the *current* scope.+ if (resource.scope.get() !== scope) return;+ for (const key of persisted) {+ if (!loaded.has(key)) slice.remove(key);+ }+ };++ /** Invalidate the sidebar's cached searches (see `#invalidateSearchSurface`). */+ collapseHierarchySearch = async (): Promise<void> =>+ this.#invalidateSearchSurface(+ hierarchySearchResource,+ this.#get().hierarchySearchEntries,+ this.#activeHierarchySearchKey,+ this.#hierarchySearch,+ );++ /**+ * Invalidate the explorer's search overlay after a mutation it cannot patch+ * by id, then refresh the query on screen.+ */+ #invalidateExplorerSearch = async (): Promise<void> => {+ await this.#invalidateSearchSurface(+ explorerSearchResource,+ this.#get().explorerSearchEntries,+ this.#activeExplorerSearchKey,+ this.#explorerSearch,+ );+ await revalidateReplica(explorerSearchResource);+ };+clearSelectAllState = (): void => {this.#set({ selectAllState: 'none', selectedFileIds: [], selectionTotal: undefined });};@@ -70,6 +345,10 @@ export class ResourceManagerStoreActionImpl {fileStore.queryParams as any,selectedFileIds,);+ // The deleted set is only known to the server, so the cached searches+ // cannot drop those rows by id: invalidate the surfaces instead and+ // let the refetch paint whatever survived.+ void this.#invalidateExplorerSearch();fileStore.clearCurrentQueryResources();// The server applies the caller's workspace role: members delete// only their own rows, while owners may delete the full query scope.@@ -89,6 +368,12 @@ export class ResourceManagerStoreActionImpl {await fileStore.deleteResources(resourceIds);void useTreeStore.getState().dropNodes(resourceIds, currentFolderKey);+ // The explorer's own list drops the rows optimistically; the overlay+ // mirrors cached replica pages, so drop them there too β from memory and+ // from every stored page, loaded here or not β or a deleted hit would be+ // painted again, on screen and on the next reload.+ for (const id of resourceIds) this.#explorerSearch.updateEntity(id, () => undefined);+ void revalidateReplica(explorerSearchResource);this.clearSelectAllState();return;@@ -309,6 +594,72 @@ export class ResourceManagerStoreActionImpl {setViewMode = (viewMode: ViewMode): void => {this.#set({ viewMode });};++ /**+ * Fetch orchestration for the explorer's search overlay. It only schedules the+ * sync; read the rows from `explorerSearchEntries[explorerSearchResource.key(params)]`.+ */+ useFetchExplorerSearch = (params: ExplorerSearchParams | null): ReplicaSyncResult => {+ const key = params ? explorerSearchResource.key(params) : undefined;+ useLayoutEffect(() => {+ if (key) {+ this.#trackRecentSearch(+ this.#recentExplorerSearches,+ key,+ (stale) => this.#explorerSearch.remove(stale),+ explorerSearchResource,+ );+ }+ }, [key]);+ // The driver revalidates only mounted queries, so remember which entry the+ // overlay is showing: the invalidation below collapses that one's head (the+ // refetch repairs it) and drops the heads of the rest.+ useLayoutEffect(() => {+ if (!key) return;+ this.#activeExplorerSearchKey = key;+ return () => {+ if (this.#activeExplorerSearchKey === key) this.#activeExplorerSearchKey = undefined;+ };+ }, [key]);+ return this.#explorerSearch.useSync(params);+ };++ /**+ * Fetch orchestration for the library sidebar's flat search list. It only+ * schedules the sync; read the rows from+ * `hierarchySearchEntries[hierarchySearchResource.key(params)]`.+ */+ useFetchHierarchySearch = (params: HierarchySearchParams | null): ReplicaSyncResult => {+ const key = params ? hierarchySearchResource.key(params) : undefined;+ useLayoutEffect(() => {+ if (key) {+ this.#trackRecentSearch(+ this.#recentHierarchySearches,+ key,+ (stale) => this.#hierarchySearch.remove(stale),+ hierarchySearchResource,+ );+ }+ }, [key]);+ // The driver revalidates only mounted queries, so remember which entry the+ // sidebar is showing: `collapseHierarchySearch` collapses that one's head+ // (the refetch repairs it) and drops the heads of the rest.+ useLayoutEffect(() => {+ if (!key) return;+ this.#activeHierarchySearchKey = key;+ return () => {+ if (this.#activeHierarchySearchKey === key) this.#activeHierarchySearchKey = undefined;+ };+ }, [key]);+ return this.#hierarchySearch.useSync(params);+ };++ /** Append the next page of the explorer search (the entry's own query). */+ loadMoreExplorerSearch = async (key: string): Promise<void> => this.#explorerSearch.loadMore(key);++ /** Append the next page of the sidebar search (the entry's own query). */+ loadMoreHierarchySearch = async (key: string): Promise<void> =>+ this.#hierarchySearch.loadMore(key);}export type Action = Pick<ResourceManagerStoreActionImpl, keyof ResourceManagerStoreActionImpl>;diff --git a/src/features/ResourceManager/store/initialState.ts b/src/features/ResourceManager/store/initialState.tsindex 712a8f3deb0..c4f015a6577 100644--- a/src/features/ResourceManager/store/initialState.ts+++ b/src/features/ResourceManager/store/initialState.ts@@ -1,6 +1,9 @@import { type ResourceManagerMode } from '@/features/ResourceManager';+import { createReplicaState, type ReplicaState } from '@/libs/replica';import { FilesTabs, type ResourceSourceFilter, SortType } from '@/types/files';+import { type ExplorerSearchValue, type HierarchySearchValue } from './projection';+export type ViewMode = 'list' | 'masonry';export type SelectAllState = 'all' | 'loaded' | 'none';@@ -26,7 +29,32 @@ export type ResourceListVisibilityFilter = 'private' | 'workspace';*/export const DEFAULT_WORKSPACE_LIST_VISIBILITY: ResourceListVisibilityFilter = 'workspace';-export interface State {+/**+ * The ResourceManager's two search surfaces as `@lobechat/replica` views.+ *+ * Both were bare `useClientDataSWR` entries before: the rows only lived in the+ * SWR cache, so re-opening a search (or coming back to the surface) had to wait+ * for a network round-trip before anything was on screen. The replica paints the+ * persisted head page first and lets the network confirm it.+ */+export interface ResourceSearchState {+ /**+ * Replica views of the explorer's search overlay (`SearchResultsOverlay`),+ * one entry per query so revisiting a keyword restores its own rows.+ */+ explorerSearchEntries: Record<string, ExplorerSearchValue>;+ /** Replica bookkeeping of `explorerSearchEntries`. */+ explorerSearchReplica: ReplicaState<ExplorerSearchValue>;+ /**+ * Replica views of the library sidebar's flat search list, one entry per+ * (library, keyword).+ */+ hierarchySearchEntries: Record<string, HierarchySearchValue>;+ /** Replica bookkeeping of `hierarchySearchEntries`. */+ hierarchySearchReplica: ReplicaState<HierarchySearchValue>;+}++export interface State extends ResourceSearchState {/*** Current file category filter*/@@ -124,6 +152,10 @@ export const initialState: State = {currentViewItemId: undefined,detailPanelId: undefined,detailPanelIsPage: false,+ explorerSearchEntries: {},+ explorerSearchReplica: createReplicaState(),+ hierarchySearchEntries: {},+ hierarchySearchReplica: createReplicaState(),libraryId: undefined,librarySearchQuery: '',// Personal mode keeps the historical neutral value; workspace mode hydratesdiff --git a/src/features/ResourceManager/store/projection.ts b/src/features/ResourceManager/store/projection.tsnew file mode 100644index 00000000000..27fa77b2b8d--- /dev/null+++ b/src/features/ResourceManager/store/projection.ts@@ -0,0 +1,98 @@+import { definePagedReplica, type ReplicaPagedData, stableQueryKey } from '@/libs/replica';+import { type FilesTabs, type ResourceSourceFilter } from '@/types/files';+import { type ResourceItem } from '@/types/resource';++/**+ * Query identity of the explorer's search overlay (`q` + the chips the user is+ * looking through). `page` is NOT here β it is the paging cursor, owned by the+ * replica.+ */+export interface ExplorerSearchParams {+ category?: FilesTabs;+ includeContentPreview?: boolean;+ libraryId?: string;+ pageSize?: number;+ q: string;+ sourceFilter?: ResourceSourceFilter;+ visibility?: 'private' | 'public';+}++/** Query identity of the library sidebar's flat search list. */+export interface HierarchySearchParams {+ libraryId: string;+ pageSize?: number;+ q: string;+}++/**+ * Each search surface keeps ONE replica entry **per query**, exactly like the+ * SWR cache it replaced. The ResourceManager shows one query at a time, but+ * keying entries by the query (not by a shared constant) is what lets coming+ * back to a keyword paint its own rows again, and keeps a projection taken+ * under another search from ever merging with the loaded pages. The store+ * bounds how many of these entries survive, so routine searching cannot grow+ * memory or IndexedDB without limit (see `MAX_RECENT_SEARCHES`).+ */++/** Rows fetched per page when the caller does not name one (the legacy `limit: 50`). */+export const DEFAULT_SEARCH_PAGE_SIZE = 50;++/** The replica value plus the query it answers, so a surface can tell whether it is current. */+export type SearchReplicaValue<TParams> = ReplicaPagedData<ResourceItem, number> & {+ /** Absent only on a view written before its query identity was known. */+ searchParams?: TParams;+};++export type ExplorerSearchValue = SearchReplicaValue<ExplorerSearchParams>;+export type HierarchySearchValue = SearchReplicaValue<HierarchySearchParams>;++/**+ * The explorer search overlay (`resourceService.queryResources` narrowed by a+ * keyword): a local-first paged replica, so re-opening a search paints the+ * persisted head page on the first frame, the network confirms it, and "load+ * more" appends further pages.+ */+export const explorerSearchResource = definePagedReplica<+ ExplorerSearchParams,+ ResourceItem,+ number,+ ExplorerSearchValue+>({+ // One entry per query: the keyword and every narrowing chip the user picked.+ key: (params) => stableQueryKey(params),+ name: 'resourceManagerSearch',+ paging: {+ direction: 'forward',+ getId: (item) => item.id,+ mode: 'offset',+ // A reload repaints what the first network page would show, never a stale tail.+ persist: { pages: 1 },+ },+ storage: 'indexedDB',+ version: 1,+});++/**+ * The library sidebar's flat search list, which replaces the folder tree while+ * the user has a query typed. It grows by whole pages as the user scrolls,+ * which is exactly an `offset` replica's `loadMore`, so the rows keep the+ * persisted head page across a reopen instead of flashing a skeleton.+ */+export const hierarchySearchResource = definePagedReplica<+ HierarchySearchParams,+ ResourceItem,+ number,+ HierarchySearchValue+>({+ // One entry per (library, keyword) so revisiting a keyword restores its rows.+ key: (params) => stableQueryKey(params),+ name: 'resourceManagerHierarchySearch',+ paging: {+ direction: 'forward',+ getId: (item) => item.id,+ mode: 'offset',+ persist: { pages: 1 },+ },+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/features/ResourceManager/store/replica.test.ts b/src/features/ResourceManager/store/replica.test.tsnew file mode 100644index 00000000000..2ee3ac9eccb--- /dev/null+++ b/src/features/ResourceManager/store/replica.test.ts@@ -0,0 +1,598 @@+/**+ * @vitest-environment happy-dom+ *+ * The ResourceManager's two search surfaces are `@lobechat/replica` paged+ * resources owned by the feature store: the persisted head page paints before+ * the network answers, the response confirms and persists it, "load more"+ * appends through the engine, and a new keyword repaints from its own head page+ * instead of merging into the previous search.+ */+import { randomUUID } from 'node:crypto';++import { act, cleanup, 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, REPLICA_INDEX_KEY } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { resourceService } from '@/services/resource';+import type { ResourceItem } from '@/types/resource';++import { MAX_RECENT_SEARCHES } from './action';+import { useResourceManagerStore } from './index';+import { initialState } from './initialState';+import {+ DEFAULT_SEARCH_PAGE_SIZE,+ type ExplorerSearchParams,+ explorerSearchResource,+ type HierarchySearchParams,+ hierarchySearchResource,+} from './projection';++const EXPLORER_PARAMS: ExplorerSearchParams = {+ pageSize: DEFAULT_SEARCH_PAGE_SIZE,+ q: 'report',+};+const EXPLORER_KEY = explorerSearchResource.storageKey(EXPLORER_PARAMS);++const HIERARCHY_PARAMS: HierarchySearchParams = {+ libraryId: 'kb-1',+ pageSize: DEFAULT_SEARCH_PAGE_SIZE,+ q: 'report',+};+const HIERARCHY_KEY = hierarchySearchResource.storageKey(HIERARCHY_PARAMS);++/**+ * Every query keeps its own replica entry, so the tests read (and assert on)+ * the entry named by the query, exactly as the components do.+ */+const explorerKeyOf = (params: ExplorerSearchParams) => explorerSearchResource.key(params);+const hierarchyKeyOf = (params: HierarchySearchParams) => hierarchySearchResource.key(params);+const explorerEntry = (params: ExplorerSearchParams) =>+ useResourceManagerStore.getState().explorerSearchEntries[explorerKeyOf(params)];+const hierarchyEntry = (params: HierarchySearchParams) =>+ useResourceManagerStore.getState().hierarchySearchEntries[hierarchyKeyOf(params)];++const item = (id: string): ResourceItem => ({ fileType: 'custom/document', id, name: id });++const itemsOf = (length: number, offset = 0) =>+ Array.from({ length }, (_, i) => item(`file-${i + offset}`));++const page = (items: ResourceItem[], total?: number) => ({+ hasMore: total === undefined ? items.length >= DEFAULT_SEARCH_PAGE_SIZE : total > items.length,+ items,+ total,+});++const ids = (list: { items: ResourceItem[] } | undefined) => list?.items.map((entry) => entry.id);++/** Never-resolving fetch: the first frame can only come from storage. */+const pending = () => new Promise<never>(() => {});++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,+ );++describe('ResourceManager search replicas', () => {+ const scopes = new Set<string>();+ let scope = '';+ let fetchSpy: ReturnType<typeof vi.spyOn>;++ 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);+ };++ beforeEach(() => {+ useScope(`rm-user-${randomUUID()}:personal`);+ fetchSpy = vi.spyOn(resourceService, 'queryResources');+ act(() => useResourceManagerStore.setState(initialState));+ });++ afterEach(async () => {+ cleanup();+ await Promise.all(+ [...scopes]+ .flatMap((value) =>+ [EXPLORER_KEY, HIERARCHY_KEY].map((queryKey) =>+ Promise.all([+ explorerSearchResource.storage!.remove({ queryKey, scope: value }),+ hierarchySearchResource.storage!.remove({ queryKey, scope: value }),+ ]),+ ),+ )+ .flat(),+ );+ await Promise.all(+ [...scopes].flatMap((value) =>+ [explorerSearchResource, hierarchySearchResource].map((resource) =>+ resource.storage!.remove({ queryKey: REPLICA_INDEX_KEY, scope: value }),+ ),+ ),+ );+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ it('paints the persisted explorer search head page before the network answers', async () => {+ await explorerSearchResource.storage!.set(+ { queryKey: EXPLORER_KEY, scope },+ {+ data: {+ currentPage: 0,+ hasMore: true,+ items: [item('cached-1')],+ pageSize: DEFAULT_SEARCH_PAGE_SIZE,+ searchParams: EXPLORER_PARAMS,+ total: 60,+ },+ updatedAt: 1,+ },+ );+ fetchSpy.mockImplementation(pending);++ const hook = renderHook(+ () => ({+ entry: useResourceManagerStore(+ (s) => s.explorerSearchEntries[explorerKeyOf(EXPLORER_PARAMS)],+ ),+ sync: useResourceManagerStore((s) => s.useFetchExplorerSearch)(EXPLORER_PARAMS),+ }),+ { wrapper },+ );++ await waitFor(() => expect(ids(explorerEntry(EXPLORER_PARAMS))).toEqual(['cached-1']));+ expect(hook.result.current.sync.isHydrated).toBe(true);+ expect(hook.result.current.sync.isValidating).toBe(true);+ });++ it('replaces the explorer search head page with the response and persists it', async () => {+ fetchSpy.mockResolvedValue(page([item('a'), item('b')], 60));++ renderHook(() => useResourceManagerStore((s) => s.useFetchExplorerSearch)(EXPLORER_PARAMS), {+ wrapper,+ });++ await waitFor(() => expect(ids(explorerEntry(EXPLORER_PARAMS))).toEqual(['a', 'b']));+ expect(explorerEntry(EXPLORER_PARAMS)).toMatchObject({+ hasMore: true,+ searchParams: EXPLORER_PARAMS,+ total: 60,+ });++ await waitFor(async () => {+ const row = await explorerSearchResource.storage!.get({ queryKey: EXPLORER_KEY, scope });+ expect(ids(row?.data)).toEqual(['a', 'b']);+ });+ });++ it('repaints the explorer search from its own head page when the keyword changes', async () => {+ fetchSpy+ .mockResolvedValueOnce({+ hasMore: true,+ items: itemsOf(DEFAULT_SEARCH_PAGE_SIZE),+ total: 100,+ })+ .mockResolvedValueOnce({ hasMore: false, items: [item('foo-1')], total: 1 });++ const hook = renderHook(+ (props: { q: string }) =>+ useResourceManagerStore((s) => s.useFetchExplorerSearch)({+ pageSize: DEFAULT_SEARCH_PAGE_SIZE,+ q: props.q,+ }),+ { initialProps: { q: 'report' }, wrapper },+ );++ await waitFor(() =>+ expect(+ explorerEntry({ pageSize: DEFAULT_SEARCH_PAGE_SIZE, q: 'report' })?.items,+ ).toHaveLength(DEFAULT_SEARCH_PAGE_SIZE),+ );++ hook.rerender({ q: 'foo' });++ await waitFor(() =>+ expect(ids(explorerEntry({ pageSize: DEFAULT_SEARCH_PAGE_SIZE, q: 'foo' }))).toEqual([+ 'foo-1',+ ]),+ );+ // Each keyword owns its entry: the new one starts at its own head page and+ // the rows of the previous search never merge into it.+ expect(explorerEntry({ pageSize: DEFAULT_SEARCH_PAGE_SIZE, q: 'foo' })).toMatchObject({+ currentPage: 0,+ searchParams: { pageSize: DEFAULT_SEARCH_PAGE_SIZE, q: 'foo' },+ total: 1,+ });+ expect(explorerEntry({ pageSize: DEFAULT_SEARCH_PAGE_SIZE, q: 'report' })?.items).toHaveLength(+ DEFAULT_SEARCH_PAGE_SIZE,+ );+ });++ it('appends the next sidebar search page through the engine', async () => {+ fetchSpy+ .mockResolvedValueOnce({+ hasMore: true,+ items: itemsOf(DEFAULT_SEARCH_PAGE_SIZE),+ total: 100,+ })+ .mockResolvedValueOnce({+ hasMore: true,+ items: itemsOf(DEFAULT_SEARCH_PAGE_SIZE, DEFAULT_SEARCH_PAGE_SIZE),+ total: 100,+ });++ const hook = renderHook(+ () => ({+ loadMore: useResourceManagerStore((s) => s.loadMoreHierarchySearch),+ sync: useResourceManagerStore((s) => s.useFetchHierarchySearch)(HIERARCHY_PARAMS),+ }),+ { wrapper },+ );++ await waitFor(() =>+ expect(hierarchyEntry(HIERARCHY_PARAMS)?.items).toHaveLength(DEFAULT_SEARCH_PAGE_SIZE),+ );++ await act(async () => {+ await hook.result.current.loadMore(hierarchyKeyOf(HIERARCHY_PARAMS));+ });++ const list = hierarchyEntry(HIERARCHY_PARAMS)!;+ expect(list.items).toHaveLength(DEFAULT_SEARCH_PAGE_SIZE * 2);+ expect(list.items[DEFAULT_SEARCH_PAGE_SIZE].id).toBe(`file-${DEFAULT_SEARCH_PAGE_SIZE}`);+ expect(list.currentPage).toBe(1);+ // The replica owns the cursor: the second page of the loaded query.+ expect(fetchSpy).toHaveBeenLastCalledWith(+ expect.objectContaining({+ libraryId: 'kb-1',+ limit: DEFAULT_SEARCH_PAGE_SIZE,+ offset: DEFAULT_SEARCH_PAGE_SIZE,+ q: 'report',+ }),+ );+ });++ it('keeps the explorer and sidebar searches in separate entries', async () => {+ fetchSpy.mockImplementation(({ libraryId }: { libraryId?: string }) =>+ Promise.resolve(page(libraryId ? [item('kb-hit')] : [item('explorer-hit')], 1)),+ );++ renderHook(+ () => ({+ explorer: useResourceManagerStore((s) => s.useFetchExplorerSearch)(EXPLORER_PARAMS),+ hierarchy: useResourceManagerStore((s) => s.useFetchHierarchySearch)(HIERARCHY_PARAMS),+ }),+ { wrapper },+ );++ await waitFor(() => expect(ids(explorerEntry(EXPLORER_PARAMS))).toEqual(['explorer-hit']));+ await waitFor(() => expect(ids(hierarchyEntry(HIERARCHY_PARAMS))).toEqual(['kb-hit']));+ });++ it('does not fetch another sidebar page when the head page is the last one', async () => {+ fetchSpy.mockResolvedValue({ hasMore: false, items: [item('only')], total: 1 });++ const hook = renderHook(+ () => ({+ loadMore: useResourceManagerStore((s) => s.loadMoreHierarchySearch),+ sync: useResourceManagerStore((s) => s.useFetchHierarchySearch)(HIERARCHY_PARAMS),+ }),+ { wrapper },+ );++ await waitFor(() => expect(hierarchyEntry(HIERARCHY_PARAMS)?.items).toHaveLength(1));+ expect(hierarchyEntry(HIERARCHY_PARAMS)?.hasMore).toBe(false);++ await act(async () => {+ await hook.result.current.loadMore(hierarchyKeyOf(HIERARCHY_PARAMS));+ });++ expect(fetchSpy).toHaveBeenCalledTimes(1);+ });++ it('restores a revisited keyword from its own entry (no waiting for the network)', async () => {+ fetchSpy.mockImplementation(({ q }: { q?: string }) =>+ Promise.resolve(page([item(`${q}-hit`)], 1)),+ );++ const hook = renderHook(+ (props: { q: string }) =>+ useResourceManagerStore((s) => s.useFetchExplorerSearch)({+ pageSize: DEFAULT_SEARCH_PAGE_SIZE,+ q: props.q,+ }),+ { initialProps: { q: 'report' }, wrapper },+ );++ const reportParams = { pageSize: DEFAULT_SEARCH_PAGE_SIZE, q: 'report' };+ const fooParams = { pageSize: DEFAULT_SEARCH_PAGE_SIZE, q: 'foo' };++ await waitFor(() => expect(ids(explorerEntry(reportParams))).toEqual(['report-hit']));++ hook.rerender({ q: 'foo' });+ await waitFor(() => expect(ids(explorerEntry(fooParams))).toEqual(['foo-hit']));++ hook.rerender({ q: 'report' });++ // The previous search kept its own entry, so its rows are back on the very+ // next render β the component never falls back to a waiting state.+ expect(ids(explorerEntry(reportParams))).toEqual(['report-hit']);+ expect(ids(explorerEntry(fooParams))).toEqual(['foo-hit']);+ });++ it('bounds how many search entries (memory + storage) are kept', async () => {+ fetchSpy.mockImplementation(({ q }: { q?: string }) =>+ Promise.resolve(page([item(`${q}-hit`)], 1)),+ );++ const queries = Array.from({ length: MAX_RECENT_SEARCHES + 2 }, (_, i) => `q-${i}`);+ const params = (q: string) => ({ pageSize: DEFAULT_SEARCH_PAGE_SIZE, q });++ const hook = renderHook(+ (props: { q: string }) =>+ useResourceManagerStore((s) => s.useFetchExplorerSearch)(params(props.q)),+ { initialProps: { q: queries[0] }, wrapper },+ );++ for (const q of queries.slice(1)) {+ hook.rerender({ q });+ await waitFor(() => expect(explorerEntry(params(q))).toBeDefined());+ }++ const entries = useResourceManagerStore.getState().explorerSearchEntries;+ expect(Object.keys(entries)).toHaveLength(MAX_RECENT_SEARCHES);+ // The first keyword fell out of the bounded recent-query window.+ expect(explorerEntry(params(queries[0]))).toBeUndefined();+ expect(explorerEntry(params(queries.at(-1)!))).toBeDefined();+ });++ it('collapseHierarchySearch drops the loaded depth so no stale tail can survive', async () => {+ fetchSpy+ .mockResolvedValueOnce({+ hasMore: true,+ items: itemsOf(DEFAULT_SEARCH_PAGE_SIZE),+ total: 100,+ })+ .mockResolvedValueOnce({+ hasMore: true,+ items: itemsOf(DEFAULT_SEARCH_PAGE_SIZE, DEFAULT_SEARCH_PAGE_SIZE),+ total: 100,+ });++ const hook = renderHook(+ () => ({+ loadMore: useResourceManagerStore((s) => s.loadMoreHierarchySearch),+ sync: useResourceManagerStore((s) => s.useFetchHierarchySearch)(HIERARCHY_PARAMS),+ }),+ { wrapper },+ );++ await waitFor(() =>+ expect(hierarchyEntry(HIERARCHY_PARAMS)?.items).toHaveLength(DEFAULT_SEARCH_PAGE_SIZE),+ );+ await act(async () => {+ await hook.result.current.loadMore(hierarchyKeyOf(HIERARCHY_PARAMS));+ });+ expect(hierarchyEntry(HIERARCHY_PARAMS)?.currentPage).toBe(1);++ await act(async () => {+ await useResourceManagerStore.getState().collapseHierarchySearch();+ });++ const list = hierarchyEntry(HIERARCHY_PARAMS)!;+ expect(list.currentPage).toBe(0);+ expect(list.items).toHaveLength(DEFAULT_SEARCH_PAGE_SIZE);+ expect(list.hasMore).toBe(true);+ });++ it('stops at a full page the server called complete (hasMore false, no total)', async () => {+ fetchSpy.mockResolvedValue({ hasMore: false, items: itemsOf(DEFAULT_SEARCH_PAGE_SIZE) });++ renderHook(() => useResourceManagerStore((s) => s.useFetchHierarchySearch)(HIERARCHY_PARAMS), {+ wrapper,+ });++ await waitFor(() =>+ expect(ids(hierarchyEntry(HIERARCHY_PARAMS))).toHaveLength(DEFAULT_SEARCH_PAGE_SIZE),+ );++ // The endpoint omits `total` when the result set is an exact multiple of the+ // page size, so `hasMore: false` is the only terminator it sends; dropping it+ // would keep "load more" alive and fetch one more, empty page.+ expect(hierarchyEntry(HIERARCHY_PARAMS)?.hasMore).toBe(false);+ });++ it('bounds the window across reloads, from the searches an earlier session persisted', async () => {+ // Emulate a page that persisted MORE queries than the window before this+ // store instance existed: the rows, plus the engine's index of them. The+ // in-memory recency list alone cannot see these, so without seeding it the+ // window would start empty and persist another cap on top of them.+ const previous = Array.from({ length: MAX_RECENT_SEARCHES + 2 }, (_, i) => `old-${i}`);+ const paramsOf = (q: string) => ({ pageSize: DEFAULT_SEARCH_PAGE_SIZE, q });+ for (const q of previous) {+ await explorerSearchResource.storage!.set(+ { queryKey: explorerSearchResource.storageKey(paramsOf(q)), scope },+ {+ data: {+ currentPage: 0,+ hasMore: false,+ items: [item(`${q}-hit`)],+ pageSize: DEFAULT_SEARCH_PAGE_SIZE,+ searchParams: paramsOf(q),+ total: 1,+ },+ updatedAt: 1,+ },+ );+ }+ // The engine's index holds the storage keys it persisted (the JSON query+ // identity), not the raw keywords.+ await explorerSearchResource.storage!.set(+ { queryKey: REPLICA_INDEX_KEY, scope },+ { data: previous.map((q) => explorerSearchResource.storageKey(paramsOf(q))), updatedAt: 1 },+ );++ const remove = vi.spyOn(explorerSearchResource.storage!, 'remove');+ fetchSpy.mockImplementation(({ q }: { q?: string }) =>+ Promise.resolve(page([item(`${q}-hit`)], 1)),+ );++ renderHook(() => useResourceManagerStore((s) => s.useFetchExplorerSearch)(paramsOf('fresh')), {+ wrapper,+ });++ // Seeding put the persisted queries ahead of this session's own entry, so+ // eviction reached the oldest three of THEM β the bound now spans sessions.+ const evicted = (q: string) => explorerSearchResource.storageKey(paramsOf(q));+ await waitFor(() =>+ expect(remove.mock.calls.map(([key]) => key.queryKey)).toEqual(+ previous.slice(0, previous.length - MAX_RECENT_SEARCHES + 1).map(evicted),+ ),+ );+ expect(remove).not.toHaveBeenCalledWith(+ expect.objectContaining({ queryKey: evicted('fresh') }),+ );++ // The evicted keys must leave the persisted index too: they were never+ // written by this instance, and a leftover entry would survive every reload.+ await waitFor(async () => {+ const index = await explorerSearchResource.storage!.get({+ queryKey: REPLICA_INDEX_KEY,+ scope,+ });+ const stored = (index?.data as unknown as string[] | undefined) ?? [];+ expect(stored).toHaveLength(MAX_RECENT_SEARCHES);+ for (const q of previous.slice(0, previous.length - MAX_RECENT_SEARCHES + 1)) {+ expect(stored).not.toContain(evicted(q));+ }+ });+ });++ it('drops a sidebar search an earlier session persisted when the tree changes', async () => {+ const staleParams: HierarchySearchParams = {+ libraryId: 'kb-1',+ pageSize: DEFAULT_SEARCH_PAGE_SIZE,+ q: 'stale',+ };+ const staleKey = hierarchySearchResource.storageKey(staleParams);+ await hierarchySearchResource.storage!.set(+ { queryKey: staleKey, scope },+ {+ data: {+ currentPage: 0,+ hasMore: false,+ items: [item('stale-hit')],+ pageSize: DEFAULT_SEARCH_PAGE_SIZE,+ searchParams: staleParams,+ total: 1,+ },+ updatedAt: 1,+ },+ );+ await hierarchySearchResource.storage!.set(+ { queryKey: REPLICA_INDEX_KEY, scope },+ { data: [staleKey], updatedAt: 1 },+ );++ // Not loaded this session: memory and the SWR cache are both empty for it,+ // which is exactly the case the in-memory collapse loop cannot reach.+ expect(hierarchyEntry(staleParams)).toBeUndefined();++ await act(async () => {+ await useResourceManagerStore.getState().collapseHierarchySearch();+ });++ await waitFor(async () => {+ expect(+ await hierarchySearchResource.storage!.get({ queryKey: staleKey, scope }),+ ).toBeUndefined();+ });+ });++ it('drops a search left behind in memory, keeping only the on-screen entry collapsible', async () => {+ fetchSpy.mockImplementation(({ q }: { q?: string }) =>+ Promise.resolve(page([item(`${q}-hit`)], 1)),+ );++ const leftParams: HierarchySearchParams = {+ libraryId: 'kb-1',+ pageSize: DEFAULT_SEARCH_PAGE_SIZE,+ q: 'left',+ };+ const shownParams: HierarchySearchParams = {+ libraryId: 'kb-1',+ pageSize: DEFAULT_SEARCH_PAGE_SIZE,+ q: 'shown',+ };++ const hook = renderHook(+ (props: { q: string }) =>+ useResourceManagerStore((s) => s.useFetchHierarchySearch)({+ libraryId: 'kb-1',+ pageSize: DEFAULT_SEARCH_PAGE_SIZE,+ q: props.q,+ }),+ { initialProps: { q: 'left' }, wrapper },+ );++ await waitFor(() => expect(ids(hierarchyEntry(leftParams))).toEqual(['left-hit']));++ // Searching again leaves the first query in memory but with no mounted+ // query, so nothing would ever revalidate its head.+ hook.rerender({ q: 'shown' });+ await waitFor(() => expect(ids(hierarchyEntry(shownParams))).toEqual(['shown-hit']));+ expect(hierarchyEntry(leftParams)).toBeDefined();++ await act(async () => {+ await useResourceManagerStore.getState().collapseHierarchySearch();+ });++ expect(hierarchyEntry(leftParams)).toBeUndefined();+ expect(hierarchyEntry(shownParams)).toBeDefined();+ });++ it('leaves the new scope alone when the identity changes while the index is read', async () => {+ const staleParams: HierarchySearchParams = {+ libraryId: 'kb-1',+ pageSize: DEFAULT_SEARCH_PAGE_SIZE,+ q: 'stale',+ };+ const staleKey = hierarchySearchResource.storageKey(staleParams);+ const previousScope = scope;++ const remove = vi.spyOn(hierarchySearchResource.storage!, 'remove');+ vi.spyOn(hierarchySearchResource.storage!, 'get').mockImplementation(async (key) => {+ if (key.queryKey === REPLICA_INDEX_KEY) {+ // The user switches workspaces while the index row is in flight.+ useScope(`${previousScope}-next`);+ return { data: [staleKey], updatedAt: 1 };+ }+ return undefined;+ });++ await act(async () => {+ await useResourceManagerStore.getState().collapseHierarchySearch();+ });++ // The keys belong to the scope that was read; `remove` would resolve them+ // against the new one, so the whole cleanup must be abandoned.+ expect(remove).not.toHaveBeenCalled();+ });+});diff --git a/src/libs/replica/index.ts b/src/libs/replica/index.tsindex bd970a96ba0..bd67640fb35 100644--- a/src/libs/replica/index.ts+++ b/src/libs/replica/index.ts@@ -4,6 +4,7 @@ import {defineReplica as defineCoreReplica,type DefineReplicaOptions,isReplicaSyncKey,+ REPLICA_INDEX_KEY,type ReplicaPagedData,type ReplicaResource,type ReplicaScope,@@ -116,6 +117,30 @@ export const revalidateReplica = (isReplicaSyncKey(queryKey, resource.name, { key, scope: resource.scope.get() }),);+/**+ * The entry storage keys this resource has a persisted row for in the active+ * scope, oldest first.+ *+ * Storage has no key listing of its own; the engine keeps one index row per+ * scope (`REPLICA_INDEX_KEY`) as it persists and drops entries, and this reads+ * it. That is how code outside the owning store reaches rows an *earlier+ * session* wrote β bounding how many survive a reload, or invalidating a row+ * whose entry is not loaded in memory.+ *+ * The keys are storage keys (`key`, plus `?query` when the resource sets one),+ * so a caller only matches them against entry keys when the resource leaves+ * `query` unset.+ */+export const readReplicaStoredKeys = async (+ resource: Pick<ReplicaResource<any, any, any>, 'scope' | 'storage'>,+): Promise<string[]> => {+ const row = await resource.storage?.get({+ queryKey: REPLICA_INDEX_KEY,+ scope: resource.scope.get(),+ });+ return (row?.data as unknown as string[] | undefined) ?? [];+};+/** `createReplicaSlice` bound to the app's SWR driver. */export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(resource: ReplicaResource<TParams, TData, TFetched>,diff --git a/src/libs/swr/keys.test.ts b/src/libs/swr/keys.test.tsindex 621991a9568..c8d8d3aaf2a 100644--- a/src/libs/swr/keys.test.ts+++ b/src/libs/swr/keys.test.ts@@ -132,9 +132,6 @@ describe('resourceKeys', () => {expect(resourceKeys.recentFiles(null, undefined)).not.toEqual(resourceKeys.recentFiles('workspace-1', undefined),);- expect(resourceKeys.search({ q: 'report' }, 'workspace-1')).not.toEqual(- resourceKeys.search({ q: 'report' }, 'workspace-2'),- );});});diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 38d3680a56d..161eb285095 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -1278,11 +1278,6 @@ export const resourceKeys = {visibility ?? null,],),- search: def('resource:search', (params: unknown, workspaceId: string | null) => [- 'resource:search',- params,- workspaceId,- ]),};export const providerKeys = {clientConfig: def('provider:clientConfig', (id: string) => ['provider:clientConfig', id]),diff --git a/src/store/tree/actions.test.ts b/src/store/tree/actions.test.tsindex 226dd10ec4c..3727bd9f27d 100644--- a/src/store/tree/actions.test.ts+++ b/src/store/tree/actions.test.ts@@ -1,30 +1,44 @@import { CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { hierarchySearchResource } from '@/features/ResourceManager/store/projection';+import type * as ReplicaModule from '@/libs/replica';+import { sortTreeItems, toTreeItem, toTreeItemFromResource, TreeActionImpl } from './actions';import type { TreeState } from './types';const {mockApplyMovedResourceToCaches,+ mockCollapseHierarchySearch,mockDeleteResources,mockGetKnowledgeItems,mockRefreshFileList,mockResourceMove,+ mockRevalidateReplica,mockStoreMove,- mockSwrMutate,mockUpdateResource,} = vi.hoisted(() => ({mockApplyMovedResourceToCaches: vi.fn(),+ mockCollapseHierarchySearch: vi.fn(),mockDeleteResources: vi.fn(),mockGetKnowledgeItems: vi.fn(),mockRefreshFileList: vi.fn(),mockResourceMove: vi.fn(),+ mockRevalidateReplica: vi.fn(),mockStoreMove: vi.fn(),- mockSwrMutate: vi.fn(),mockUpdateResource: vi.fn(),}));-vi.mock('swr', () => ({ mutate: mockSwrMutate }));+vi.mock('@/libs/replica', async () => ({+ ...(await vi.importActual<typeof ReplicaModule>('@/libs/replica')),+ revalidateReplica: mockRevalidateReplica,+}));++vi.mock('@/features/ResourceManager/store', () => ({+ useResourceManagerStore: {+ getState: () => ({ collapseHierarchySearch: mockCollapseHierarchySearch }),+ },+}));vi.mock('@/services/file', () => ({fileService: {@@ -258,25 +272,25 @@ describe('TreeActionImpl folder key resolution', () => {expect(state.children['docs_unloaded']).toEqual([doc]);});- it('revalidate also refreshes the hierarchy-scoped search caches', async () => {+ it('revalidate drops the sidebar search depth and refreshes the replica', async () => {const state = createState();const actions = new TreeActionImpl(createSetter(() => state),() => state,);- mockSwrMutate.mockClear();+ mockCollapseHierarchySearch.mockClear();+ mockRevalidateReplica.mockClear();mockGetKnowledgeItems.mockResolvedValue({ items: [] });await actions.revalidate('folder-a');- expect(mockSwrMutate).toHaveBeenCalledTimes(1);- const [matcher, , options] = mockSwrMutate.mock.calls[0];- expect(options).toEqual({ revalidate: true });- // Only the sidebar search entries match β not the explorer's own search.- expect(matcher(['resource:search', { q: 'a', scope: 'hierarchy' }, 'ws-1'])).toBe(true);- expect(matcher(['resource:search', { q: 'a' }, 'ws-1'])).toBe(false);- expect(matcher(['resource:list', { q: 'a', scope: 'hierarchy' }, 'ws-1'])).toBe(false);- expect(matcher('resource:search')).toBe(false);+ // The sidebar's flat search list is a replica now; a rename/move/delete in+ // the tree must drop the loaded search depth (so a stale tail row cannot+ // survive) and revalidate it (so the head is fresh).+ await vi.waitFor(() => {+ expect(mockCollapseHierarchySearch).toHaveBeenCalled();+ expect(mockRevalidateReplica).toHaveBeenCalledWith(hierarchySearchResource);+ });});it('a revalidate requested during an in-flight root load runs once that load settles', async () => {diff --git a/src/store/tree/actions.ts b/src/store/tree/actions.tsindex 3944d813a28..8760aec1dbd 100644--- a/src/store/tree/actions.ts+++ b/src/store/tree/actions.ts@@ -1,7 +1,7 @@import { CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';-import { mutate } from 'swr';-import { resourceKeys } from '@/libs/swr/keys';+import { hierarchySearchResource } from '@/features/ResourceManager/store/projection';+import { revalidateReplica } from '@/libs/replica';import { fileService } from '@/services/file';import { resourceService } from '@/services/resource';import type { StoreSetter } from '@/store/types';@@ -13,17 +13,20 @@ import type { TreeDataState, TreeItem, TreeState, TreeStoreHandle } from './type* The library sidebar swaps the tree for a flat search list while a query is* typed; its rows reuse the tree's rename/move/delete actions. Those actions* only know the affected folder, so every tree revalidation also refreshes the- * hierarchy-scoped search caches or a renamed/deleted hit would linger there.+ * hierarchy search replica or a renamed/deleted hit would linger there.+ *+ * A revalidation only re-runs the *head* request, and the replica deliberately+ * keeps the rows the user already scrolled to. So dropping the loaded depth is+ * part of the refresh: without it a rename / move / deletion of a row past the+ * first page would leave the stale hit in the loaded tail. The same call drops+ * the searches only a previous session had persisted (never loaded here), which+ * no revalidation could otherwise reach.*/-export const revalidateHierarchySearch = () =>- mutate(- (key) =>- Array.isArray(key) &&- key[0] === resourceKeys.search.root &&- (key[1] as { scope?: string } | undefined)?.scope === 'hierarchy',- async (currentData) => currentData,- { revalidate: true },- );+export const revalidateHierarchySearch = async (): Promise<void> => {+ const { useResourceManagerStore } = await import('@/features/ResourceManager/store');+ await useResourceManagerStore.getState().collapseHierarchySearch();+ await revalidateReplica(hierarchySearchResource);+};const createdTime = (value?: Date | string): number => {if (!value) return 0;