🤯 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(file): move the file manager store onto @lobechat/replica (#20605)
Arvin Xuc15764cdfedd
diff --git a/packages/replica/src/core/engine.ts b/packages/replica/src/core/engine.tsindex f56c9e64178..030751cb804 100644--- a/packages/replica/src/core/engine.ts+++ b/packages/replica/src/core/engine.ts@@ -89,8 +89,16 @@ export interface ReplicaEngineOptions<TParams, TData, TFetched> {) => TFetched | undefined;/** Re-run the network sync of one entry (or all); wired by the fetch adapter. */revalidate?: (key?: string) => Promise<unknown>;- /** Strip transient / client-only parts before persisting; `undefined` skips. */- toPersisted?: (data: TData) => TData | undefined;+ /**+ * Strip transient / client-only parts before persisting.+ *+ * - a value → persisted+ * - `undefined` → skip this write (keep whatever is already stored)+ * - `null` → the entry is a server-confirmed absence: drop any prior+ * persisted projection, so a later hydrate cannot paint a value the server+ * no longer has (the view keeps the confirmed value).+ */+ toPersisted?: (data: TData) => TData | null | undefined;/** Paged: domain fields derived from params, written with every head page. */viewFields?: (params: TParams) => Partial<TData>;}@@ -137,7 +145,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(queryKey: replicaStorageKey(key, query),});- const toPersisted = (data: TData): TData | undefined => {+ const toPersisted = (data: TData): TData | null | undefined => {const paged = paging ? (toPersistedPage(data as any, paging, pagingCtx) as TData) : data;return options.toPersisted ? options.toPersisted(paged) : paged;};@@ -186,6 +194,13 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(}const data = toPersisted(effect.data);if (data === undefined) continue;+ if (data === null) {+ // Server-confirmed absence: remove the prior projection rather than+ // leaving it to be hydrated as if the value were still current.+ writeQueue.remove(key);+ trackStorageKey(effect.scope, key.queryKey, false);+ continue;+ }writeQueue.set(key, { data, updatedAt: Date.now() });trackStorageKey(effect.scope, key.queryKey, true);}diff --git a/packages/replica/src/zustand/createReplicaSlice.test.ts b/packages/replica/src/zustand/createReplicaSlice.test.tsindex b9ade6acc73..6cee3dabba1 100644--- a/packages/replica/src/zustand/createReplicaSlice.test.ts+++ b/packages/replica/src/zustand/createReplicaSlice.test.ts@@ -141,6 +141,72 @@ describe('createReplicaSlice', () => {expect(failing.store.getState().lists.b).toBeUndefined();});+ it('drops the prior persisted projection when `toPersisted` reports a confirmed absence', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });+ const resource = defineReplica<{ id: string }, string[]>({+ // The server confirms the id no longer exists.+ fetcher: vi.fn(async () => []),+ key: ({ id }) => id,+ name: 'absentList',+ scope,+ storage: storage.storage,+ version: 1,+ });+ const store = createStore<TestState>()(() => ({+ lists: {},+ listsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {+ driver,+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'listsReplica',+ // An empty list is a confirmed absence: drop the stored row instead of+ // leaving the stale projection to be hydrated again.+ toPersisted: (data) => (data.length ? data : null),+ view: recordLens('lists'),+ });++ renderHook(() => slice.useSync({ id: 'a' }), { wrapper });++ // The confirmed absence replaces the hydrated value in the view…+ await waitFor(() => expect(store.getState().lists.a).toEqual([]));+ // …and the stale persisted projection is gone, so a reload cannot paint it.+ await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());+ });++ it('keeps the stored row when `toPersisted` returns undefined (skip)', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });+ const resource = defineReplica<{ id: string }, string[]>({+ fetcher: vi.fn(async () => ['server']),+ key: ({ id }) => id,+ name: 'skippedList',+ scope,+ storage: storage.storage,+ version: 1,+ });+ const store = createStore<TestState>()(() => ({+ lists: {},+ listsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {+ driver,+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'listsReplica',+ // `undefined` means "skip this write", not "remove".+ toPersisted: () => undefined,+ view: recordLens('lists'),+ });++ renderHook(() => slice.useSync({ id: 'a' }), { wrapper });++ await waitFor(() => expect(store.getState().lists.a).toEqual(['server']));+ expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['cached']);+ });+it('hands its schedule (polling, focus revalidation …) to the driver', () => {const useQuery = vi.fn(() => ({ isValidating: false, mutate: vi.fn() }));const resource = defineReplica<{ id: string }, string[]>({diff --git a/src/features/ResourceManager/store/index.ts b/src/features/ResourceManager/store/index.tsindex 84fd8997267..667761684df 100644--- a/src/features/ResourceManager/store/index.ts+++ b/src/features/ResourceManager/store/index.ts@@ -1,13 +1,12 @@'use client';-import type { SWRResponse } from 'swr';import { subscribeWithSelector } from 'zustand/middleware';import { shallow } from 'zustand/shallow';import { createWithEqualityFn } from 'zustand/traditional';import { useFileStore } from '@/store/file';-import type { FolderCrumb, Store } from './action';+import type { Store } from './action';import { store } from './action';export type { State } from './initialState';@@ -19,8 +18,6 @@ export const useResourceManagerStore = createStore();export { selectors } from './selectors';-export const useResourceManagerFetchFolderBreadcrumb = (- slug?: string | null,-): SWRResponse<FolderCrumb[]> => {+export const useResourceManagerFetchFolderBreadcrumb = (slug?: string | null) => {return useFileStore((s) => s.useFetchFolderBreadcrumb)(slug);};diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 239583360d7..5c5abcd879e 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -902,7 +902,6 @@ export const agentBotKeys = {// ---- file ---------------------------------------------------------------export const fileKeys = {- knowledgeItems: def('file:knowledgeItems', (params: unknown) => ['file:knowledgeItems', params]),ttsFile: def('file:ttsFile', (messageId: string) => ['file:ttsFile', messageId]),};diff --git a/src/store/file/initialState.ts b/src/store/file/initialState.tsindex 413b58d6d46..06a8c25af29 100644--- a/src/store/file/initialState.ts+++ b/src/store/file/initialState.ts@@ -4,8 +4,11 @@ import { type FileChunkState } from './slices/chunk';import { initialFileChunkState } from './slices/chunk';import { type DocumentState } from './slices/document';import { initialDocumentState } from './slices/document';-import { type FileManagerState } from './slices/fileManager';-import { initialFileManagerState } from './slices/fileManager';+// Leaf module on purpose: the slice barrel also pulls in `action.ts`, which+// imports this store back — reaching it from here would close the cycle before+// the store is initialized.+import { type FileManagerState } from './slices/fileManager/initialState';+import { initialFileManagerState } from './slices/fileManager/initialState';import { type ResourceState } from './slices/resource/initialState';import { initialResourceState } from './slices/resource/initialState';diff --git a/src/store/file/slices/fileManager/action.test.ts b/src/store/file/slices/fileManager/action.test.tsindex 9ddde0e87f2..21ac7976b04 100644--- a/src/store/file/slices/fileManager/action.test.ts+++ b/src/store/file/slices/fileManager/action.test.ts@@ -2,6 +2,7 @@ import { act, renderHook, waitFor } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { FILE_UPLOAD_BLACKLIST, MAX_UPLOAD_FILE_COUNT } from '@/const/file';+import { createReplicaState } from '@/libs/replica';import { mutate } from '@/libs/swr';import { lambdaClient } from '@/libs/trpc/client';import { fileService } from '@/services/file';@@ -66,10 +67,15 @@ beforeEach(() => {creatingChunkingTaskIds: [],creatingEmbeddingTaskIds: [],dockUploadFileList: [],+ fileDetailMap: {},+ fileDetailReplica: createReplicaState(),fileList: [],+ fileListMeta: undefined,+ fileListReplica: createReplicaState(),+ folderBreadcrumbMap: {},+ folderBreadcrumbReplica: createReplicaState(),resourceList: [],resourceMap: new Map(),- queryListParams: undefined,},false,);@@ -936,7 +942,7 @@ describe('FileManagerActions', () => {});describe('refreshFileList', () => {- it('should refresh knowledge caches and revalidate resources by default', async () => {+ it('should revalidate the list replica and revalidate resources by default', async () => {const { result } = renderHook(() => useStore());const revalidateResourcesSpy = vi.spyOn(resourceHooks, 'revalidateResources')@@ -946,9 +952,8 @@ describe('FileManagerActions', () => {await result.current.refreshFileList();});- expect(mutate).toHaveBeenCalledWith(expect.any(Function), expect.any(Function), {- revalidate: true,- });+ // The replica's revalidate fans the list entry out through the SWR driver.+ expect(mutate).toHaveBeenCalledWith(expect.any(Function));expect(revalidateResourcesSpy).toHaveBeenCalledTimes(1);});@@ -962,9 +967,7 @@ describe('FileManagerActions', () => {await result.current.refreshFileList({ revalidateResources: false });});- expect(mutate).toHaveBeenCalledWith(expect.any(Function), expect.any(Function), {- revalidate: true,- });+ expect(mutate).toHaveBeenCalledWith(expect.any(Function));expect(revalidateResourcesSpy).not.toHaveBeenCalled();});});@@ -1129,7 +1132,22 @@ describe('FileManagerActions', () => {});});- describe('useFetchFileItem', () => {+ describe('useFetchKnowledgeItem', () => {+ const mockFile: FileListItem = {+ chunkCount: null,+ chunkingError: null,+ createdAt: new Date(),+ embeddingError: null,+ fileType: 'text/plain',+ finishEmbedding: false,+ id: 'file-1',+ name: 'test.txt',+ size: 100,+ sourceType: 'file',+ updatedAt: new Date(),+ url: 'http://example.com/test.txt',+ };+it('should not fetch when id is undefined', () => {const { result } = renderHook(() => useStore());@@ -1138,120 +1156,129 @@ describe('FileManagerActions', () => {expect(lambdaClient.file.getFileItemById.query).not.toHaveBeenCalled();});- it('should fetch file item when id is provided', async () => {+ it('reads the fetched item from the replica view when id is provided', async () => {const { result } = renderHook(() => useStore());- const mockFile: FileListItem = {- chunkCount: null,- chunkingError: null,- createdAt: new Date(),- embeddingError: null,- fileType: 'text/plain',- finishEmbedding: false,- id: 'file-1',- name: 'test.txt',- size: 100,- sourceType: 'file',- updatedAt: new Date(),- url: 'http://example.com/test.txt',- };-vi.mocked(lambdaClient.file.getFileItemById.query).mockResolvedValue(mockFile);- const { result: swrResult } = renderHook(+ const { result: itemResult } = renderHook(() => result.current.useFetchKnowledgeItem('file-1'),{ wrapper: withSWR },);await waitFor(() => {- expect(swrResult.current.data).toEqual(mockFile);+ expect(itemResult.current.data).toEqual(mockFile);});+ // The value is the replica view, not a value flowing out of the hook.+ expect(useStore.getState().fileDetailMap['file-1']?.file).toEqual(mockFile);});- });- describe('useFetchKnowledgeItems', () => {- it('should fetch file list with params', async () => {+ it('maps a server "not found" to undefined data instead of a permanent loading state', async () => {const { result } = renderHook(() => useStore());- const mockFiles: FileListItem[] = [- {- chunkCount: null,- chunkingError: null,- createdAt: new Date(),- embeddingError: null,- fileType: 'text/plain',- finishEmbedding: false,- id: 'file-1',- name: 'test1.txt',- size: 100,- sourceType: 'file',- updatedAt: new Date(),- url: 'http://example.com/test1.txt',- },- {- chunkCount: null,- chunkingError: null,- createdAt: new Date(),- embeddingError: null,- fileType: 'text/plain',- finishEmbedding: false,- id: 'file-2',- name: 'test2.txt',- size: 200,- sourceType: 'file',- updatedAt: new Date(),- url: 'http://example.com/test2.txt',- },- ];+ // `getKnowledgeItem` resolves `null` (not a throw) for a missing document id.+ vi.mocked(lambdaClient.file.getFileItemById.query).mockResolvedValue(undefined as any);- vi.mocked(lambdaClient.file.getKnowledgeItems.query).mockResolvedValue({- hasMore: false,- items: mockFiles,+ const { result: itemResult } = renderHook(+ () => result.current.useFetchKnowledgeItem('file-missing'),+ { wrapper: withSWR },+ );++ await waitFor(() => {+ expect(itemResult.current.data).toBeUndefined();+ expect(itemResult.current.isLoading).toBe(false);});+ expect(useStore.getState().fileDetailMap['file-missing']).toEqual({ file: null });+ });++ it('treats a NOT_FOUND from the file endpoint as a confirmed absence, not an error', async () => {+ const { result } = renderHook(() => useStore());++ // `getFileItemById` throws NOT_FOUND for a deleted / inaccessible `file_*`.+ vi.mocked(lambdaClient.file.getFileItemById.query).mockRejectedValue(+ Object.assign(new Error('File not found'), { data: { code: 'NOT_FOUND' } }),+ );- const params = { category: 'all' as any };- const { result: swrResult } = renderHook(- () => result.current.useFetchKnowledgeItems(params),+ const { result: itemResult } = renderHook(+ () => result.current.useFetchKnowledgeItem('file-deleted'),{ wrapper: withSWR },);await waitFor(() => {- expect(swrResult.current.data).toEqual(mockFiles);+ expect(itemResult.current.data).toBeUndefined();+ expect(itemResult.current.isLoading).toBe(false);});+ // Not an error state: the response folded a "not found" page value.+ expect(itemResult.current.error).toBeUndefined();+ expect(useStore.getState().fileDetailMap['file-deleted']).toEqual({ file: null });});+ });- it('should update store state on successful fetch', async () => {- const { result } = renderHook(() => useStore());+ describe('useFetchKnowledgeItems', () => {+ const makeFile = (id: string, size = 100): FileListItem => ({+ chunkCount: null,+ chunkingError: null,+ createdAt: new Date(),+ embeddingError: null,+ fileType: 'text/plain',+ finishEmbedding: false,+ id,+ name: `${id}.txt`,+ size,+ sourceType: 'file',+ updatedAt: new Date(),+ url: `http://example.com/${id}.txt`,+ });- const mockFiles: FileListItem[] = [- {- chunkCount: null,- chunkingError: null,- createdAt: new Date(),- embeddingError: null,- fileType: 'text/plain',- finishEmbedding: false,- id: 'file-1',- name: 'test.txt',- size: 100,- sourceType: 'file',- updatedAt: new Date(),- url: 'http://example.com/test.txt',- },- ];+ it('paints the fetched head page into the store list view', async () => {+ const { result } = renderHook(() => useStore());+ const mockFiles = [makeFile('file-1'), makeFile('file-2', 200)];vi.mocked(lambdaClient.file.getKnowledgeItems.query).mockResolvedValue({hasMore: false,items: mockFiles,});- const params = { category: 'all' as any };- renderHook(() => result.current.useFetchKnowledgeItems(params), { wrapper: withSWR });+ renderHook(() => result.current.useFetchKnowledgeItems({ category: 'all' }), {+ wrapper: withSWR,+ });- await waitFor(() => {- expect(result.current.fileList).toEqual(mockFiles);- expect(result.current.queryListParams).toEqual(params);+ await waitFor(() => expect(useStore.getState().fileList).toEqual(mockFiles));+ expect(useStore.getState().fileListMeta?.hasMore).toBe(false);+ expect(lambdaClient.file.getKnowledgeItems.query).toHaveBeenCalledWith(+ expect.objectContaining({ category: 'all', limit: 50, offset: 0 }),+ );+ });++ it('appends the next page through the replica when loadMoreKnowledgeItems runs', async () => {+ const { result } = renderHook(() => useStore());+ const firstPage = Array.from({ length: 50 }, (_, i) => makeFile(`file-${i}`));+ const secondPage = Array.from({ length: 5 }, (_, i) => makeFile(`file-${50 + i}`));++ vi.mocked(lambdaClient.file.getKnowledgeItems.query).mockImplementation(+ async (params: any) =>+ (params?.offset ?? 0) === 0+ ? { hasMore: true, items: firstPage }+ : { hasMore: false, items: secondPage },+ );++ renderHook(() => result.current.useFetchKnowledgeItems({ category: 'all', limit: 50 }), {+ wrapper: withSWR,});+ await waitFor(() => expect(useStore.getState().fileList).toHaveLength(50));+ expect(useStore.getState().fileListMeta?.hasMore).toBe(true);++ await act(async () => {+ await useStore.getState().loadMoreKnowledgeItems();+ });++ const list = useStore.getState().fileList;+ expect(list).toHaveLength(55);+ expect(list[50].id).toBe('file-50');+ expect(useStore.getState().fileListMeta?.hasMore).toBe(false);+ expect(lambdaClient.file.getKnowledgeItems.query).toHaveBeenLastCalledWith(+ expect.objectContaining({ limit: 50, offset: 50 }),+ );});});});diff --git a/src/store/file/slices/fileManager/action.ts b/src/store/file/slices/fileManager/action.tsindex 98bc8258294..4514e9df314 100644--- a/src/store/file/slices/fileManager/action.ts+++ b/src/store/file/slices/fileManager/action.ts@@ -7,12 +7,18 @@ import {import { toast, type ToastInstance } from '@lobehub/ui/base-ui';import { t } from 'i18next';import pMap from 'p-map';-import { type SWRResponse } from 'swr';import { FILE_UPLOAD_BLACKLIST, MAX_UPLOAD_FILE_COUNT } from '@/const/file';import { isChunkingSupported } from '@/libs/document-loaders/loaderType';-import { mutate, useClientDataSWR } from '@/libs/swr';-import { fileKeys } from '@/libs/swr/keys';+import {+ createReplicaSlice,+ linkReplicaEntity,+ recordLens,+ type ReplicaEntityAdapter,+ type ReplicaLens,+ type ReplicaPageResult,+ type ReplicaSyncResult,+} from '@/libs/replica';import { documentService } from '@/services/document';import { FileService, fileService } from '@/services/file';import { ragService } from '@/services/rag';@@ -21,35 +27,152 @@ import { uploadFileListReducer } from '@/store/file/reducers/uploadFileList';import { type StoreSetter } from '@/store/types';import { type FileListItem, type QueryFileListParams } from '@/types/files';import { type ResourceItem } from '@/types/resource';+import { isTrpcErrorCode } from '@/utils/trpcError';import { unzipFile } from '@/utils/unzipFile';-import { type FileStore } from '../../store';+import { type FileStore, useFileStore } from '../../store';+import {+ DEFAULT_FILE_LIST_PAGE_SIZE,+ FILE_LIST_KEY,+ fileDetailResource,+ type FileDetailValue,+ type FileListData,+ type FileListParams,+ fileListResource,+ folderBreadcrumbResource,+ type FolderCrumb,+} from './projection';import { fileManagerSelectors } from './selectors';const serverFileService = new FileService();-export interface FolderCrumb {- id: string;- name: string;- slug: string;-}-interface RefreshFileListOptions {revalidateResources?: boolean;}+/**+ * Result of {@link FileManageActionImpl.useFetchKnowledgeItem}.+ *+ * `data` is the replica view, read from the store (not from the hook's return)+ * so a reload or a return to the route paints the persisted projection first and+ * the network only confirms it: `undefined` = nothing loaded for this id yet,+ * `null` on the server is mapped to `undefined`.+ */+export interface UseFetchKnowledgeItemResult {+ data: FileListItem | undefined;+ error: unknown;+ /** SWR's `isLoading` semantics: no value yet and no error. */+ isLoading: boolean;+ isValidating: boolean;+ /** Re-run the network sync for this item. */+ mutate: () => Promise<unknown>;+}++/** Result of {@link FileManageActionImpl.useFetchFolderBreadcrumb}. */+export interface UseFetchFolderBreadcrumbResult {+ /** The ancestor chain; `[]` while nothing is loaded or the folder is at the root. */+ data: FolderCrumb[];+ error: unknown;+ isLoading: boolean;+ isValidating: boolean;+ mutate: () => Promise<unknown>;+}++const EMPTY_CRUMBS: FolderCrumb[] = [];++/**+ * The knowledge-item list lives in a flat array (`fileList`) with its paging+ * bookkeeping in a sibling field (`fileListMeta`), so every reader of the list+ * keeps the shape it already had while the replica owns hydration, paging and+ * optimistic overlays.+ */+const fileListLens: ReplicaLens<FileStore, FileListData> = {+ clear: () => ({ fileList: [], fileListMeta: undefined }),+ get: (state) => {+ if (!state.fileListMeta) return undefined;+ return { ...state.fileListMeta, items: state.fileList };+ },+ set: (_state, _key, data) => {+ if (data === undefined) return { fileList: [], fileListMeta: undefined };+ const { items, ...meta } = data;+ return { fileList: items, fileListMeta: meta };+ },+};++/**+ * How one knowledge item sits in `fileDetailMap[id]`. A "not found" answer+ * (`file: null`) is a page state, not a row: deleting the entity drops the whole+ * value, and patching it maps the row it wraps.+ */+const fileDetailEntity: ReplicaEntityAdapter<FileDetailValue, FileListItem> = {+ has: (data, id) => !!data.file && data.file.id === id,+ map: (data, _id, fn) => {+ if (!data.file) return data;+ const next = fn(data.file);+ if (next === undefined) return undefined;+ if (next === data.file) return data;+ return { ...data, file: next };+ },+};+type Setter = StoreSetter<FileStore>;export const createFileManageSlice = (set: Setter, get: () => FileStore, _api?: unknown) =>new FileManageActionImpl(set, get, _api);export class FileManageActionImpl {readonly #get: () => FileStore;+ /**+ * The knowledge-item list is a `@lobechat/replica` paged resource: the+ * persisted head page paints before the network answers and "load more"+ * appends further pages through the engine instead of a hand-rolled offset.+ */+ readonly #fileList;+ /**+ * By-id knowledge-item detail. Linked with the list below, so a rename or a+ * move updates every copy of the same file the client holds.+ */+ readonly #fileDetail;+ readonly #folderBreadcrumb;+ /** The same file lives in the list and in every loaded detail entry. */+ readonly #fileEntity;readonly #set: Setter;constructor(set: Setter, get: () => FileStore, _api?: unknown) {void _api;this.#set = set;this.#get = get;++ this.#fileList = createReplicaSlice(fileListResource, {+ actionPrefix: 'fileList',+ fetcher: (params, cursor) => this.#fetchFileListPage(params, cursor),+ get,+ set,+ stateKey: 'fileListReplica',+ view: fileListLens,+ });+ this.#fileDetail = createReplicaSlice(fileDetailResource, {+ actionPrefix: 'fileDetail',+ entity: fileDetailEntity,+ fetcher: async (id) => ({ file: await this.#fetchFileDetail(id) }),+ get,+ set,+ stateKey: 'fileDetailReplica',+ // A "not found" answer is a page state, not a row: the view keeps it so+ // consumers stop rendering, but the prior persisted projection must go.+ // `null` drops any stored row, so a reload cannot paint a file the server+ // has already confirmed missing.+ toPersisted: (data) => (data.file ? data : null),+ view: recordLens<FileStore, FileDetailValue>('fileDetailMap'),+ });+ this.#folderBreadcrumb = createReplicaSlice(folderBreadcrumbResource, {+ actionPrefix: 'folderBreadcrumb',+ fetcher: (slug) => serverFileService.getFolderBreadcrumb(slug),+ get,+ set,+ stateKey: 'folderBreadcrumbReplica',+ view: recordLens<FileStore, FolderCrumb[]>('folderBreadcrumbMap'),+ });+ this.#fileEntity = linkReplicaEntity<FileListItem>([this.#fileList, this.#fileDetail]);}#resolveChunkTargetId = async (id: string): Promise<string> => {@@ -70,6 +193,52 @@ export class FileManageActionImpl {#resolveChunkTargetIds = async (ids: string[]): Promise<string[]> =>Promise.all(ids.map((id) => this.#resolveChunkTargetId(id)));+ /**+ * One knowledge item, with the server's "not found" mapped to a confirmed+ * absence (`{ file: null }`) instead of a rejection. `getKnowledgeItem` throws+ * `NOT_FOUND` for a deleted or inaccessible `file_*` id, which would otherwise+ * leave the hydrated projection in place and surface only a revalidation+ * error — consumers ignore that error and keep rendering the stale file.+ */+ #fetchFileDetail = async (id: string): Promise<FileListItem | null> => {+ try {+ return (await serverFileService.getKnowledgeItem(id)) ?? null;+ } catch (error) {+ if (isTrpcErrorCode(error, 'NOT_FOUND')) return null;+ throw error;+ }+ };++ /**+ * One page of the knowledge-item list; `cursor` is the raw window start+ * (`undefined` = head page), which the next request continues from.+ */+ #fetchFileListPage = async (+ params: FileListParams,+ cursor?: number,+ ): Promise<ReplicaPageResult<FileListItem, number>> => {+ const { pageSize, ...filters } = params;+ const offset = cursor ?? 0;+ const response = await serverFileService.getKnowledgeItems({+ ...filters,+ includeContentPreview: filters.includeContentPreview ?? false,+ limit: pageSize,+ offset,+ });++ return {+ items: response.items,+ // The endpoint pages by row offset, reports `hasMore` rather than a total,+ // and drops rows *after* paging (Inbox folders), so `items.length` counts+ // visible rows while the next window starts at a raw offset. Carry the raw+ // offset forward — the whole server window was consumed, filtered or not —+ // and let exhaustion be exactly the server's `hasMore`. Anything derived+ // from `items.length` would both stall on a filtered page and keep+ // "load more" alive past the end of the list.+ nextCursor: response.hasMore ? offset + pageSize : null,+ };+ };+#buildOptimisticUploadResource = (file: File,result: { id: string; url: string },@@ -234,59 +403,22 @@ export class FileManageActionImpl {this.#get().toggleEmbeddingIds(chunkTargetIds, false);};+ /**+ * Append the next page of the knowledge-item list. The engine reads the loaded+ * head params and de-dupes by id, so a shifted offset never repeats a row.+ */loadMoreKnowledgeItems = async (): Promise<void> => {- const { queryListParams, fileList, fileListOffset, fileListHasMore } = this.#get();-- // Don't load if there's no more data or no params- if (!fileListHasMore || !queryListParams) return;-- try {- const response = await serverFileService.getKnowledgeItems({- ...queryListParams,- includeContentPreview: queryListParams.includeContentPreview ?? false,- limit: queryListParams.limit ?? 50,- offset: fileListOffset,- });-- // Deduplicate items by ID to prevent duplicate items at page boundaries- const existingIds = new Set(fileList.map((item) => item.id));- const newItems = response.items.filter((item) => !existingIds.has(item.id));- const updatedFileList = [...fileList, ...newItems];-- // Update Zustand store- this.#set({- fileList: updatedFileList,- fileListHasMore: response.hasMore,- fileListOffset: fileListOffset + newItems.length,- });-- // Update SWR cache so the component sees the new items- await mutate(fileKeys.knowledgeItems(queryListParams), updatedFileList, {- revalidate: false,- });- } catch (error) {- console.error('Failed to load more knowledge items:', error);- }+ await this.#fileList.loadMore(FILE_LIST_KEY);};moveFileToFolder = async (fileId: string, parentId: string | null): Promise<void> => {- // Optimistically update all file list caches- await mutate(- (key) => Array.isArray(key) && key[0] === fileKeys.knowledgeItems.root,- async (currentData: FileListItem[] | undefined) => {- if (!currentData) return currentData;- // Update the moved file's parentId in the cache- return currentData.map((item) => (item.id === fileId ? { ...item, parentId } : item));- },- {- revalidate: false, // Don't revalidate yet- },+ // Move optimistically in every loaded list / detail, then confirm from the server.+ await this.#fileEntity.optimistic(+ fileId,+ (item) => ({ ...item, parentId }),+ () => fileService.updateFile(fileId, { parentId }),);- // Perform the actual update- await fileService.updateFile(fileId, { parentId });-- // Revalidate to get fresh data from serverawait this.#get().refreshFileList();};@@ -456,22 +588,8 @@ export class FileManageActionImpl {this.#get().toggleParsingIds([chunkTargetId], false);};- #refreshKnowledgeListCaches = async (): Promise<void> => {- // Invalidate all queries under the file:knowledgeItems namespace- // This ensures all file lists (explorer, tree, etc.) are refreshed- // Note: We don't pass data as undefined to avoid clearing the cache,- // which would cause isLoading to become true and show skeleton screen- await mutate(- (key) => Array.isArray(key) && key[0] === fileKeys.knowledgeItems.root,- async (currentData) => currentData,- {- revalidate: true,- },- );- };-refreshFileList = async (options?: RefreshFileListOptions): Promise<void> => {- await this.#refreshKnowledgeListCaches();+ await this.#fileList.revalidate();if (options?.revalidateResources === false) return;@@ -481,44 +599,49 @@ export class FileManageActionImpl {publishFileToWorkspace = async (id: string): Promise<void> => {await fileService.publishFileToWorkspace(id);+ this.#fileEntity.update(id, (item) => ({ ...item, visibility: 'public' }));await this.#get().refreshFileList();};setFileVisibility = async (id: string, visibility: 'private' | 'public'): Promise<void> => {await fileService.setFileVisibility(id, visibility);+ this.#fileEntity.update(id, (item) => ({ ...item, visibility }));await this.#get().refreshFileList();};removeFileItem = async (id: string): Promise<void> => {await fileService.removeFile(id);+ // Drop it from every loaded list / detail at once, then confirm from the server.+ this.#fileEntity.remove(id);await this.#get().refreshFileList();};removeFiles = async (ids: string[]): Promise<void> => {await fileService.removeFiles(ids);+ for (const id of ids) this.#fileEntity.remove(id);await this.#get().refreshFileList();};+ /**+ * Drop cached knowledge items without calling the server, for a deletion that+ * was already confirmed elsewhere (the resource explorer has its own delete+ * paths). Both of this slice's replicas persist by id, so leaving a deleted+ * row behind lets a later direct visit repaint it until a NOT_FOUND answer+ * arrives — and offline that answer never comes. Evicts the list row and every+ * loaded detail together, exactly like a local delete.+ */+ forgetKnowledgeItems = (ids: string[]): void => {+ for (const id of ids) this.#fileEntity.remove(id);+ };+renameFolder = async (folderId: string, newName: string): Promise<void> => {- // Optimistically update all file list caches- await mutate(- (key) => Array.isArray(key) && key[0] === fileKeys.knowledgeItems.root,- async (currentData: FileListItem[] | undefined) => {- if (!currentData) return currentData;- // Update the folder's name in the cache- return currentData.map((item) =>- item.id === folderId ? { ...item, name: newName } : item,- );- },- {- revalidate: false, // Don't revalidate yet- },+ // Rename optimistically in every loaded list / detail, then confirm from the server.+ await this.#fileEntity.optimistic(+ folderId,+ (item) => ({ ...item, name: newName }),+ () => documentService.updateDocument({ id: folderId, title: newName }),);- // Perform the actual update- await documentService.updateDocument({ id: folderId, title: newName });-- // Revalidate to get fresh data from serverawait this.#get().refreshFileList();};@@ -752,45 +875,57 @@ export class FileManageActionImpl {}};- useFetchFolderBreadcrumb = (slug?: string | null): SWRResponse<FolderCrumb[]> => {- return useClientDataSWR<FolderCrumb[]>(- !slug ? null : ['useFetchFolderBreadcrumb', slug],- async () => {- const response = await serverFileService.getFolderBreadcrumb(slug!);- return response;- },- );- };+ /**+ * Fetch orchestration for a folder's ancestor chain. Hydrates the persisted+ * projection, then revalidates; the chain lands in `folderBreadcrumbMap` and+ * this hook returns it for the breadcrumb surfaces.+ */+ useFetchFolderBreadcrumb = (slug?: string | null): UseFetchFolderBreadcrumbResult => {+ const entry = useFileStore((s) => (slug ? s.folderBreadcrumbMap[slug] : undefined));+ const sync = this.#folderBreadcrumb.useSync(slug ?? null);- useFetchKnowledgeItem = (id?: string): SWRResponse<FileListItem | undefined> => {- return useClientDataSWR<FileListItem | undefined>(- !id ? null : ['useFetchKnowledgeItem', id],- async () => {- const response = await serverFileService.getKnowledgeItem(id!);- return response ?? undefined;- },- );+ return {+ data: entry ?? EMPTY_CRUMBS,+ error: sync.error,+ isLoading: Boolean(slug) && entry === undefined && sync.error == null,+ isValidating: sync.isValidating,+ mutate: sync.revalidate,+ };};- useFetchKnowledgeItems = (params: QueryFileListParams): SWRResponse<FileListItem[]> => {- return useClientDataSWR<FileListItem[]>(fileKeys.knowledgeItems(params), async () => {- const response = await serverFileService.getKnowledgeItems({- ...params,- includeContentPreview: params.includeContentPreview ?? false,- limit: params.limit ?? 50,- offset: 0,- });+ /**+ * Sync one knowledge item through its replica. The view is the source of+ * truth, so a reload or a return to the route paints from the persisted+ * projection on the first frame and the network only confirms it.+ *+ * Keeps SWR's `{ data, error, isLoading, mutate }` shape for its callers while+ * reading `data` from the store view — a "not found" answer reads as `undefined`.+ */+ useFetchKnowledgeItem = (id?: string): UseFetchKnowledgeItemResult => {+ const entry = useFileStore((s) => (id ? s.fileDetailMap[id] : undefined));+ const sync = this.#fileDetail.useSync(id ?? null);- // Update store immediately with response data (no duplicate fetch!)- this.#set({- fileList: response.items,- fileListHasMore: response.hasMore,- fileListOffset: response.items.length,- queryListParams: params,- });+ return {+ data: entry?.file ?? undefined,+ error: sync.error,+ isLoading: Boolean(id) && entry === undefined && sync.error == null,+ isValidating: sync.isValidating,+ mutate: sync.revalidate,+ };+ };- return response.items;- });+ /**+ * Fetch orchestration for the knowledge-item list. Hydrates the persisted head+ * page, then revalidates; the rows land in `fileList` — read them from the+ * store, never from this hook.+ */+ useFetchKnowledgeItems = (params: QueryFileListParams): ReplicaSyncResult => {+ const { limit, offset, ...filters } = params;+ void offset;+ return this.#fileList.useSync({+ ...filters,+ pageSize: limit ?? DEFAULT_FILE_LIST_PAGE_SIZE,+ } satisfies FileListParams);};}diff --git a/src/store/file/slices/fileManager/index.ts b/src/store/file/slices/fileManager/index.tsindex 6bdd1f4b2ef..2f9449bdb81 100644--- a/src/store/file/slices/fileManager/index.ts+++ b/src/store/file/slices/fileManager/index.ts@@ -1,3 +1,4 @@export * from './action';export * from './initialState';+export * from './projection';export * from './selectors';diff --git a/src/store/file/slices/fileManager/initialState.ts b/src/store/file/slices/fileManager/initialState.tsindex eff994bdeec..00e85a430bc 100644--- a/src/store/file/slices/fileManager/initialState.ts+++ b/src/store/file/slices/fileManager/initialState.ts@@ -1,17 +1,41 @@-import { type FileListItem, type QueryFileListParams } from '@/types/files';+import { createReplicaState, type ReplicaState } from '@/libs/replica';+import { type FileListItem } from '@/types/files';import { type UploadFileItem } from '@/types/files/upload';+import {+ type FileDetailValue,+ type FileListData,+ type FileListMeta,+ type FolderCrumb,+} from './projection';+export interface FileManagerState {creatingChunkingTaskIds: string[];creatingEmbeddingTaskIds: string[];currentFolderId?: string | null;dockUploadFileList: UploadFileItem[];- fileDetail?: FileListItem;+ /**+ * One knowledge item per id — the replica view of `fileDetail`. Selectors read+ * this location; the replica slice is its only writer. `file: null` means the+ * server answered "not found".+ */+ fileDetailMap: Record<string, FileDetailValue>;+ /** Replica bookkeeping of `fileDetailMap`. */+ fileDetailReplica: ReplicaState<FileDetailValue>;+ /**+ * Rows of the knowledge-item list — the replica view of `fileList`, kept as a+ * flat array where every existing reader expects it.+ */fileList: FileListItem[];- fileListHasMore: boolean;- fileListOffset: number;+ /** Paging bookkeeping of `fileList` (part of the replica view). */+ fileListMeta?: FileListMeta;+ /** Replica bookkeeping of `fileList`. */+ fileListReplica: ReplicaState<FileListData>;+ /** A folder's ancestor chain per slug — the replica view of `folderBreadcrumb`. */+ folderBreadcrumbMap: Record<string, FolderCrumb[]>;+ /** Replica bookkeeping of `folderBreadcrumbMap`. */+ folderBreadcrumbReplica: ReplicaState<FolderCrumb[]>;pendingRenameItemId: string | null;- queryListParams?: QueryFileListParams;}export const initialFileManagerState: FileManagerState = {@@ -19,8 +43,12 @@ export const initialFileManagerState: FileManagerState = {creatingEmbeddingTaskIds: [],currentFolderId: undefined,dockUploadFileList: [],+ fileDetailMap: {},+ fileDetailReplica: createReplicaState(),fileList: [],- fileListHasMore: false,- fileListOffset: 0,+ fileListMeta: undefined,+ fileListReplica: createReplicaState(),+ folderBreadcrumbMap: {},+ folderBreadcrumbReplica: createReplicaState(),pendingRenameItemId: null,};diff --git a/src/store/file/slices/fileManager/projection.ts b/src/store/file/slices/fileManager/projection.tsnew file mode 100644index 00000000000..1fec6e19fd7--- /dev/null+++ b/src/store/file/slices/fileManager/projection.ts@@ -0,0 +1,100 @@+import { definePagedReplica, defineReplica, type ReplicaPagedData } from '@/libs/replica';+import { type FileListItem, type QueryFileListParams } from '@/types/files';++/** One crumb of a folder's ancestor chain. */+export interface FolderCrumb {+ id: string;+ name: string;+ slug: string;+}++/** The knowledge-item list is not partitioned: one entry per scope. */+export const FILE_LIST_KEY = 'all';++/** Page size when the caller does not name one. */+export const DEFAULT_FILE_LIST_PAGE_SIZE = 50;++/**+ * Params of one knowledge-item list page: the server-side filters plus the page+ * size. The window start (`offset`) is NOT here — it is the replica's paging+ * cursor, which the fetcher reads off this resource.+ */+export interface FileListParams extends Omit<QueryFileListParams, 'limit' | 'offset'> {+ pageSize: number;+}++/**+ * The knowledge-item list view: the generic local-first paged data. The list+ * lives in `FilesStoreState.fileList` (a flat array, where every existing+ * reader expects it) with the paging bookkeeping in `fileListMeta`.+ */+export interface FileListData extends ReplicaPagedData<FileListItem, number> {}+export type FileListMeta = Omit<FileListData, 'items'>;++/**+ * The explorer / picker's knowledge-item list (`fileService.getKnowledgeItems`):+ * a local-first paged replica, so a reload or a return to the route paints the+ * persisted head page on the first frame, the network confirms it, and "load+ * more" appends further pages through the engine.+ *+ * Filters are the query identity: a projection taken under other filters never+ * paints, and an un-loaded list never reads as an empty one.+ *+ * Cursor mode, with the raw window start as the cursor: the endpoint pages by+ * row offset, reports `hasMore` instead of a total, and filters rows out *after*+ * paging (folders in the Inbox) — so a page can be short and its visible count+ * is not a position. Carrying the offset keeps "is there more" exactly the+ * server's answer, instead of a count derived from mixed units.+ */+export const fileListResource = definePagedReplica<+ FileListParams,+ FileListItem,+ number,+ FileListData+>({+ key: () => FILE_LIST_KEY,+ name: 'fileList',+ paging: {+ direction: 'forward',+ getId: (item) => item.id,+ mode: 'cursor',+ // A reload repaints what the first network page would show, never a stale tail.+ persist: { pages: 1 },+ },+ query: (params) => params,+ storage: 'indexedDB',+ version: 1,+});++/**+ * One knowledge item by id (`fileDetailMap[id]`).+ *+ * Wrapped in an object on purpose: a replica value can never be `null` (the+ * engine reads `null` as "keep the current value"), but a page must tell "the+ * server answered not found" (`file: null`) apart from "nothing loaded yet"+ * (no entry at all).+ */+export interface FileDetailValue {+ /** The row, or `null` when the server has no such item. */+ file: FileListItem | null;+}++/** By-id knowledge-item detail, for items outside the loaded list page. */+export const fileDetailResource = defineReplica<string, FileDetailValue>({+ key: (id) => id,+ name: 'fileDetail',+ storage: 'indexedDB',+ version: 1,+});++/**+ * A folder's ancestor chain, keyed by the folder slug (`folderBreadcrumbMap[slug]`).+ * Read-only and immutable per slug, so naming a folder repaints from its own+ * head — a stale chain can never be patched in place.+ */+export const folderBreadcrumbResource = defineReplica<string, FolderCrumb[]>({+ key: (slug) => slug,+ name: 'folderBreadcrumb',+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/file/slices/fileManager/replica.test.ts b/src/store/file/slices/fileManager/replica.test.tsnew file mode 100644index 00000000000..75c3f822294--- /dev/null+++ b/src/store/file/slices/fileManager/replica.test.ts@@ -0,0 +1,454 @@+/**+ * @vitest-environment happy-dom+ *+ * The file manager's knowledge-item list and by-id detail are+ * `@lobechat/replica` resources: the persisted head page / detail paints before+ * the network answers, the response confirms and persists it, "load more"+ * appends through the engine, and — because the two resources are linked — a+ * rename or delete reaches the list row and every loaded detail entry at once.+ */+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 } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { lambdaClient } from '@/libs/trpc/client';+import { type FileListItem } from '@/types/files';++import { useFileStore } from '../../store';+import {+ fileDetailResource,+ type FileListData,+ type FileListParams,+ fileListResource,+} from './projection';++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ document: { updateDocument: { mutate: vi.fn() } },+ file: {+ getFileItemById: { query: vi.fn() },+ getKnowledgeItems: { query: vi.fn() },+ publishFileToWorkspace: { mutate: vi.fn() },+ removeFile: { mutate: vi.fn() },+ removeFiles: { mutate: vi.fn() },+ setFileVisibility: { mutate: vi.fn() },+ updateFile: { mutate: vi.fn() },+ },+ },+}));++const BASE_PARAMS: FileListParams = { category: 'all', pageSize: 50 };+const BASE_KEY = fileListResource.storageKey(BASE_PARAMS);++const file = (id: string, name = id): FileListItem =>+ ({+ chunkCount: null,+ chunkingError: null,+ createdAt: new Date(0),+ embeddingError: null,+ fileType: 'text/plain',+ finishEmbedding: false,+ id,+ name,+ size: 1,+ sourceType: 'file',+ updatedAt: new Date(0),+ url: `https://example.com/${id}`,+ }) as FileListItem;++const listData = (items: FileListItem[], total?: number): FileListData => ({+ currentPage: 0,+ hasMore: total === undefined ? false : total > items.length,+ items,+ pageSize: BASE_PARAMS.pageSize,+ total,+});++/** 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('fileManager 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);+ };++ beforeEach(() => {+ useScope(`file-user-${randomUUID()}:personal`);+ act(() =>+ useFileStore.setState({+ dockUploadFileList: [],+ fileDetailMap: {},+ fileList: [],+ fileListMeta: undefined,+ }),+ );+ });++ afterEach(async () => {+ cleanup();+ await Promise.all(+ [...scopes].flatMap((value) => [+ fileListResource.storage!.remove({ queryKey: BASE_KEY, scope: value }),+ fileDetailResource.storage!.remove({ queryKey: 'file-1', scope: value }),+ ]),+ );+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ it('paints the persisted head page before the network answers', async () => {+ await fileListResource.storage!.set(+ { queryKey: BASE_KEY, scope },+ { data: listData([file('cached-1')], 40), updatedAt: 1 },+ );+ vi.mocked(lambdaClient.file.getKnowledgeItems.query).mockImplementation(pending);++ const sync = renderHook(+ () => useFileStore((s) => s.useFetchKnowledgeItems)({ category: 'all', limit: 50 }),+ { wrapper },+ );++ await waitFor(() =>+ expect(useFileStore.getState().fileList.map((f) => f.id)).toEqual(['cached-1']),+ );+ expect(sync.result.current.isHydrated).toBe(true);+ expect(sync.result.current.isValidating).toBe(true);+ });++ it('replaces the head page with the server response and persists it', async () => {+ vi.mocked(lambdaClient.file.getKnowledgeItems.query).mockResolvedValue({+ hasMore: true,+ items: [file('a'), file('b')],+ } as any);++ renderHook(+ () => useFileStore((s) => s.useFetchKnowledgeItems)({ category: 'all', limit: 50 }),+ { wrapper },+ );++ await waitFor(() =>+ expect(useFileStore.getState().fileList.map((f) => f.id)).toEqual(['a', 'b']),+ );+ expect(useFileStore.getState().fileListMeta?.hasMore).toBe(true);+ // A non-final page leaves the total unknown; the response still persists.+ await waitFor(async () => {+ const row = await fileListResource.storage!.get({ queryKey: BASE_KEY, scope });+ expect((row?.data as FileListData).items.map((f) => f.id)).toEqual(['a', 'b']);+ });+ });++ it('appends the next page with the loaded query params', async () => {+ const firstPage = Array.from({ length: 50 }, (_, i) => file(`file-${i}`));+ const secondPage = Array.from({ length: 5 }, (_, i) => file(`file-${50 + i}`));+ vi.mocked(lambdaClient.file.getKnowledgeItems.query).mockImplementation(+ async (params: any) =>+ ((params?.offset ?? 0) === 0+ ? { hasMore: true, items: firstPage }+ : { hasMore: false, items: secondPage }) as any,+ );++ renderHook(+ () => useFileStore((s) => s.useFetchKnowledgeItems)({ category: 'all', limit: 50 }),+ { wrapper },+ );+ await waitFor(() => expect(useFileStore.getState().fileList).toHaveLength(50));++ await act(async () => {+ await useFileStore.getState().loadMoreKnowledgeItems();+ });++ const list = useFileStore.getState().fileList;+ expect(list).toHaveLength(55);+ expect(list[50].id).toBe('file-50');+ expect(lambdaClient.file.getKnowledgeItems.query).toHaveBeenLastCalledWith(+ expect.objectContaining({ limit: 50, offset: 50 }),+ );+ });++ it('keeps the loaded tail when the head revalidates', async () => {+ // 55 rows on the server: a full head page (`hasMore`) plus a 5-row terminal page.+ const head = Array.from({ length: 50 }, (_, i) => file(`file-${i}`));+ const tail = Array.from({ length: 5 }, (_, i) => file(`file-${50 + i}`));+ vi.mocked(lambdaClient.file.getKnowledgeItems.query).mockImplementation(+ async (params: any) =>+ ((params?.offset ?? 0) === 0+ ? { hasMore: true, items: head }+ : { hasMore: false, items: tail }) as any,+ );++ renderHook(+ () => useFileStore((s) => s.useFetchKnowledgeItems)({ category: 'all', limit: 50 }),+ { wrapper },+ );+ await waitFor(() => expect(useFileStore.getState().fileList).toHaveLength(50));+ await act(async () => {+ await useFileStore.getState().loadMoreKnowledgeItems();+ });+ expect(useFileStore.getState().fileList).toHaveLength(55);+ expect(useFileStore.getState().fileListMeta?.hasMore).toBe(false);++ // A refresh re-fetches only the head page, which reports `hasMore` and no+ // total. The rows the user already loaded must survive it.+ await act(async () => {+ await useFileStore.getState().refreshFileList({ revalidateResources: false });+ });++ expect(useFileStore.getState().fileList.map((f) => f.id)).toEqual(+ [...head, ...tail].map((f) => f.id),+ );+ expect(useFileStore.getState().fileListMeta?.hasMore).toBe(false);+ });++ it('keeps paging open when a revalidated head still has rows beyond the loaded depth', async () => {+ // 150 rows on the server: two full pages (`hasMore`) plus a terminal page.+ const page = (start: number) => Array.from({ length: 50 }, (_, i) => file(`a-${start + i}`));+ vi.mocked(lambdaClient.file.getKnowledgeItems.query).mockImplementation(async (params: any) => {+ const offset = params?.offset ?? 0;+ if (offset === 0) return { hasMore: true, items: page(0) } as any;+ if (offset === 50) return { hasMore: true, items: page(50) } as any;+ return { hasMore: false, items: page(100) } as any;+ });++ renderHook(+ () => useFileStore((s) => s.useFetchKnowledgeItems)({ category: 'all', limit: 50 }),+ { wrapper },+ );+ await waitFor(() => expect(useFileStore.getState().fileList).toHaveLength(50));+ await act(async () => {+ await useFileStore.getState().loadMoreKnowledgeItems();+ });+ expect(useFileStore.getState().fileList).toHaveLength(100);+ expect(useFileStore.getState().fileListMeta?.hasMore).toBe(true);++ // The head page says nothing about rows 101+, so the refresh must neither+ // drop the loaded depth nor close paging.+ await act(async () => {+ await useFileStore.getState().refreshFileList({ revalidateResources: false });+ });+ expect(useFileStore.getState().fileList).toHaveLength(100);+ expect(useFileStore.getState().fileListMeta?.hasMore).toBe(true);++ await act(async () => {+ await useFileStore.getState().loadMoreKnowledgeItems();+ });+ expect(useFileStore.getState().fileList).toHaveLength(150);+ expect(useFileStore.getState().fileList[149].id).toBe('a-149');+ expect(useFileStore.getState().fileListMeta?.hasMore).toBe(false);+ });++ it('reaches exhaustion when a filtered page is shorter than the window', async () => {+ // The endpoint pages raw rows and drops Inbox folders afterwards, so a page+ // can be shorter than `pageSize` while raw rows remain — and the last page+ // can be shorter still. Both pages here carry fewer rows than the window.+ const visible = (start: number, count: number) =>+ Array.from({ length: count }, (_, i) => file(`v-${start + i}`));+ vi.mocked(lambdaClient.file.getKnowledgeItems.query).mockImplementation(+ async (params: any) =>+ ((params?.offset ?? 0) === 0+ ? { hasMore: true, items: visible(0, 40) }+ : { hasMore: false, items: visible(40, 5) }) as any,+ );++ renderHook(+ () => useFileStore((s) => s.useFetchKnowledgeItems)({ category: 'all', limit: 50 }),+ { wrapper },+ );+ await waitFor(() => expect(useFileStore.getState().fileList).toHaveLength(40));+ expect(useFileStore.getState().fileListMeta?.hasMore).toBe(true);++ await act(async () => {+ await useFileStore.getState().loadMoreKnowledgeItems();+ });+ expect(useFileStore.getState().fileList).toHaveLength(45);+ expect(useFileStore.getState().fileListMeta?.hasMore).toBe(false);++ // The server ended the list, so another attempt must not issue a request.+ const calls = vi.mocked(lambdaClient.file.getKnowledgeItems.query).mock.calls.length;+ await act(async () => {+ await useFileStore.getState().loadMoreKnowledgeItems();+ });+ expect(vi.mocked(lambdaClient.file.getKnowledgeItems.query).mock.calls.length).toBe(calls);+ });++ // The explorer deletes through the resource slice, not through this one. Both+ // of this slice's replicas persist by id, so a confirmed deletion must evict+ // them too — otherwise a later direct visit repaints the deleted item until a+ // NOT_FOUND answer arrives, and offline that answer never comes.+ describe('resource deletion eviction', () => {+ it('drops the list row and the persisted detail when the explorer deletes a resource', async () => {+ vi.mocked(lambdaClient.file.getKnowledgeItems.query).mockResolvedValue({+ hasMore: false,+ items: [file('file-1', 'Original'), file('file-2')],+ } as any);+ vi.mocked(lambdaClient.file.getFileItemById.query).mockResolvedValue(+ file('file-1', 'Original'),+ );+ vi.mocked(lambdaClient.file.removeFile.mutate).mockResolvedValue(undefined);++ renderHook(+ () => {+ useFileStore((s) => s.useFetchKnowledgeItems)({ category: 'all', limit: 50 });+ useFileStore((s) => s.useFetchKnowledgeItem)('file-1');+ },+ { wrapper },+ );+ await waitFor(() => {+ expect(useFileStore.getState().fileDetailMap['file-1']?.file?.name).toBe('Original');+ });++ await act(async () => {+ await useFileStore.getState().deleteResource('file-1');+ });++ expect(useFileStore.getState().fileList.map((f) => f.id)).toEqual(['file-2']);+ expect(useFileStore.getState().fileDetailMap['file-1']).toBeUndefined();+ // The persisted row is gone, so a reload cannot repaint the deleted item.+ await expect(+ fileDetailResource.storage!.get({ queryKey: 'file-1', scope }),+ ).resolves.toBeFalsy();+ });+ });++ describe('confirmed missing detail', () => {+ it('drops the persisted projection on NOT_FOUND so a reload cannot paint the stale file', async () => {+ // A previous visit persisted this file's detail.+ await fileDetailResource.storage!.set(+ { queryKey: 'file-1', scope },+ { data: { file: file('file-1', 'Stale') }, updatedAt: 1 },+ );+ // The server now answers NOT_FOUND (deleted or inaccessible).+ vi.mocked(lambdaClient.file.getFileItemById.query).mockRejectedValue(+ Object.assign(new Error('File not found'), { data: { code: 'NOT_FOUND' } }),+ );++ const { result } = renderHook(() => useFileStore((s) => s.useFetchKnowledgeItem)('file-1'), {+ wrapper,+ });++ await waitFor(() => {+ expect(result.current.data).toBeUndefined();+ expect(result.current.isLoading).toBe(false);+ });+ // The view carries the confirmed absence…+ expect(useFileStore.getState().fileDetailMap['file-1']).toEqual({ file: null });+ // …and the stale persisted projection is gone: a reload hydrates nothing.+ await waitFor(async () => {+ expect(+ await fileDetailResource.storage!.get({ queryKey: 'file-1', scope }),+ ).toBeUndefined();+ });+ });+ });++ describe('linked entity mutations', () => {+ const seed = async () => {+ vi.mocked(lambdaClient.file.getKnowledgeItems.query).mockResolvedValue({+ hasMore: false,+ items: [file('file-1', 'Original'), file('file-2')],+ } as any);+ vi.mocked(lambdaClient.file.getFileItemById.query).mockResolvedValue(+ file('file-1', 'Original'),+ );++ renderHook(+ () => {+ useFileStore((s) => s.useFetchKnowledgeItems)({ category: 'all', limit: 50 });+ useFileStore((s) => s.useFetchKnowledgeItem)('file-1');+ },+ { wrapper },+ );++ await waitFor(() => {+ expect(useFileStore.getState().fileList).toHaveLength(2);+ expect(useFileStore.getState().fileDetailMap['file-1']?.file?.name).toBe('Original');+ });+ };++ const listName = () => useFileStore.getState().fileList.find((f) => f.id === 'file-1')?.name;+ const detailName = () => useFileStore.getState().fileDetailMap['file-1']?.file?.name;++ it('renames the list row and the loaded detail optimistically', async () => {+ await seed();+ let resolveUpdate!: (value: unknown) => void;+ vi.mocked(lambdaClient.document.updateDocument.mutate).mockImplementation(+ () => new Promise((resolve) => (resolveUpdate = resolve)) as any,+ );++ let operation!: Promise<unknown>;+ act(() => {+ operation = useFileStore.getState().renameFolder('file-1', 'Renamed');+ });++ expect(listName()).toBe('Renamed');+ expect(detailName()).toBe('Renamed');++ vi.mocked(lambdaClient.file.getKnowledgeItems.query).mockResolvedValue({+ hasMore: false,+ items: [file('file-1', 'Renamed'), file('file-2')],+ } as any);+ await act(async () => {+ resolveUpdate({});+ await operation;+ });++ expect(listName()).toBe('Renamed');+ });++ it('rolls both copies back when the rename fails', async () => {+ await seed();+ vi.mocked(lambdaClient.document.updateDocument.mutate).mockRejectedValue(new Error('boom'));++ const operation = useFileStore.getState().renameFolder('file-1', 'Renamed');+ await act(async () => {+ await expect(operation).rejects.toThrow('boom');+ });++ expect(listName()).toBe('Original');+ expect(detailName()).toBe('Original');+ });++ it('drops a removed file from the list and its detail', async () => {+ await seed();+ vi.mocked(lambdaClient.file.removeFile.mutate).mockResolvedValue(undefined);+ vi.mocked(lambdaClient.file.getKnowledgeItems.query).mockResolvedValue({+ hasMore: false,+ items: [file('file-2')],+ } as any);++ await act(async () => {+ await useFileStore.getState().removeFileItem('file-1');+ });++ expect(useFileStore.getState().fileList.map((f) => f.id)).toEqual(['file-2']);+ expect(useFileStore.getState().fileDetailMap['file-1']).toBeUndefined();+ });+ });+});diff --git a/src/store/file/slices/fileManager/selectors.ts b/src/store/file/slices/fileManager/selectors.tsindex 9a9f68ba68c..308f1d4604f 100644--- a/src/store/file/slices/fileManager/selectors.ts+++ b/src/store/file/slices/fileManager/selectors.ts@@ -70,7 +70,7 @@ const isCreatingFileParseTask = (id: string) => (s: FilesStoreState) =>const isCreatingChunkEmbeddingTask = (id: string) => (s: FilesStoreState) =>s.creatingEmbeddingTaskIds.includes(id);-const fileListHasMore = (s: FilesStoreState) => s.fileListHasMore;+const fileListHasMore = (s: FilesStoreState) => s.fileListMeta?.hasMore ?? false;export const fileManagerSelectors = {dockFileList,diff --git a/src/store/file/slices/resource/action.ts b/src/store/file/slices/resource/action.tsindex 4dc47ad5729..2063b01effb 100644--- a/src/store/file/slices/resource/action.ts+++ b/src/store/file/slices/resource/action.ts@@ -484,6 +484,11 @@ export class ResourceActionImpl {tx.mutation = () => resourceService.deleteResource(id);await tx.commit<void>();++ // The file manager's by-id detail replica persists, so a confirmed deletion+ // has to evict it as well: otherwise a direct visit to the deleted id+ // repaints it until a NOT_FOUND answer arrives, and offline it never does.+ this.#get().forgetKnowledgeItems([id]);};deleteResources = async (ids: string[]) => {@@ -502,6 +507,10 @@ export class ResourceActionImpl {tx.mutation = () => resourceService.deleteResources(ids);await tx.commit<void>();++ // See `deleteResource`: the detail replica persists by id, so it must be+ // evicted here too.+ this.#get().forgetKnowledgeItems(ids);};flushSync = async (): Promise<void> => {