🤯 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
refac: Improve resource manager (#11351)
René Wangb56d159c8448
diff --git a/locales/en-US/file.json b/locales/en-US/file.jsonindex 9a81632fbda..6827619cde1 100644--- a/locales/en-US/file.json+++ b/locales/en-US/file.json@@ -18,6 +18,8 @@"empty": "No files or folders have been uploaded yet.","header.actions.builtInBlockList.filtered": "{{ignored}} files filtered (out of {{total}} total)","header.actions.connect": "Connect...",+ "header.actions.createFolderError": "Failed to create folder",+ "header.actions.creatingFolder": "Creating folder...","header.actions.gitignore.apply": "Apply Rules","header.actions.gitignore.cancel": "Ignore Rules","header.actions.gitignore.content": ".gitignore file detected ({{count}} files in total). Would you like to apply the ignore rules?",diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.jsonindex b3beb148706..283fb54d897 100644--- a/locales/zh-CN/file.json+++ b/locales/zh-CN/file.json@@ -18,6 +18,8 @@"empty": "这里还没有文件或文件夹。先上传一个文件,或创建文稿开始整理","header.actions.builtInBlockList.filtered": "已过滤 {{ignored}} 个文件(共 {{total}} 个文件)","header.actions.connect": "连接…",+ "header.actions.createFolderError": "创建文件夹失败",+ "header.actions.creatingFolder": "正在创建文件夹...","header.actions.gitignore.apply": "应用规则","header.actions.gitignore.cancel": "忽略规则","header.actions.gitignore.content": "检测到 .gitignore 文件(共 {{count}} 个文件),是否应用忽略规则?",diff --git a/src/app/[variants]/(main)/home/_layout/Body/Project/List/Editing.tsx b/src/app/[variants]/(main)/home/_layout/Body/Project/List/Editing.tsxindex b7dfbc599aa..46b12afe32b 100644--- a/src/app/[variants]/(main)/home/_layout/Body/Project/List/Editing.tsx+++ b/src/app/[variants]/(main)/home/_layout/Body/Project/List/Editing.tsx@@ -1,7 +1,7 @@import { Input, Popover } from '@lobehub/ui';import { memo, useCallback, useState } from 'react';-import { useKnowledgeBaseStore } from '@/store/knowledgeBase';+import { useKnowledgeBaseStore } from '@/store/library';interface EditingProps {id: string;diff --git a/src/app/[variants]/(main)/home/_layout/Body/Project/List/Item.tsx b/src/app/[variants]/(main)/home/_layout/Body/Project/List/Item.tsxindex 0c8b350dfa9..8599fbdfca0 100644--- a/src/app/[variants]/(main)/home/_layout/Body/Project/List/Item.tsx+++ b/src/app/[variants]/(main)/home/_layout/Body/Project/List/Item.tsx@@ -1,7 +1,7 @@import { BoxIcon } from 'lucide-react';import { memo, useCallback } from 'react';-import { useKnowledgeBaseStore } from '@/store/knowledgeBase';+import { useKnowledgeBaseStore } from '@/store/library';import NavItem from '../../../../../../../../features/NavPanel/components/NavItem';import Actions from './Actions';diff --git a/src/app/[variants]/(main)/home/_layout/Body/Project/List/index.tsx b/src/app/[variants]/(main)/home/_layout/Body/Project/List/index.tsxindex 7d4f79fe40b..f38daa51fde 100644--- a/src/app/[variants]/(main)/home/_layout/Body/Project/List/index.tsx+++ b/src/app/[variants]/(main)/home/_layout/Body/Project/List/index.tsx@@ -6,7 +6,7 @@ import { useTranslation } from 'react-i18next';import { Link, useNavigate } from 'react-router-dom';import { LIBRARY_URL } from '@/const/url';-import { useKnowledgeBaseStore } from '@/store/knowledgeBase';+import { useKnowledgeBaseStore } from '@/store/library';import EmptyNavItem from '../../../../../../../../features/NavPanel/components/EmptyNavItem';import SkeletonList from '../../../../../../../../features/NavPanel/components/SkeletonList';diff --git a/src/app/[variants]/(main)/home/_layout/Body/Project/List/useDropdownMenu.tsx b/src/app/[variants]/(main)/home/_layout/Body/Project/List/useDropdownMenu.tsxindex e29663e6693..3fe2faff0e2 100644--- a/src/app/[variants]/(main)/home/_layout/Body/Project/List/useDropdownMenu.tsx+++ b/src/app/[variants]/(main)/home/_layout/Body/Project/List/useDropdownMenu.tsx@@ -4,7 +4,7 @@ import { PencilLine, Trash } from 'lucide-react';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';-import { useKnowledgeBaseStore } from '@/store/knowledgeBase';+import { useKnowledgeBaseStore } from '@/store/library';interface ProjectItemDropdownMenuProps {id: string;diff --git a/src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/List/Item/Actions.tsx b/src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/Item/Actions.tsxsimilarity index 100%rename from src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/List/Item/Actions.tsxrename to src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/Item/Actions.tsxdiff --git a/src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/List/Item/Editing.tsx b/src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/Item/Editing.tsxsimilarity index 96%rename from src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/List/Item/Editing.tsxrename to src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/Item/Editing.tsxindex b326f5d1944..21cc3eff769 100644--- a/src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/List/Item/Editing.tsx+++ b/src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/Item/Editing.tsx@@ -1,7 +1,7 @@import { Input, Popover } from '@lobehub/ui';import { memo, useCallback, useEffect, useState } from 'react';-import { useKnowledgeBaseStore } from '@/store/knowledgeBase';+import { useKnowledgeBaseStore } from '@/store/library';interface EditingProps {id: string;diff --git a/src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/List/Item/index.tsx b/src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/Item/index.tsxsimilarity index 97%rename from src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/List/Item/index.tsxrename to src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/Item/index.tsxindex 7f137c3082f..5277716f8ff 100644--- a/src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/List/Item/index.tsx+++ b/src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/Item/index.tsx@@ -7,7 +7,7 @@ import { useNavigate } from 'react-router-dom';import { useResourceManagerStore } from '@/app/[variants]/(main)/resource/features/store';import RepoIcon from '@/components/LibIcon';import NavItem from '@/features/NavPanel/components/NavItem';-import { useKnowledgeBaseStore } from '@/store/knowledgeBase';+import { useKnowledgeBaseStore } from '@/store/library';import Actions from './Actions';import Editing from './Editing';diff --git a/src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/List/Item/useDropdownMenu.tsx b/src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/Item/useDropdownMenu.tsxsimilarity index 95%rename from src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/List/Item/useDropdownMenu.tsxrename to src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/Item/useDropdownMenu.tsxindex 6702b1107ce..4b7ee2196bd 100644--- a/src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/List/Item/useDropdownMenu.tsx+++ b/src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/Item/useDropdownMenu.tsx@@ -4,7 +4,7 @@ import { PencilLine, Trash } from 'lucide-react';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';-import { useKnowledgeBaseStore } from '@/store/knowledgeBase';+import { useKnowledgeBaseStore } from '@/store/library';interface ActionProps {id: string;diff --git a/src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/List/index.tsx b/src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/List/index.tsxdeleted file mode 100644index b1d45daf9c6..00000000000--- a/src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/List/index.tsx+++ /dev/null@@ -1,25 +0,0 @@-'use client';--import { Flexbox } from '@lobehub/ui';-import { memo } from 'react';--import { useKnowledgeBaseStore } from '@/store/knowledgeBase';--import Item from './Item';--const KnowledgeBaseListView = memo(() => {- const useFetchKnowledgeBaseList = useKnowledgeBaseStore((s) => s.useFetchKnowledgeBaseList);- const { data } = useFetchKnowledgeBaseList();-- if (!data || data.length === 0) return null;-- return (- <Flexbox gap={1} paddingInline={4}>- {data.map((item) => (- <Item id={item.id} key={item.id} name={item.name} />- ))}- </Flexbox>- );-});--export default KnowledgeBaseListView;diff --git a/src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/index.tsx b/src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/index.tsxindex f2ed87aa8ac..3ec040c37f7 100644--- a/src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/index.tsx+++ b/src/app/[variants]/(main)/resource/(home)/_layout/Body/LibraryList/index.tsx@@ -1,17 +1,21 @@'use client';-import React, { memo } from 'react';+import { Flexbox } from '@lobehub/ui';+import { memo } from 'react';import { useTranslation } from 'react-i18next';import { useNavigate } from 'react-router-dom';import { useCreateNewModal } from '@/features/LibraryModal';import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';import SkeletonList from '@/features/NavPanel/components/SkeletonList';-import { useKnowledgeBaseStore } from '@/store/knowledgeBase';+import { useKnowledgeBaseStore } from '@/store/library';-import List from './List';+import Item from './Item';-const KnowledgeBaseList = memo(() => {+/**+ * Show library list in the sidebar+ */+const LibraryList = memo(() => {const { t } = useTranslation('file');const useFetchKnowledgeBaseList = useKnowledgeBaseStore((s) => s.useFetchKnowledgeBaseList);const { data, isLoading } = useFetchKnowledgeBaseList();@@ -32,7 +36,13 @@ const KnowledgeBaseList = memo(() => {if (data?.length === 0) return <EmptyNavItem onClick={handleCreate} title={t('library.new')} />;- return <List />;+ return (+ <Flexbox gap={1} paddingInline={4}>+ {data?.map((item) => (+ <Item id={item.id} key={item.id} name={item.name} />+ ))}+ </Flexbox>+ );});-export default KnowledgeBaseList;+export default LibraryList;diff --git a/src/app/[variants]/(main)/resource/(home)/_layout/Body/KnowledgeBase.tsx b/src/app/[variants]/(main)/resource/(home)/_layout/Body/index.tsxsimilarity index 89%rename from src/app/[variants]/(main)/resource/(home)/_layout/Body/KnowledgeBase.tsxrename to src/app/[variants]/(main)/resource/(home)/_layout/Body/index.tsxindex cda531724bf..0e7959250d1 100644--- a/src/app/[variants]/(main)/resource/(home)/_layout/Body/KnowledgeBase.tsx+++ b/src/app/[variants]/(main)/resource/(home)/_layout/Body/index.tsx@@ -8,7 +8,7 @@ import { useCreateNewModal } from '@/features/LibraryModal';import LibraryList from './LibraryList';-const Collection = memo<{ itemKey: string }>(({ itemKey }) => {+const SidebarBody = memo<{ itemKey: string }>(({ itemKey }) => {const { t } = useTranslation('file');const navigate = useNavigate();@@ -29,7 +29,6 @@ const Collection = memo<{ itemKey: string }>(({ itemKey }) => {icon={PlusIcon}onClick={handleCreate}size={'small'}- style={{ flex: 'none' }}title={t('library.new')}/>}@@ -47,4 +46,4 @@ const Collection = memo<{ itemKey: string }>(({ itemKey }) => {);});-export default Collection;+export default SidebarBody;diff --git a/src/app/[variants]/(main)/resource/(home)/_layout/Sidebar.tsx b/src/app/[variants]/(main)/resource/(home)/_layout/Sidebar.tsxindex f21ac08df37..6c3176dcf11 100644--- a/src/app/[variants]/(main)/resource/(home)/_layout/Sidebar.tsx+++ b/src/app/[variants]/(main)/resource/(home)/_layout/Sidebar.tsx@@ -6,7 +6,7 @@ import { memo } from 'react';import { NavPanelPortal } from '@/features/NavPanel';import SideBarLayout from '@/features/NavPanel/SideBarLayout';-import Collection from './Body/KnowledgeBase';+import SidebarBody from './Body';import Header from './Header';export enum GroupKey {@@ -20,7 +20,7 @@ const Sidebar = memo(() => {body={<Flexbox paddingBlock={8} paddingInline={4}><Accordion defaultExpandedKeys={[GroupKey.Library]} gap={8}>- <Collection itemKey={GroupKey.Library} />+ <SidebarBody itemKey={GroupKey.Library} /></Accordion></Flexbox>}diff --git a/src/app/[variants]/(main)/resource/(home)/index.tsx b/src/app/[variants]/(main)/resource/(home)/index.tsxindex 60f28c1d8dd..8789517d52f 100644--- a/src/app/[variants]/(main)/resource/(home)/index.tsx+++ b/src/app/[variants]/(main)/resource/(home)/index.tsx@@ -1,7 +1,7 @@'use client';-import { memo, useEffect } from 'react';-import { useSearchParams } from 'react-router-dom';+import { memo, useEffect, useLayoutEffect } from 'react';+import { useLocation, useSearchParams } from 'react-router-dom';import ResourceManager from '@/features/ResourceManager';import { documentSelectors, useFileStore } from '@/store/file';@@ -11,6 +11,7 @@ import { useResourceManagerStore } from '../features/store';const ResourceHomePage = memo(() => {const [searchParams] = useSearchParams();+ const location = useLocation();const [setMode, setCurrentViewItemId, setCategory, setLibraryId] = useResourceManagerStore((s) => [s.setMode, s.setCurrentViewItemId, s.setCategory, s.setLibraryId],);@@ -23,15 +24,27 @@ const ResourceHomePage = memo(() => {const { data: fileData } = useFetchKnowledgeItem(fileId || undefined);const documentData = useFileStore(documentSelectors.getDocumentById(fileId || undefined));- // Clear libraryId when on home route (only once on mount)- useEffect(() => {- setLibraryId(undefined);- }, [setLibraryId]);+ // Clear libraryId when on home route using useLayoutEffect+ // useLayoutEffect runs synchronously before browser paint, ensuring state is cleared+ // before child components' useEffects run, while avoiding React's setState-in-render error+ // IMPORTANT: Only depend on location.pathname, NOT currentLibraryId to avoid feedback loop+ // When location changes to /resource, clear libraryId+ // Don't clear when location is /library/* (even if this component is still mounted)+ useLayoutEffect(() => {+ const isOnHomeRoute = location.pathname === '/resource' || !location.pathname.includes('/library/');+ if (isOnHomeRoute) {+ setLibraryId(undefined);+ }+ }, [setLibraryId, location.pathname]);- // Sync category from URL- useEffect(() => {- setCategory(categoryParam);- }, [categoryParam, setCategory]);+ // Sync category from URL using useLayoutEffect+ // IMPORTANT: Only sync if we're actually on the home route (not transitioning to library)+ useLayoutEffect(() => {+ const isOnHomeRoute = location.pathname === '/resource' || !location.pathname.includes('/library/');+ if (isOnHomeRoute) {+ setCategory(categoryParam);+ }+ }, [categoryParam, setCategory, location.pathname]);// Sync file view mode from URLuseEffect(() => {diff --git a/src/app/[variants]/(main)/resource/features/DndContextWrapper.tsx b/src/app/[variants]/(main)/resource/features/DndContextWrapper.tsxindex c22bd018a35..edf9744baa3 100644--- a/src/app/[variants]/(main)/resource/features/DndContextWrapper.tsx+++ b/src/app/[variants]/(main)/resource/features/DndContextWrapper.tsx@@ -60,6 +60,7 @@ interface DragState {const DragStateContext = createContext<{currentDrag: DragState | null;+ // eslint-disable-next-line @typescript-eslint/no-unused-varssetCurrentDrag: (state: DragState | null) => void;}>({currentDrag: null,@@ -77,10 +78,8 @@ export const DndContextWrapper = memo<PropsWithChildren>(({ children }) => {const { message } = App.useApp();const [currentDrag, setCurrentDrag] = useState<DragState | null>(null);const overlayRef = useRef<HTMLDivElement>(null);- const updateDocument = useFileStore((s) => s.updateDocument);- const moveFileToFolder = useFileStore((s) => s.moveFileToFolder);- const refreshFileList = useFileStore((s) => s.refreshFileList);- const fileList = useFileStore((s) => s.fileList);+ const moveResource = useFileStore((s) => s.moveResource);+ const resourceList = useFileStore((s) => s.resourceList);const selectedFileIds = useResourceManagerStore((s) => s.selectedFileIds);const setSelectedFileIds = useResourceManagerStore((s) => s.setSelectedFileIds);const libraryId = useResourceManagerStore((s) => s.libraryId);@@ -143,8 +142,8 @@ export const DndContextWrapper = memo<PropsWithChildren>(({ children }) => {}// Save current drag data before clearing state- const draggedItemId = currentDrag.id;- const draggedItemData = currentDrag.data;+ // const draggedItemId = currentDrag.id;+ // const draggedItemData = currentDrag.data;// Clear drag state immediately for better UXsetCurrentDrag(null);@@ -153,36 +152,14 @@ export const DndContextWrapper = memo<PropsWithChildren>(({ children }) => {const hideLoading = message.loading(t('FileManager.actions.moving'), 0);try {- // Track source folder IDs before moving- const sourceFolderIds = new Set<string | null>();-- const pools = itemsToMove.map((id) => {- const item = fileList.find((f) => f.id === id);- const itemData = item || (id === draggedItemId ? draggedItemData : null);-- if (!itemData) return Promise.resolve();-- // Track source folder ID- if (item?.parentId !== undefined) {- sourceFolderIds.add(item.parentId);- }-- const isDocument =- itemData.sourceType === 'document' ||- itemData.fileType === 'custom/document' ||- itemData.fileType === 'custom/folder';-- if (isDocument) {- return updateDocument(id, { parentId: targetParentId });- } else {- return moveFileToFolder(id, targetParentId);- }- });+ // Move all items using optimistic moveResource+ const pools = itemsToMove.map((id) => moveResource(id, targetParentId));await Promise.all(pools);- // Refresh file list to invalidate SWR cache for both Explorer and Tree- await refreshFileList();+ // Refetch resources to update the view (items should disappear from current folder)+ const { revalidateResources } = await import('@/store/file/slices/resource/hooks');+ await revalidateResources();// Clear and reload all expanded folders in Tree's module-level cacheif (libraryId) {@@ -230,10 +207,8 @@ export const DndContextWrapper = memo<PropsWithChildren>(({ children }) => {}, [currentDrag,selectedFileIds,- fileList,- updateDocument,- moveFileToFolder,- refreshFileList,+ resourceList,+ moveResource,setSelectedFileIds,message,t,diff --git a/src/app/[variants]/(main)/resource/features/hooks/useKnowledgeItem.ts b/src/app/[variants]/(main)/resource/features/hooks/useKnowledgeItem.tsindex 97433656525..18429fbb5db 100644--- a/src/app/[variants]/(main)/resource/features/hooks/useKnowledgeItem.ts+++ b/src/app/[variants]/(main)/resource/features/hooks/useKnowledgeItem.ts@@ -1,4 +1,4 @@-import { useKnowledgeBaseStore } from '@/store/knowledgeBase';+import { useKnowledgeBaseStore } from '@/store/library';export const useKnowledgeBaseItem = (id: string) => {const useFetchKnowledgeBaseItem = useKnowledgeBaseStore((s) => s.useFetchKnowledgeBaseItem);diff --git a/src/app/[variants]/(main)/resource/features/store/action.ts b/src/app/[variants]/(main)/resource/features/store/action.tsindex e3d5a9ec7b4..af3be7e2c03 100644--- a/src/app/[variants]/(main)/resource/features/store/action.ts+++ b/src/app/[variants]/(main)/resource/features/store/action.ts@@ -130,7 +130,7 @@ export const store: CreateStore = (publicState) => (set, get) => ({onActionClick: async (type) => {const { selectedFileIds, libraryId } = get();const { useFileStore } = await import('@/store/file');- const { useKnowledgeBaseStore } = await import('@/store/knowledgeBase');+ const { useKnowledgeBaseStore } = await import('@/store/library');const { isChunkingUnsupported } = await import('@/utils/isChunkingUnsupported');const fileStore = useFileStore.getState();@@ -138,37 +138,9 @@ export const store: CreateStore = (publicState) => (set, get) => ({switch (type) {case 'delete': {- // Separate documents/pages from regular files- const documentsToDelete: string[] = [];- const filesToDelete: string[] = [];-- selectedFileIds.forEach((id) => {- const item = fileStore.fileList.find((f) => f.id === id);- if (!item) return;-- const isPage = item.sourceType === 'document' || item.fileType === 'custom/document';- const isFolder = item.fileType === 'custom/folder';-- if (isPage || isFolder) {- documentsToDelete.push(id);- } else {- filesToDelete.push(id);- }- });-- // Delete documents using batch delete endpoint- if (documentsToDelete.length > 0) {- const { documentService } = await import('@/services/document');- await documentService.deleteDocuments(documentsToDelete);- }-- // Delete regular files using file service- if (filesToDelete.length > 0) {- await fileStore.removeFiles(filesToDelete);- } else {- // If only documents were deleted, still refresh the file list- await fileStore.refreshFileList();- }+ // Use optimistic deleteResource for instant batch delete+ // All items disappear immediately, sync happens in background+ await Promise.all(selectedFileIds.map((id) => fileStore.deleteResource(id)));set({ selectedFileIds: [] });return;@@ -197,8 +169,8 @@ export const store: CreateStore = (publicState) => (set, get) => ({case 'batchChunking': {const chunkableFileIds = selectedFileIds.filter((id) => {- const file = fileStore.fileList.find((f) => f.id === id);- return file && !isChunkingUnsupported(file.fileType);+ const resource = fileStore.resourceMap?.get(id);+ return resource && !isChunkingUnsupported(resource.fileType);});await fileStore.parseFilesToChunks(chunkableFileIds, { skipExist: true });set({ selectedFileIds: [] });@@ -246,7 +218,7 @@ export const store: CreateStore = (publicState) => (set, get) => ({set({ isTransitioning });},- setLibraryId: async (libraryId) => {+ setLibraryId: (libraryId) => {set({ libraryId });// Reset pagination state when switching libraries to prevent showing stale data@@ -255,10 +227,8 @@ export const store: CreateStore = (publicState) => (set, get) => ({fileListOffset: 0,});- // Invalidate SWR cache to prevent showing stale data from previous library- const { useFileStore } = await import('@/store/file');- const fileStore = useFileStore.getState();- await fileStore.refreshFileList();+ // Note: No need to manually refresh - Explorer's useEffect will automatically+ // call fetchResources when libraryId changes},setMode: (mode) => {diff --git a/src/app/[variants]/(main)/resource/library/_layout/Header/LibraryHead.tsx b/src/app/[variants]/(main)/resource/library/_layout/Header/LibraryHead.tsxindex cbdda0b31cb..a410cce6420 100644--- a/src/app/[variants]/(main)/resource/library/_layout/Header/LibraryHead.tsx+++ b/src/app/[variants]/(main)/resource/library/_layout/Header/LibraryHead.tsx@@ -9,7 +9,7 @@ import { useNavigate } from 'react-router-dom';import { useDragActive } from '@/app/[variants]/(main)/resource/features/DndContextWrapper';import { useResourceManagerStore } from '@/app/[variants]/(main)/resource/features/store';import RepoIcon from '@/components/LibIcon';-import { knowledgeBaseSelectors, useKnowledgeBaseStore } from '@/store/knowledgeBase';+import { knowledgeBaseSelectors, useKnowledgeBaseStore } from '@/store/library';const styles = createStaticStyles(({ css, cssVar }) => ({clickableHeader: css`diff --git a/src/app/[variants]/(main)/resource/library/index.tsx b/src/app/[variants]/(main)/resource/library/index.tsxindex e333eb87c6b..cb0e4aa0e48 100644--- a/src/app/[variants]/(main)/resource/library/index.tsx+++ b/src/app/[variants]/(main)/resource/library/index.tsx@@ -1,7 +1,7 @@'use client';-import { memo, useEffect } from 'react';-import { useParams, useSearchParams } from 'react-router-dom';+import { memo, useEffect, useLayoutEffect } from 'react';+import { useLocation, useParams, useSearchParams } from 'react-router-dom';import Container from '@/app/[variants]/(main)/resource/library/features/Container';import NProgress from '@/components/NProgress';@@ -14,6 +14,7 @@ import { useResourceManagerStore } from '../features/store';const MainContent = memo(() => {const { id: knowledgeBaseId } = useParams<{ id: string }>();const [searchParams] = useSearchParams();+ const location = useLocation();const [setMode, setCurrentViewItemId, setLibraryId] = useResourceManagerStore((s) => [s.setMode,s.setCurrentViewItemId,@@ -30,10 +31,16 @@ const MainContent = memo(() => {// Load knowledge base datauseKnowledgeBaseItem(knowledgeBaseId || '');- // Set libraryId from URL params (only when knowledgeBaseId changes)- useEffect(() => {- setLibraryId(knowledgeBaseId);- }, [knowledgeBaseId, setLibraryId]);+ // Sync libraryId from URL params using useLayoutEffect+ // useLayoutEffect runs synchronously before browser paint, ensuring state is set+ // before Explorer component renders and computes query parameters+ // IMPORTANT: Only depend on knowledgeBaseId and location.pathname, NOT currentLibraryId to avoid feedback loop+ useLayoutEffect(() => {+ const isOnLibraryRoute = location.pathname.includes('/library/');+ if (isOnLibraryRoute) {+ setLibraryId(knowledgeBaseId);+ }+ }, [knowledgeBaseId, setLibraryId, location.pathname]);// Sync file view mode from URLuseEffect(() => {diff --git a/src/features/LibraryModal/AddFilesToKnowledgeBase/SelectForm.tsx b/src/features/LibraryModal/AddFilesToKnowledgeBase/SelectForm.tsxindex 3f68ab7cd86..c7bde3bd612 100644--- a/src/features/LibraryModal/AddFilesToKnowledgeBase/SelectForm.tsx+++ b/src/features/LibraryModal/AddFilesToKnowledgeBase/SelectForm.tsx@@ -5,7 +5,7 @@ import { memo, useState } from 'react';import { Trans, useTranslation } from 'react-i18next';import RepoIcon from '@/components/LibIcon';-import { useKnowledgeBaseStore } from '@/store/knowledgeBase';+import { useKnowledgeBaseStore } from '@/store/library';interface CreateFormProps {fileIds: string[];diff --git a/src/features/LibraryModal/CreateNew/CreateForm.tsx b/src/features/LibraryModal/CreateNew/CreateForm.tsxindex 24f3bf3baa9..eb166487e3a 100644--- a/src/features/LibraryModal/CreateNew/CreateForm.tsx+++ b/src/features/LibraryModal/CreateNew/CreateForm.tsx@@ -2,7 +2,7 @@ import { Button, Form, Input, TextArea } from '@lobehub/ui';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { useKnowledgeBaseStore } from '@/store/knowledgeBase';+import { useKnowledgeBaseStore } from '@/store/library';import { type CreateKnowledgeBaseParams } from '@/types/knowledgeBase';interface CreateFormProps {diff --git a/src/features/PageEditor/Header/Breadcrumb.tsx b/src/features/PageEditor/Header/Breadcrumb.tsxindex 76588861d4e..003b9fb3ed3 100644--- a/src/features/PageEditor/Header/Breadcrumb.tsx+++ b/src/features/PageEditor/Header/Breadcrumb.tsx@@ -4,7 +4,7 @@ import { memo } from 'react';import { useTranslation } from 'react-i18next';import { useFileStore } from '@/store/file';-import { knowledgeBaseSelectors, useKnowledgeBaseStore } from '@/store/knowledgeBase';+import { knowledgeBaseSelectors, useKnowledgeBaseStore } from '@/store/library';import { usePageEditorStore } from '../store';diff --git a/src/features/PageEditor/store/action.ts b/src/features/PageEditor/store/action.tsindex 9153433dd5f..75b417e3fe5 100644--- a/src/features/PageEditor/store/action.ts+++ b/src/features/PageEditor/store/action.ts@@ -181,7 +181,7 @@ export const store: (initState?: Partial<State>) => StateCreator<Store> =return;}- const { updateDocumentOptimistically, replaceTempDocumentWithReal, refreshFileList } =+ const { updateDocumentOptimistically, replaceTempDocumentWithReal } =useFileStore.getState();if (currentDocId && !currentDocId.startsWith('temp-document-')) {@@ -241,7 +241,10 @@ export const store: (initState?: Partial<State>) => StateCreator<Store> =set({ currentDocId: newPage.id });onDocumentIdChange?.(newPage.id);- refreshFileList();++ // Refetch resource list to show newly created page+ const { revalidateResources } = await import('@/store/file/slices/resource/hooks');+ await revalidateResources();}if (hadFocus) {diff --git a/src/features/PageExplorer/PageExplorerPlaceholder.tsx b/src/features/PageExplorer/PageExplorerPlaceholder.tsxindex 50de40048c8..c224dac6e1d 100644--- a/src/features/PageExplorer/PageExplorerPlaceholder.tsx+++ b/src/features/PageExplorer/PageExplorerPlaceholder.tsx@@ -82,7 +82,6 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(createOptimisticDocument,replaceTempDocumentWithReal,setSelectedPageId,- refreshFileList,fetchDocuments,] = useFileStore((s) => [s.createNewPage,@@ -90,7 +89,6 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(s.createOptimisticDocument,s.replaceTempDocumentWithReal,s.setSelectedPageId,- s.refreshFileList,s.fetchDocuments,]);@@ -98,7 +96,11 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(createDocument,currentFolderId: null,libraryId: knowledgeBaseId ?? null,- refreshFileList,+ refetchResources: async () => {+ const { revalidateResources } = await import('@/store/file/slices/resource/hooks');+ await revalidateResources();+ await fetchDocuments({ pageOnly: true });+ },t,});@@ -107,10 +109,6 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(event: React.ChangeEvent<HTMLInputElement>,) => {await notionImport.handleNotionImport(event);- // Fetch documents to update the UI immediately- // The hook calls refreshFileList which invalidates SWR cache,- // but we need to explicitly fetch to update the zustand store- await fetchDocuments({ pageOnly: true });};const handleCreateDocument = async (content: string, title: string) => {diff --git a/src/features/ResourceManager/components/Explorer/Header/Breadcrumb.tsx b/src/features/ResourceManager/components/Explorer/Header/Breadcrumb.tsxindex 9cfdc2705ea..3daad66590f 100644--- a/src/features/ResourceManager/components/Explorer/Header/Breadcrumb.tsx+++ b/src/features/ResourceManager/components/Explorer/Header/Breadcrumb.tsx@@ -7,7 +7,7 @@ import { useNavigate, useSearchParams } from 'react-router-dom';import { useFolderPath } from '@/app/[variants]/(main)/resource/features/hooks/useFolderPath';import { useResourceManagerStore } from '@/app/[variants]/(main)/resource/features/store';import { useFileStore } from '@/store/file';-import { knowledgeBaseSelectors, useKnowledgeBaseStore } from '@/store/knowledgeBase';+import { knowledgeBaseSelectors, useKnowledgeBaseStore } from '@/store/library';import { FilesTabs } from '@/types/files';const styles = createStaticStyles(({ css, cssVar }) => ({diff --git a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsxindex 42f0f345177..0f93a75d1b3 100644--- a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx+++ b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx@@ -12,11 +12,14 @@ import {} from 'lucide-react';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';+import { shallow } from 'zustand/shallow';import RepoIcon from '@/components/LibIcon';+import { clearTreeFolderCache } from '@/features/ResourceManager/components/Tree';+import { PAGE_FILE_TYPE } from '@/features/ResourceManager/constants';import { documentService } from '@/services/document';import { useFileStore } from '@/store/file';-import { useKnowledgeBaseStore } from '@/store/knowledgeBase';+import { useKnowledgeBaseStore } from '@/store/library';import { downloadFile } from '@/utils/client/downloadFile';import MoveToFolderModal from '../MoveToFolderModal';@@ -26,7 +29,7 @@ interface UseFileItemDropdownParams {fileType: string;filename: string;id: string;- knowledgeBaseId?: string;+ libraryId?: string;onRenameStart?: () => void;sourceType?: string;url: string;@@ -36,9 +39,12 @@ interface UseFileItemDropdownReturn {menuItems: () => ItemType[];}+/**+ * Shared with folder tree and explorer+ */export const useFileItemDropdown = ({id,- knowledgeBaseId,+ libraryId,url,filename,fileType,@@ -48,7 +54,13 @@ export const useFileItemDropdown = ({const { t } = useTranslation(['components', 'common', 'knowledgeBase']);const { message, modal } = App.useApp();- const [removeFile, refreshFileList] = useFileStore((s) => [s.removeFileItem, s.refreshFileList]);+ const { deleteResource, refreshFileList } = useFileStore(+ (s) => ({+ deleteResource: s.deleteResource,+ refreshFileList: s.refreshFileList,+ }),+ shallow,+ );const [removeFilesFromKnowledgeBase, addFilesToKnowledgeBase, useFetchKnowledgeBaseList] =useKnowledgeBaseStore((s) => [s.removeFilesFromKnowledgeBase,@@ -59,17 +71,15 @@ export const useFileItemDropdown = ({// Fetch knowledge bases - SWR caches this across all dropdown instances// Only the first call fetches from server, subsequent calls use cache// The expensive menu computation is deferred until dropdown opens (menuItems is a function)- const { data: knowledgeBases } = useFetchKnowledgeBaseList();+ const { data: libraries } = useFetchKnowledgeBaseList();- const inKnowledgeBase = !!knowledgeBaseId;+ const isInLibrary = !!libraryId;const isFolder = fileType === 'custom/folder';- const isPage = sourceType === 'document' || fileType === 'custom/document';+ const isPage = sourceType === 'document' || fileType === PAGE_FILE_TYPE;const menuItems = useCallback(() => {// Filter out current knowledge base and create submenu items- const availableKnowledgeBases = (knowledgeBases || []).filter(- (kb) => kb.id !== knowledgeBaseId,- );+ const availableKnowledgeBases = (libraries || []).filter((kb) => kb.id !== libraryId);const addToKnowledgeBaseSubmenu: ItemType[] = availableKnowledgeBases.map((kb) => ({icon: <RepoIcon />,@@ -92,8 +102,8 @@ export const useFileItemDropdown = ({},}));- const knowledgeBaseActions = (- inKnowledgeBase+ const libraryRelatedActions = (+ isInLibrary? [availableKnowledgeBases.length > 0 && {children: addToKnowledgeBaseSubmenu,@@ -113,7 +123,7 @@ export const useFileItemDropdown = ({danger: true,},onOk: async () => {- await removeFilesFromKnowledgeBase(knowledgeBaseId, [id]);+ await removeFilesFromKnowledgeBase(libraryId, [id]);message.success(t('FileManager.actions.removeFromKnowledgeBaseSuccess'));},@@ -134,15 +144,15 @@ export const useFileItemDropdown = ({]) as ItemType[];- const hasKnowledgeBaseActions = knowledgeBaseActions.some(Boolean);+ const hasKnowledgeBaseActions = libraryRelatedActions.some(Boolean);return ([- ...knowledgeBaseActions,+ ...libraryRelatedActions,hasKnowledgeBaseActions && {type: 'divider',},- inKnowledgeBase && {+ isInLibrary && {icon: <Icon icon={FolderInputIcon} />,key: 'moveToFolder',label: t('FileManager.actions.moveToFolder'),@@ -151,8 +161,7 @@ export const useFileItemDropdown = ({createRawModal(MoveToFolderModal, {fileId: id,- fileType,- knowledgeBaseId,+ knowledgeBaseId: libraryId,});},},@@ -176,8 +185,8 @@ export const useFileItemDropdown = ({let urlToCopy = url;if (isPage) {const baseUrl = window.location.origin;- if (knowledgeBaseId) {- urlToCopy = `${baseUrl}/resource/library/${knowledgeBaseId}?file=${id}`;+ if (libraryId) {+ urlToCopy = `${baseUrl}/resource/library/${libraryId}?file=${id}`;} else {urlToCopy = `${baseUrl}/resource?file=${id}`;}@@ -249,19 +258,41 @@ export const useFileItemDropdown = ({: t('FileManager.actions.confirmDelete'),okButtonProps: { danger: true },onOk: async () => {- if (isFolder || isPage) {- await documentService.deleteDocument(id);- await refreshFileList();- } else {- await removeFile(id);+ // Use optimistic delete - instant UI update, sync in background+ await deleteResource(id);++ // Ensure tree caches stay in sync with explorer+ if (libraryId) {+ await clearTreeFolderCache(libraryId);}+ await refreshFileList();++ message.success(t('FileManager.actions.deleteSuccess'));},});},},] as ItemType[]).filter(Boolean);- }, [inKnowledgeBase, isFolder, knowledgeBases, knowledgeBaseId, id]);+ }, [+ addFilesToKnowledgeBase,+ clearTreeFolderCache,+ deleteResource,+ filename,+ id,+ isFolder,+ isInLibrary,+ isPage,+ libraries,+ libraryId,+ message,+ modal,+ onRenameStart,+ refreshFileList,+ removeFilesFromKnowledgeBase,+ t,+ url,+ ]);return { menuItems };};diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx b/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsxindex f65ae62f27b..bdd59147802 100644--- a/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx@@ -17,6 +17,8 @@ import {} from '@/app/[variants]/(main)/resource/features/DndContextWrapper';import { useResourceManagerStore } from '@/app/[variants]/(main)/resource/features/store';import FileIcon from '@/components/FileIcon';+import { clearTreeFolderCache } from '@/features/ResourceManager/components/Tree';+import { PAGE_FILE_TYPE } from '@/features/ResourceManager/constants';import { fileManagerSelectors, useFileStore } from '@/store/file';import { type FileListItem as FileListItemType } from '@/types/files';import { formatSize } from '@/utils/format';@@ -142,7 +144,8 @@ const FileListItem = memo<FileListItemProps>((s) => ({isCreatingFileParseTask: fileManagerSelectors.isCreatingFileParseTask(id)(s),parseFiles: s.parseFilesToChunks,- renameFolder: s.renameFolder,+ refreshFileList: s.refreshFileList,+ updateResource: s.updateResource,}),shallow,);@@ -161,6 +164,7 @@ const FileListItem = memo<FileListItemProps>(const [isRenaming, setIsRenaming] = useState(false);const [renamingValue, setRenamingValue] = useState(name);const inputRef = useRef<any>(null);+ const isConfirmingRef = useRef(false);const isDragActive = useDragActive();const { setCurrentDrag } = useDragState();const [isDragging, setIsDragging] = useState(false);@@ -170,10 +174,10 @@ const FileListItem = memo<FileListItemProps>(const computedValues = useMemo(() => {const isPDF = fileType?.toLowerCase() === 'pdf' || name?.toLowerCase().endsWith('.pdf');return {- emoji: sourceType === 'document' || fileType === 'custom/document' ? metadata?.emoji : null,+ emoji: sourceType === 'document' || fileType === PAGE_FILE_TYPE ? metadata?.emoji : null,isFolder: fileType === 'custom/folder',// PDF files should not be treated as pages, even if they have sourceType='document'- isPage: !isPDF && (sourceType === 'document' || fileType === 'custom/document'),+ isPage: !isPDF && (sourceType === 'document' || fileType === PAGE_FILE_TYPE),isSupportedForChunking: !isChunkingUnsupported(fileType),};}, [fileType, sourceType, metadata?.emoji, name]);@@ -260,27 +264,52 @@ const FileListItem = memo<FileListItemProps>(}, [name]);const handleRenameConfirm = useCallback(async () => {+ // Prevent duplicate calls (e.g., from both Enter key and onBlur)+ if (isConfirmingRef.current) return;+ isConfirmingRef.current = true;+if (!renamingValue.trim()) {message.error(t('FileManager.actions.renameError'));+ isConfirmingRef.current = false;return;}if (renamingValue.trim() === name) {setIsRenaming(false);+ isConfirmingRef.current = false;return;}try {- await fileStoreState.renameFolder(id, renamingValue.trim());+ // Use optimistic updateResource for instant UI update+ await fileStoreState.updateResource(id, { name: renamingValue.trim() });+ if (resourceManagerState.libraryId) {+ await clearTreeFolderCache(resourceManagerState.libraryId);+ }+ await fileStoreState.refreshFileList();+message.success(t('FileManager.actions.renameSuccess'));setIsRenaming(false);} catch (error) {console.error('Rename error:', error);message.error(t('FileManager.actions.renameError'));+ } finally {+ isConfirmingRef.current = false;}- }, [renamingValue, name, fileStoreState.renameFolder, id, message, t]);+ }, [+ fileStoreState.refreshFileList,+ fileStoreState.updateResource,+ id,+ message,+ name,+ renamingValue,+ resourceManagerState.libraryId,+ t,+ ]);const handleRenameCancel = useCallback(() => {+ // Don't cancel if we're in the middle of confirming+ if (isConfirmingRef.current) return;setIsRenaming(false);setRenamingValue(name);}, [name]);@@ -334,7 +363,7 @@ const FileListItem = memo<FileListItemProps>(fileType,filename: name,id,- knowledgeBaseId: resourceManagerState.libraryId,+ libraryId: resourceManagerState.libraryId,onRenameStart: isFolder ? handleRenameStart : undefined,sourceType,url,diff --git a/src/features/ResourceManager/components/Explorer/ListView/Skeleton.tsx b/src/features/ResourceManager/components/Explorer/ListView/Skeleton.tsxindex 36a3f123000..4e5ace11c21 100644--- a/src/features/ResourceManager/components/Explorer/ListView/Skeleton.tsx+++ b/src/features/ResourceManager/components/Explorer/ListView/Skeleton.tsx@@ -14,20 +14,25 @@ interface ListViewSkeletonProps {const ListViewSkeleton = ({columnWidths = { date: FILE_DATE_WIDTH, name: 400, size: FILE_SIZE_WIDTH },- count = 3,-}: ListViewSkeletonProps) => (- <Flexbox>- {Array.from({ length: count }).map((_, index) => (- <Flexbox- align={'center'}- height={48}- horizontal- key={index}- paddingInline={8}- style={{- borderBlockEnd: `1px solid ${cssVar.colorBorderSecondary}`,- }}- >+ count = 6,+}: ListViewSkeletonProps) => {+ // Calculate opacity gradient from 100% to 20%+ const getOpacity = (index: number) => 1 - (index / (count - 1)) * 0.8;++ return (+ <Flexbox>+ {Array.from({ length: count }).map((_, index) => (+ <Flexbox+ align={'center'}+ height={48}+ horizontal+ key={index}+ paddingInline={8}+ style={{+ borderBlockEnd: `1px solid ${cssVar.colorBorderSecondary}`,+ opacity: getOpacity(index),+ }}+ ><Center height={40} style={{ paddingInline: 4 }}><Checkbox disabled /></Center>@@ -55,5 +60,6 @@ const ListViewSkeleton = ({))}</Flexbox>);+};export default ListViewSkeleton;diff --git a/src/features/ResourceManager/components/Explorer/ListView/index.tsx b/src/features/ResourceManager/components/Explorer/ListView/index.tsxindex 90c745fefa8..1d9da009005 100644--- a/src/features/ResourceManager/components/Explorer/ListView/index.tsx+++ b/src/features/ResourceManager/components/Explorer/ListView/index.tsx@@ -11,12 +11,14 @@ import { useDragActive } from '@/app/[variants]/(main)/resource/features/DndContimport { useFolderPath } from '@/app/[variants]/(main)/resource/features/hooks/useFolderPath';import {useResourceManagerFetchFolderBreadcrumb,- useResourceManagerFetchKnowledgeItems,useResourceManagerStore,} from '@/app/[variants]/(main)/resource/features/store';import { sortFileList } from '@/app/[variants]/(main)/resource/features/store/selectors';+import { useFileStore } from '@/store/file';import { useGlobalStore } from '@/store/global';import { INITIAL_STATUS } from '@/store/global/initialState';+import { type AsyncTaskStatus } from '@/types/asyncTask';+import { type FileListItem as FileListItemType } from '@/types/files';import ColumnResizeHandle from './ColumnResizeHandle';import FileListItem from './ListItem';@@ -52,11 +54,7 @@ const styles = createStaticStyles(({ css }) => ({}));const ListView = memo(() => {- // Access all state from Resource Manager storeconst [- libraryId,- category,- searchQuery,selectFileIds,setSelectedFileIds,pendingRenameItemId,@@ -65,9 +63,6 @@ const ListView = memo(() => {sorter,sortType,] = useResourceManagerStore((s) => [- s.libraryId,- s.category,- s.searchQuery,s.selectedFileIds,s.setSelectedFileIds,s.pendingRenameItemId,@@ -86,12 +81,12 @@ const ListView = memo(() => {const { t } = useTranslation(['components', 'file']);const virtuosoRef = useRef<VirtuosoHandle>(null);const [isLoadingMore, setIsLoadingMore] = useState(false);- const [lastSelectedIndex, setLastSelectedIndex] = useState<number | null>(null);const isDragActive = useDragActive();const [isDropZoneActive, setIsDropZoneActive] = useState(false);const scrollTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);const autoScrollIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);const containerRef = useRef<HTMLDivElement>(null);+ const lastSelectedIndexRef = useRef<number | null>(null);const { currentFolderSlug } = useFolderPath();const { data: folderBreadcrumb } = useResourceManagerFetchFolderBreadcrumb(currentFolderSlug);@@ -99,28 +94,43 @@ const ListView = memo(() => {// Get current folder ID - either from breadcrumb or null for rootconst currentFolderId = folderBreadcrumb?.at(-1)?.id || null;- const { data: rawData } = useResourceManagerFetchKnowledgeItems({- category,- knowledgeBaseId: libraryId,- parentId: currentFolderSlug || null,- q: searchQuery ?? undefined,- showFilesInKnowledgeBase: false,- });+ const resourceList = useFileStore((s) => s.resourceList);++ // Map ResourceItem[] to FileListItem[] for compatibility+ const rawData =+ resourceList?.map<FileListItemType>((item) => ({+ ...item,+ chunkCount: item.chunkCount ?? null,+ chunkingError: item.chunkingError ?? null,+ chunkingStatus: (item.chunkingStatus ?? null) as AsyncTaskStatus | null,+ embeddingError: item.embeddingError ?? null,+ embeddingStatus: (item.embeddingStatus ?? null) as AsyncTaskStatus | null,+ finishEmbedding: item.finishEmbedding ?? false,+ url: item.url ?? '',+ })) ?? [];// Sort data using current sort settings- const data = sortFileList(rawData, sorter, sortType);+ const data = sortFileList(rawData, sorter, sortType) || [];++ const dataRef = useRef<FileListItemType[]>(data);++ useEffect(() => {+ dataRef.current = data;+ }, [data]);// Handle selection change with shift-click support for range selectionconst handleSelectionChange = useCallback((id: string, checked: boolean, shiftKey: boolean, clickedIndex: number) => {// Always get the latest state from the store to avoid stale closure issuesconst currentSelected = useResourceManagerStore.getState().selectedFileIds;-- if (shiftKey && lastSelectedIndex !== null && data) {- // Shift-click: select range from lastSelectedIndex to current index- const start = Math.min(lastSelectedIndex, clickedIndex);- const end = Math.max(lastSelectedIndex, clickedIndex);- const rangeIds = data+ const lastIndex = lastSelectedIndexRef.current;+ const list = dataRef.current;++ if (shiftKey && lastIndex !== null && list.length > 0) {+ // Shift-click: select range from lastIndex to current index+ const start = Math.min(lastIndex, clickedIndex);+ const end = Math.max(lastIndex, clickedIndex);+ const rangeIds = list.slice(start, end + 1).filter(Boolean).map((item) => item.id);@@ -137,14 +147,14 @@ const ListView = memo(() => {setSelectedFileIds(currentSelected.filter((item) => item !== id));}}- setLastSelectedIndex(clickedIndex);+ lastSelectedIndexRef.current = clickedIndex;},- [lastSelectedIndex, data, setSelectedFileIds],+ [setSelectedFileIds],);// Clean up invalid selections when data changesuseEffect(() => {- if (data && selectFileIds.length > 0) {+ if (selectFileIds.length > 0) {const validFileIds = new Set(data.map((item) => item?.id).filter(Boolean));const filteredSelection = selectFileIds.filter((id) => validFileIds.has(id));if (filteredSelection.length !== selectFileIds.length) {@@ -156,13 +166,13 @@ const ListView = memo(() => {// Reset last selected index when all selections are cleareduseEffect(() => {if (selectFileIds.length === 0) {- setLastSelectedIndex(null);+ lastSelectedIndexRef.current = null;}}, [selectFileIds.length]);// Calculate select all checkbox stateconst { allSelected, indeterminate } = useMemo(() => {- const fileCount = data?.length || 0;+ const fileCount = data.length;const selectedCount = selectFileIds.length;return {allSelected: fileCount > 0 && selectedCount === fileCount,@@ -175,7 +185,7 @@ const ListView = memo(() => {if (allSelected) {setSelectedFileIds([]);} else {- setSelectedFileIds(data?.filter((item) => item).map((item) => item.id) || []);+ setSelectedFileIds(data.map((item) => item.id));}};@@ -303,7 +313,7 @@ const ListView = memo(() => {flexShrink: 0,maxWidth: columnWidths.name,minWidth: columnWidths.name,- paddingInline: 8,+ paddingInline: 20,paddingInlineEnd: 16,position: 'relative',width: columnWidths.name,@@ -364,7 +374,7 @@ const ListView = memo(() => {><Virtuosocomponents={{ Footer }}- data={data || []}+ data={data}defaultItemHeight={48}endReached={handleEndReached}increaseViewportBy={{ bottom: 800, top: 1200 }}diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryFileItem/index.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryFileItem/index.tsxindex d43b96d22d8..f88eb032880 100644--- a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryFileItem/index.tsx+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryFileItem/index.tsx@@ -351,7 +351,7 @@ const MasonryFileItem = memo<MasonryFileItemProps>(fileType,filename: name,id,- knowledgeBaseId,+ libraryId: knowledgeBaseId,sourceType,url,});diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/Skeleton.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/Skeleton.tsxindex 1020474f37a..236ee6f3c19 100644--- a/src/features/ResourceManager/components/Explorer/MasonryView/Skeleton.tsx+++ b/src/features/ResourceManager/components/Explorer/MasonryView/Skeleton.tsx@@ -34,8 +34,11 @@ const MasonryViewSkeleton = memo<MasonrySkeletonProps>(({ columnCount }) => {// Generate varying heights for more natural masonry lookconst heights = [180, 220, 200, 190, 240, 210, 200, 230, 180, 220, 210, 190];- // Calculate number of items based on viewport and column count- const itemCount = Math.min(columnCount * 3, 12);+ // Calculate number of items based on viewport and column count, minimum 6 items+ const itemCount = Math.max(Math.min(columnCount * 3, 12), 6);++ // Calculate opacity gradient from 100% to 20%+ const getOpacity = (index: number) => 1 - (index / (itemCount - 1)) * 0.8;return (<div@@ -50,6 +53,7 @@ const MasonryViewSkeleton = memo<MasonrySkeletonProps>(({ columnCount }) => {key={index}style={{height: heights[index % heights.length],+ opacity: getOpacity(index),}}/>))}diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/index.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/index.tsxindex 2a27266ee00..5830fe16931 100644--- a/src/features/ResourceManager/components/Explorer/MasonryView/index.tsx+++ b/src/features/ResourceManager/components/Explorer/MasonryView/index.tsx@@ -6,12 +6,10 @@ import { cssVar } from 'antd-style';import { type UIEvent, memo, useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { useFolderPath } from '@/app/[variants]/(main)/resource/features/hooks/useFolderPath';-import {- useResourceManagerFetchKnowledgeItems,- useResourceManagerStore,-} from '@/app/[variants]/(main)/resource/features/store';+import { useResourceManagerStore } from '@/app/[variants]/(main)/resource/features/store';import { sortFileList } from '@/app/[variants]/(main)/resource/features/store/selectors';+import { useFileStore } from '@/store/file';+import { type FileListItem } from '@/types/files';import { useMasonryColumnCount } from '../useMasonryColumnCount';import MasonryItemWrapper from './MasonryFileItem/MasonryItemWrapper';@@ -20,8 +18,6 @@ const MasonryView = memo(() => {// Access all state from Resource Manager storeconst [libraryId,- category,- searchQuery,selectedFileIds,setSelectedFileIds,loadMoreKnowledgeItems,@@ -31,8 +27,6 @@ const MasonryView = memo(() => {sortType,] = useResourceManagerStore((s) => [s.libraryId,- s.category,- s.searchQuery,s.selectedFileIds,s.setSelectedFileIds,s.loadMoreKnowledgeItems,@@ -46,16 +40,33 @@ const MasonryView = memo(() => {const columnCount = useMasonryColumnCount();const [isLoadingMore, setIsLoadingMore] = useState(false);- const { currentFolderSlug } = useFolderPath();+ // NEW: Read from resource store instead of fetching independently+ const resourceList = useFileStore((s) => s.resourceList);- // Fetch data with SWR- const { data: rawData } = useResourceManagerFetchKnowledgeItems({- category,- knowledgeBaseId: libraryId,- parentId: currentFolderSlug || null,- q: searchQuery ?? undefined,- showFilesInKnowledgeBase: false,- });+ // Map ResourceItem[] to FileListItem[] for compatibility+ const rawData = resourceList?.map(+ (item): FileListItem => ({+ chunkCount: item.chunkCount ?? null,+ chunkingError: item.chunkingError ?? null,+ chunkingStatus: (item.chunkingStatus as any) ?? null,+ content: item.content,+ createdAt: item.createdAt,+ editorData: item.editorData,+ embeddingError: item.embeddingError ?? null,+ embeddingStatus: (item.embeddingStatus as any) ?? null,+ fileType: item.fileType,+ finishEmbedding: item.finishEmbedding ?? false,+ id: item.id,+ metadata: item.metadata,+ name: item.name,+ parentId: item.parentId,+ size: item.size,+ slug: item.slug,+ sourceType: item.sourceType,+ updatedAt: item.updatedAt,+ url: item.url ?? '',+ }),+ );// Sort data using current sort settingsconst data = sortFileList(rawData, sorter, sortType);diff --git a/src/features/ResourceManager/components/Explorer/MoveToFolderModal.tsx b/src/features/ResourceManager/components/Explorer/MoveToFolderModal.tsxindex 8a78ee0ed9b..a1231255f30 100644--- a/src/features/ResourceManager/components/Explorer/MoveToFolderModal.tsx+++ b/src/features/ResourceManager/components/Explorer/MoveToFolderModal.tsx@@ -11,14 +11,13 @@ import { useFileStore } from '@/store/file';interface MoveToFolderModalProps {fileId: string;- fileType?: string;knowledgeBaseId?: string;onClose: () => void;open: boolean;}const MoveToFolderModal = memo<MoveToFolderModalProps>(- ({ open, onClose, fileId, fileType, knowledgeBaseId }) => {+ ({ open, onClose, fileId, knowledgeBaseId }) => {const { t } = useTranslation('components');const { message } = App.useApp();@@ -29,11 +28,9 @@ const MoveToFolderModal = memo<MoveToFolderModalProps>(const [loadedFolders, setLoadedFolders] = useState<Set<string>>(new Set());const [isCreatingFolder, setIsCreatingFolder] = useState(false);- const [moveFileToFolder, refreshFileList, createFolder, updateDocument] = useFileStore((s) => [- s.moveFileToFolder,- s.refreshFileList,+ const [moveResource, createFolder] = useFileStore((s) => [+ s.moveResource,s.createFolder,- s.updateDocument,]);// Sort items: folders only@@ -226,20 +223,8 @@ const MoveToFolderModal = memo<MoveToFolderModalProps>(const handleMove = async () => {try {- // Detect if item is a document/folder (vs regular file)- const isDocument =- fileType === 'custom/document' || fileType === 'custom/folder';-- if (isDocument) {- // Use updateDocument for Pages and folders- await updateDocument(fileId, { parentId: selectedFolderId });- } else {- // Use moveFileToFolder for regular files- await moveFileToFolder(fileId, selectedFolderId);- }-- // Refresh file list to invalidate SWR cache for both Explorer and Tree- await refreshFileList();+ // Use optimistic moveResource for instant UI update+ await moveResource(fileId, selectedFolderId);// Clear and reload all expanded folders in Tree's module-level cacheif (knowledgeBaseId) {@@ -256,20 +241,8 @@ const MoveToFolderModal = memo<MoveToFolderModalProps>(const handleMoveToRoot = async () => {try {- // Detect if item is a document/folder (vs regular file)- const isDocument =- fileType === 'custom/document' || fileType === 'custom/folder';-- if (isDocument) {- // Use updateDocument for Pages and folders- await updateDocument(fileId, { parentId: null });- } else {- // Use moveFileToFolder for regular files- await moveFileToFolder(fileId, null);- }-- // Refresh file list to invalidate SWR cache for both Explorer and Tree- await refreshFileList();+ // Use optimistic moveResource for instant UI update+ await moveResource(fileId, null);// Clear and reload all expanded folders in Tree's module-level cacheif (knowledgeBaseId) {diff --git a/src/features/ResourceManager/components/Explorer/ToolBar/BatchActionsDropdown.tsx b/src/features/ResourceManager/components/Explorer/ToolBar/BatchActionsDropdown.tsxindex 639fd4c1f90..43e38e5e7b5 100644--- a/src/features/ResourceManager/components/Explorer/ToolBar/BatchActionsDropdown.tsx+++ b/src/features/ResourceManager/components/Explorer/ToolBar/BatchActionsDropdown.tsx@@ -12,7 +12,7 @@ import { useTranslation } from 'react-i18next';import { useResourceManagerStore } from '@/app/[variants]/(main)/resource/features/store';import RepoIcon from '@/components/LibIcon';-import { useKnowledgeBaseStore } from '@/store/knowledgeBase';+import { useKnowledgeBaseStore } from '@/store/library';import ActionIconWithChevron from './ActionIconWithChevron';diff --git a/src/features/ResourceManager/components/Explorer/index.tsx b/src/features/ResourceManager/components/Explorer/index.tsxindex 775522048f2..f6b3a4320cf 100644--- a/src/features/ResourceManager/components/Explorer/index.tsx+++ b/src/features/ResourceManager/components/Explorer/index.tsx@@ -1,15 +1,13 @@'use client';import { Flexbox } from '@lobehub/ui';-import { memo, useEffect } from 'react';+import { memo, useEffect, useMemo } from 'react';import { useFolderPath } from '@/app/[variants]/(main)/resource/features/hooks/useFolderPath';import { useResourceManagerUrlSync } from '@/app/[variants]/(main)/resource/features/hooks/useResourceManagerUrlSync';-import {- useResourceManagerFetchKnowledgeItems,- useResourceManagerStore,-} from '@/app/[variants]/(main)/resource/features/store';+import { useResourceManagerStore } from '@/app/[variants]/(main)/resource/features/store';import { sortFileList } from '@/app/[variants]/(main)/resource/features/store/selectors';+import { useFetchResources, useResourceStore } from '@/store/file/slices/resource/hooks';import EmptyPlaceholder from './EmptyPlaceholder';import Header from './Header';@@ -59,14 +57,53 @@ const ResourceExplorer = memo(() => {// Get folder path for empty state checkconst { currentFolderSlug } = useFolderPath();- // Fetch data with SWR - uses built-in cache for instant category switching- const { data: rawData, isLoading } = useResourceManagerFetchKnowledgeItems({- category,- knowledgeBaseId: libraryId,- parentId: currentFolderSlug || null,- q: searchQuery ?? undefined,- showFilesInKnowledgeBase: false,- });+ // Build query params for SWR+ const queryParams = useMemo(+ () => ({+ // Only use category filter when NOT in a specific library+ // When viewing a library, show all items regardless of category+ category: libraryId ? undefined : category,+ libraryId,+ parentId: currentFolderSlug || null,+ q: searchQuery ?? undefined,+ showFilesInKnowledgeBase: false,+ sortType,+ sorter,+ }),+ [category, libraryId, currentFolderSlug, searchQuery, sortType, sorter],+ );++ // Use SWR for data fetching with automatic caching and revalidation+ const { isLoading, isValidating } = useFetchResources(queryParams);++ // Get resource data from store (updated by SWR hook)+ const { resourceList, queryParams: currentQueryParams } = useResourceStore();++ // Check if we're navigating to a different view (different query params)+ const isNavigating = useMemo(() => {+ if (!currentQueryParams || !queryParams) return false;++ return (+ currentQueryParams.libraryId !== queryParams.libraryId ||+ currentQueryParams.parentId !== queryParams.parentId ||+ currentQueryParams.category !== queryParams.category ||+ currentQueryParams.q !== queryParams.q+ );+ }, [currentQueryParams, queryParams]);++ // Map ResourceItem[] to FileListItem[] for compatibility+ // TODO: Eventually update all consumers to use ResourceItem directly+ const rawData = resourceList?.map((item) => ({+ ...item,+ // Ensure all FileListItem fields are present with proper types+ chunkCount: item.chunkCount ?? null,+ chunkingError: item.chunkingError ?? null,+ chunkingStatus: (item.chunkingStatus ?? null) as any,+ embeddingError: item.embeddingError ?? null,+ embeddingStatus: (item.embeddingStatus ?? null) as any,+ finishEmbedding: item.finishEmbedding ?? false,+ url: item.url ?? '',+ }));// Sort data using current sort settingsconst data = sortFileList(rawData, sorter, sortType);@@ -83,17 +120,20 @@ const ResourceExplorer = memo(() => {}, [category, libraryId, searchQuery, setSelectedFileIds]);// Computed values- const showEmptyStatus = !isLoading && data?.length === 0 && !currentFolderSlug;-const columnCount = useMasonryColumnCount();- // Only show skeleton on INITIAL load or view transitions, not during revalidation- // This allows cached data to show instantly while revalidating in background+ // Show skeleton when:+ // 1. Initial load with no data (isLoading && no data)+ // 2. Navigating to different folder/category (isNavigating && isValidating)+ // 3. View mode transitionsconst showSkeleton =- (isLoading && !data) || // Only show skeleton if truly loading with no cached data+ (isLoading && (!data || data.length >= 5)) ||+ (isNavigating && isValidating) ||(viewMode === 'list' && isTransitioning) ||(viewMode === 'masonry' && (isTransitioning || !isMasonryReady));+ const showEmptyStatus = !isLoading && !isValidating && data?.length === 0 && !currentFolderSlug;+return (<Flexbox height={'100%'}><Header />diff --git a/src/features/ResourceManager/components/Explorer/useCheckTaskStatus.ts b/src/features/ResourceManager/components/Explorer/useCheckTaskStatus.tsindex 91107c9c0e6..a559093d0db 100644--- a/src/features/ResourceManager/components/Explorer/useCheckTaskStatus.ts+++ b/src/features/ResourceManager/components/Explorer/useCheckTaskStatus.ts@@ -2,10 +2,10 @@ import { useEffect } from 'react';import { useFileStore } from '@/store/file';import { AsyncTaskStatus } from '@/types/asyncTask';+import { revalidateResources } from '@/store/file/slices/resource/hooks';import { type FileListItem } from '@/types/files';export const useCheckTaskStatus = (data: FileListItem[] | undefined) => {- const [refreshFileList] = useFileStore((s) => [s.refreshFileList]);const hasProcessingChunkTask = data?.some((item) => item.chunkingStatus === AsyncTaskStatus.Processing,);@@ -15,11 +15,14 @@ export const useCheckTaskStatus = (data: FileListItem[] | undefined) => {const isProcessing = hasProcessingChunkTask || hasProcessingEmbeddingTask;- // every 3s to check if the chunking status is changed+ // Poll every 5s to check if chunking/embedding status has changeduseEffect(() => {if (!isProcessing) return;- const interval = setInterval(refreshFileList, 5000);+ const interval = setInterval(() => {+ // Re-fetch with the same query params used for initial load+ revalidateResources();+ }, 5000);return () => {clearInterval(interval);};diff --git a/src/features/ResourceManager/components/Header/AddButton.tsx b/src/features/ResourceManager/components/Header/AddButton.tsxindex ed9b562536f..8b85628b2af 100644--- a/src/features/ResourceManager/components/Header/AddButton.tsx+++ b/src/features/ResourceManager/components/Header/AddButton.tsx@@ -9,11 +9,11 @@ import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { useResourceManagerStore } from '@/app/[variants]/(main)/resource/features/store';+import { message } from '@/components/AntdStaticMethods';import DragUpload from '@/components/DragUpload';import GuideModal from '@/components/GuideModal';import GuideVideo from '@/components/GuideVideo';import { useFileStore } from '@/store/file';-import { DocumentSourceType } from '@/types/document';import useNotionImport from './hooks/useNotionImport';import useUploadFolder from './hooks/useUploadFolder';@@ -22,9 +22,12 @@ const AddButton = () => {const { t } = useTranslation('file');const pushDockFileList = useFileStore((s) => s.pushDockFileList);const uploadFolderWithStructure = useFileStore((s) => s.uploadFolderWithStructure);- const createFolder = useFileStore((s) => s.createFolder);+ const createResource = useFileStore((s) => s.createResource);+ const createResourceAndSync = useFileStore((s) => s.createResourceAndSync);++ // TODO: Migrate Notion import to use createResource+ // Keep old functions temporarily for components not yet migratedconst createDocument = useFileStore((s) => s.createDocument);- const refreshFileList = useFileStore((s) => s.refreshFileList);const [libraryId, currentFolderId, setCurrentViewItemId, setMode, setPendingRenameItemId] =useResourceManagerStore((s) => [@@ -36,47 +39,64 @@ const AddButton = () => {]);const handleOpenPageEditor = useCallback(async () => {- // Create a new page directly and switch to page view+ // Create a new page with optimistic update - instant UI feedbackconst untitledTitle = t('pageList.untitled');- const newPage = await createDocument({+ const tempId = await createResource({content: '',+ fileType: 'custom/document',knowledgeBaseId: libraryId,parentId: currentFolderId ?? undefined,+ sourceType: 'document',title: untitledTitle,});- // Add to local document map for immediate availability- const newDocumentMap = new Map(useFileStore.getState().localDocumentMap);- newDocumentMap.set(newPage.id, {- content: newPage.content || '',- createdAt: newPage.createdAt ? new Date(newPage.createdAt) : new Date(),- editorData:- typeof newPage.editorData === 'string'- ? JSON.parse(newPage.editorData)- : newPage.editorData || null,- fileType: 'custom/document',- filename: newPage.title || untitledTitle,- id: newPage.id,- metadata: newPage.metadata || {},- source: 'document',- sourceType: DocumentSourceType.EDITOR,- title: newPage.title || untitledTitle,- totalCharCount: newPage.content?.length || 0,- totalLineCount: 0,- updatedAt: newPage.updatedAt ? new Date(newPage.updatedAt) : new Date(),- });- useFileStore.setState({ localDocumentMap: newDocumentMap });-- // Switch to page view mode- setCurrentViewItemId(newPage.id);+ // Switch to page view mode immediately (temp ID works)+ setCurrentViewItemId(tempId);setMode('page');- }, [createDocument, currentFolderId, libraryId, setCurrentViewItemId, setMode, t]);+ }, [createResource, currentFolderId, libraryId, setCurrentViewItemId, setMode, t]);const handleCreateFolder = useCallback(async () => {- const folderId = await createFolder('Untitled', currentFolderId ?? undefined, libraryId);- // Trigger auto-rename- setPendingRenameItemId(folderId);- }, [createFolder, currentFolderId, libraryId, setPendingRenameItemId]);+ // Create folder and wait for sync to complete before triggering rename+ try {+ // Get current resource list to check for duplicate folder names+ const resourceList = useFileStore.getState().resourceList || [];++ // Filter for folders at the same level+ const foldersAtSameLevel = resourceList.filter(+ (item) =>+ item.fileType === 'custom/folder' &&+ (item.parentId ?? null) === (currentFolderId ?? null),+ );++ // Generate unique folder name+ const baseName = 'Untitled';+ const existingNames = new Set(foldersAtSameLevel.map((folder) => folder.name));++ let uniqueName = baseName;+ let counter = 1;++ while (existingNames.has(uniqueName)) {+ uniqueName = `${baseName} ${counter}`;+ counter++;+ }++ // Wait for sync to complete to get the real ID+ const realId = await createResourceAndSync({+ content: '',+ fileType: 'custom/folder',+ knowledgeBaseId: libraryId,+ parentId: currentFolderId ?? undefined,+ sourceType: 'document',+ title: uniqueName,+ });++ // Trigger auto-rename with the real ID (after sync completes)+ setPendingRenameItemId(realId);+ } catch (error) {+ message.error(t('header.actions.createFolderError'));+ console.error('Failed to create folder:', error);+ }+ }, [createResourceAndSync, currentFolderId, libraryId, setPendingRenameItemId, t]);const {handleCloseNotionGuide,@@ -89,7 +109,10 @@ const AddButton = () => {createDocument,currentFolderId,libraryId,- refreshFileList,+ refetchResources: async () => {+ const { revalidateResources } = await import('@/store/file/slices/resource/hooks');+ await revalidateResources();+ },t,});diff --git a/src/features/ResourceManager/components/Header/hooks/useNotionImport.ts b/src/features/ResourceManager/components/Header/hooks/useNotionImport.tsindex abc97f86b35..c32818bdf67 100644--- a/src/features/ResourceManager/components/Header/hooks/useNotionImport.ts+++ b/src/features/ResourceManager/components/Header/hooks/useNotionImport.ts@@ -11,7 +11,7 @@ interface UseNotionImportOptions {createDocument: DocumentAction['createDocument'];currentFolderId?: string | null;libraryId?: string | null;- refreshFileList: () => Promise<void>;+ refetchResources: () => Promise<void>;t: TFunction<'file'>;}@@ -19,7 +19,7 @@ const useNotionImport = ({createDocument,currentFolderId,libraryId,- refreshFileList,+ refetchResources,t,}: UseNotionImportOptions) => {const notionInputRef = useRef<HTMLInputElement>(null);@@ -171,8 +171,8 @@ const useNotionImport = ({);}- // Refresh file list to show imported documents- await refreshFileList();+ // Refetch resources to show imported documents+ await refetchResources();} catch (error) {console.error('Failed to import Notion export:', error);const { message } = await import('antd');@@ -182,7 +182,7 @@ const useNotionImport = ({// Reset input to allow re-uploadingevent.target.value = '';},- [createDocument, currentFolderId, libraryId, refreshFileList, t],+ [createDocument, currentFolderId, libraryId, refetchResources, t],);return {diff --git a/src/features/ResourceManager/components/Tree/TreeSkeleton.tsx b/src/features/ResourceManager/components/Tree/TreeSkeleton.tsxindex c076662533d..10cc985f44a 100644--- a/src/features/ResourceManager/components/Tree/TreeSkeleton.tsx+++ b/src/features/ResourceManager/components/Tree/TreeSkeleton.tsx@@ -17,9 +17,13 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,}));-const TreeSkeletonItem = memo(() => {+interface TreeSkeletonItemProps {+ opacity?: number;+}++const TreeSkeletonItem = memo<TreeSkeletonItemProps>(({ opacity = 1 }) => {return (- <Flexbox className={styles.container} horizontal>+ <Flexbox className={styles.container} horizontal style={{ opacity }}><Skeleton.Buttonactivesize={'small'}@@ -43,13 +47,19 @@ const TreeSkeletonItem = memo(() => {TreeSkeletonItem.displayName = 'TreeSkeletonItem';-const TreeSkeleton = memo(() => (- <Flexbox gap={2}>- {Array.from({ length: 8 }).map((_, i) => (- <TreeSkeletonItem key={i} />- ))}- </Flexbox>-));+const TreeSkeleton = memo(() => {+ const count = 6;+ // Calculate opacity gradient from 100% to 20%+ const getOpacity = (index: number) => 1 - (index / (count - 1)) * 0.8;++ return (+ <Flexbox gap={2}>+ {Array.from({ length: count }).map((_, i) => (+ <TreeSkeletonItem key={i} opacity={getOpacity(i)} />+ ))}+ </Flexbox>+ );+});TreeSkeleton.displayName = 'TreeSkeleton';diff --git a/src/features/ResourceManager/components/Tree/index.tsx b/src/features/ResourceManager/components/Tree/index.tsxindex 7a8dd301ae7..644a4ecf4ae 100644--- a/src/features/ResourceManager/components/Tree/index.tsx+++ b/src/features/ResourceManager/components/Tree/index.tsx@@ -20,6 +20,7 @@ import { useResourceManagerStore } from '@/app/[variants]/(main)/resource/featurimport FileIcon from '@/components/FileIcon';import { fileService } from '@/services/file';import { useFileStore } from '@/store/file';+import type { ResourceItem } from '@/types/resource';import { useFileItemDropdown } from '../Explorer/ItemDropdown/useFileItemDropdown';import TreeSkeleton from './TreeSkeleton';@@ -35,6 +36,17 @@ const treeState = new Map<}>();+const TREE_REFRESH_EVENT = 'resource-tree-refresh';++const emitTreeRefresh = (knowledgeBaseId: string) => {+ if (typeof window === 'undefined') return;+ window.dispatchEvent(+ new CustomEvent(TREE_REFRESH_EVENT, {+ detail: { knowledgeBaseId },+ }),+ );+};+const getTreeState = (knowledgeBaseId: string) => {if (!treeState.has(knowledgeBaseId)) {treeState.set(knowledgeBaseId, {@@ -56,6 +68,47 @@ export const clearTreeFolderCache = async (knowledgeBaseId: string) => {const state = treeState.get(knowledgeBaseId);if (!state) return;+ const { resourceList } = useFileStore.getState();++ const resolveParentId = (key: string | null | undefined) => {+ if (!key) return null;+ // Prefer id match+ const byId = resourceList.find(+ (item) => item.knowledgeBaseId === knowledgeBaseId && item.id === key,+ );+ if (byId) return byId.id;+ // Fallback to slug match+ const bySlug = resourceList.find(+ (item) => item.knowledgeBaseId === knowledgeBaseId && item.slug === key,+ );+ return bySlug?.id ?? key;+ };++ const buildChildrenFromStore = (parentKey: string | null) => {+ const parentId = resolveParentId(parentKey);+ return resourceList+ .filter(+ (item) =>+ item.knowledgeBaseId === knowledgeBaseId &&+ (item.parentId ?? null) === (parentId ?? null),+ )+ .map<ResourceItem>((item) => item)+ .map((item) => ({+ fileType: item.fileType,+ id: item.id,+ isFolder: item.fileType === 'custom/folder',+ name: item.name,+ slug: item.slug,+ sourceType: item.sourceType,+ url: item.url || '',+ }))+ .sort((a, b) => {+ if (a.isFolder && !b.isFolder) return -1;+ if (!a.isFolder && b.isFolder) return 1;+ return a.name.localeCompare(b.name);+ });+ };+// Get list of all currently expanded folders before clearingconst expandedFoldersList = Array.from(state.expandedFolders);@@ -65,9 +118,16 @@ export const clearTreeFolderCache = async (knowledgeBaseId: string) => {// Reload each expanded folderfor (const folderKey of expandedFoldersList) {+ // Prefer local store (explorer data) to avoid stale remote state+ const localChildren = buildChildrenFromStore(folderKey);+ if (localChildren.length > 0) {+ state.folderChildrenCache.set(folderKey, localChildren);+ state.loadedFolders.add(folderKey);+ continue;+ }++ // Fallback to remote fetch if store has no data (e.g., initial load)try {- // The API expects document ID, but folderKey could be slug or ID- // We'll use it as is and let the API handle itconst response = await fileService.getKnowledgeItems({knowledgeBaseId,parentId: folderKey,@@ -92,7 +152,6 @@ export const clearTreeFolderCache = async (knowledgeBaseId: string) => {return a.name.localeCompare(b.name);});- // Update cache using the same key that was used beforestate.folderChildrenCache.set(folderKey, sortedChildren);state.loadedFolders.add(folderKey);}@@ -100,6 +159,33 @@ export const clearTreeFolderCache = async (knowledgeBaseId: string) => {console.error(`Failed to reload folder ${folderKey}:`, error);}}++ // Revalidate SWR caches for root and expanded folders to keep list and tree in sync+ try {+ const { mutate } = await import('swr');+ const revalidateFolder = (parentId: string | null) =>+ mutate(+ [+ 'useFetchKnowledgeItems',+ {+ knowledgeBaseId,+ parentId,+ showFilesInKnowledgeBase: false,+ },+ ],+ undefined,+ { revalidate: true },+ );++ await Promise.all([+ revalidateFolder(null),+ ...expandedFoldersList.map((folderKey) => revalidateFolder(folderKey)),+ ]);+ } catch (error) {+ console.error('Failed to revalidate tree SWR cache:', error);+ }++ emitTreeRefresh(knowledgeBaseId);};const styles = createStaticStyles(({ css, cssVar }) => ({@@ -201,13 +287,16 @@ const FileTreeRow = memo<{try {await renameFolder(item.id, renamingValue.trim());+ if (libraryId) {+ await clearTreeFolderCache(libraryId);+ }message.success('Renamed successfully');setIsRenaming(false);} catch (error) {console.error('Rename error:', error);message.error('Rename failed');}- }, [item.id, item.name, renamingValue, renameFolder, message]);+ }, [item.id, item.name, libraryId, renamingValue, renameFolder, message]);const handleRenameCancel = useCallback(() => {setIsRenaming(false);@@ -218,7 +307,7 @@ const FileTreeRow = memo<{fileType: item.fileType,filename: item.name,id: item.id,- knowledgeBaseId: libraryId,+ libraryId,onRenameStart: item.isFolder ? handleRenameStart : undefined,sourceType: item.sourceType,url: item.url,@@ -659,6 +748,22 @@ const FileTree = memo(() => {parentFolderKeyRef.current = null;}, [libraryId]);+ // Listen for external tree refresh events (triggered when cache is cleared)+ React.useEffect(() => {+ if (typeof window === 'undefined') return;++ const handleTreeRefresh = (event: Event) => {+ const detail = (event as CustomEvent<{ knowledgeBaseId?: string }>).detail;+ if (detail?.knowledgeBaseId && libraryId && detail.knowledgeBaseId !== libraryId) return;+ forceUpdate();+ };++ window.addEventListener(TREE_REFRESH_EVENT, handleTreeRefresh);+ return () => {+ window.removeEventListener(TREE_REFRESH_EVENT, handleTreeRefresh);+ };+ }, [libraryId, forceUpdate]);+// Auto-expand folders when navigating to a folder in ExplorerReact.useEffect(() => {if (!folderBreadcrumb || folderBreadcrumb.length === 0) return;diff --git a/src/features/ResourceManager/components/UploadDock/index.tsx b/src/features/ResourceManager/components/UploadDock/index.tsxindex 0aa73c3098c..8f2d6103961 100644--- a/src/features/ResourceManager/components/UploadDock/index.tsx+++ b/src/features/ResourceManager/components/UploadDock/index.tsx@@ -50,10 +50,11 @@ const styles = createStaticStyles(({ css }) => {const UploadDock = memo(() => {const { t } = useTranslation('file');- const [expand, setExpand] = useState(true);const [show, setShow] = useState(true);const dispatchDockFileList = useFileStore((s) => s.dispatchDockFileList);+ const expand = useFileStore((s) => s.uploadDockExpanded);+ const setExpand = useFileStore((s) => s.setUploadDockExpanded);const totalUploadingProgress = useFileStore(fileManagerSelectors.overviewUploadingProgress);const fileList = useFileStore(fileManagerSelectors.dockFileList, isEqual);const overviewUploadingStatus = useFileStore(diff --git a/src/features/ResourceManager/constants.ts b/src/features/ResourceManager/constants.tsnew file mode 100644index 00000000000..f95e6d81255--- /dev/null+++ b/src/features/ResourceManager/constants.ts@@ -0,0 +1,3 @@+const PAGE_FILE_TYPE = 'custom/document';++export { PAGE_FILE_TYPE };diff --git a/src/locales/default/file.ts b/src/locales/default/file.tsindex 63e9f2187ff..79a963c8ff4 100644--- a/src/locales/default/file.ts+++ b/src/locales/default/file.ts@@ -18,6 +18,8 @@ export default {'empty': 'No files or folders have been uploaded yet.','header.actions.builtInBlockList.filtered': '{{ignored}} files filtered (out of {{total}} total)','header.actions.connect': 'Connect...',+ 'header.actions.createFolderError': 'Failed to create folder',+ 'header.actions.creatingFolder': 'Creating folder...','header.actions.gitignore.apply': 'Apply Rules','header.actions.gitignore.cancel': 'Ignore Rules','header.actions.gitignore.content':diff --git a/src/services/file/index.ts b/src/services/file/index.tsindex 742f895f3f7..9cb4c048d3a 100644--- a/src/services/file/index.ts+++ b/src/services/file/index.ts@@ -2,6 +2,7 @@ import { lambdaClient } from '@/libs/trpc/client';import {type CheckFileHashResult,type FileItem,+ type FileListItem,type QueryFileListParams,type QueryFileListSchemaType,type UploadFileParams,@@ -58,8 +59,40 @@ export class FileService {};// V2.0 Migrate from getFileItem to getKnowledgeItem+ // This method handles both files (file_ prefix) and documents (docs_ prefix)getKnowledgeItem = async (id: string) => {- return lambdaClient.file.getFileItemById.query({ id });+ // Detect type based on ID prefix+ if (id.startsWith('docs_')) {+ // Document (including folders) - use document endpoint+ const doc = await lambdaClient.document.getDocumentById.query({ id });+ if (!doc) return null;++ // Convert document to FileListItem format+ return {+ chunkCount: null,+ chunkingError: null,+ chunkingStatus: null,+ content: doc.content,+ createdAt: doc.createdAt ? new Date(doc.createdAt) : new Date(),+ editorData: doc.editorData,+ embeddingError: null,+ embeddingStatus: null,+ fileType: doc.fileType || 'custom/document',+ finishEmbedding: false,+ id: doc.id,+ metadata: doc.metadata,+ name: doc.title || doc.filename || 'Untitled',+ parentId: doc.parentId,+ size: doc.totalCharCount || 0,+ slug: doc.slug,+ sourceType: 'document',+ updatedAt: doc.updatedAt ? new Date(doc.updatedAt) : new Date(),+ url: doc.source || '',+ } as FileListItem;+ } else {+ // File - use dedicated file endpoint+ return lambdaClient.file.getFileItemById.query({ id });+ }};getFolderBreadcrumb = async (slug: string) => {diff --git a/src/services/resource/index.ts b/src/services/resource/index.tsnew file mode 100644index 00000000000..f420d7a4ba6--- /dev/null+++ b/src/services/resource/index.ts@@ -0,0 +1,249 @@+import type { FileListItem } from '@/types/files';+import type {+ CreateResourceParams,+ ResourceItem,+ ResourceQueryParams,+ UpdateResourceParams,+} from '@/types/resource';++import { type CreateDocumentParams, documentService } from '../document';+import { fileService } from '../file';++/**+ * Map FileListItem to ResourceItem+ */+const mapToResourceItem = (item: FileListItem): ResourceItem => {+ return {+ chunkCount: item.chunkCount,+ chunkTaskId: item.chunkingStatus ? 'placeholder' : null,+ chunkingError: item.chunkingError,+ chunkingStatus: item.chunkingStatus,+ // Document-specific fields+ content: item.content,++ createdAt: item.createdAt,++ editorData: item.editorData,++ embeddingError: item.embeddingError,++ embeddingStatus: item.embeddingStatus,++ embeddingTaskId: item.embeddingStatus ? 'placeholder' : null,++ fileType: item.fileType,++ finishEmbedding: item.finishEmbedding,++ id: item.id,++ // Metadata+ metadata: item.metadata || undefined,++ name: item.name,++ parentId: item.parentId,++ size: item.size,++ slug: item.slug,++ sourceType: item.sourceType as 'file' | 'document',++ updatedAt: item.updatedAt,++ // File-specific fields+ url: item.url,+ };+};++/**+ * ResourceService - Unified service for both files and documents+ * Provides a thin wrapper over FileService and DocumentService+ * Used by ResourceManager for optimistic updates+ */+export class ResourceService {+ /**+ * Query resources (unified files + documents)+ * Uses KnowledgeRepo UNION ALL query+ */+ async queryResources(params: ResourceQueryParams): Promise<{+ hasMore: boolean;+ items: ResourceItem[];+ total?: number;+ }> {+ // Map frontend parameter names to backend parameter names+ const backendParams = {+ ...params,+ knowledgeBaseId: params.libraryId, // Map libraryId to knowledgeBaseId+ libraryId: undefined, // Remove the frontend-specific parameter+ };++ const response = await fileService.getKnowledgeItems(backendParams);++ return {+ hasMore: response.hasMore,+ items: response.items.map(mapToResourceItem),+ total: 'total' in response ? (response.total as number) : undefined,+ };+ }++ /**+ * Get a single resource by ID+ */+ async getResource(id: string): Promise<ResourceItem | undefined> {+ const item = await fileService.getKnowledgeItem(id);+ return item ? mapToResourceItem(item) : undefined;+ }++ /**+ * Create a new resource (file or document)+ */+ async createResource(params: CreateResourceParams): Promise<ResourceItem> {+ if (params.sourceType === 'file') {+ // Create file+ const result = await fileService.createFile(+ {+ fileType: params.fileType,+ name: params.name,+ parentId: params.parentId,+ size: params.size,+ url: params.url,+ },+ params.knowledgeBaseId,+ );++ // Fetch the created file to get full details+ const created = await fileService.getKnowledgeItem(result.id);+ if (!created) throw new Error('Failed to fetch created file');++ return mapToResourceItem(created);+ } else {+ // Create document+ const documentParams: CreateDocumentParams = {+ content: params.content || '',+ editorData: JSON.stringify(params.editorData || {}),+ fileType: params.fileType,+ knowledgeBaseId: params.knowledgeBaseId,+ metadata: params.metadata,+ parentId: params.parentId,+ slug: params.slug,+ title: params.title,+ };++ const created = await documentService.createDocument(documentParams);++ // Map to ResourceItem+ return {+ content: created.content,+ createdAt: created.createdAt ? new Date(created.createdAt) : new Date(),+ editorData:+ typeof created.editorData === 'string'+ ? JSON.parse(created.editorData)+ : created.editorData,+ fileType: created.fileType || 'custom/document',+ id: created.id,+ metadata: created.metadata || undefined,+ name: created.title || 'Untitled',+ parentId: created.parentId,+ size: created.totalCharCount || 0,+ slug: created.slug || undefined,+ sourceType: 'document',+ title: created.title || undefined,+ updatedAt: created.updatedAt ? new Date(created.updatedAt) : new Date(),+ url: created.source || '',+ };+ }+ }++ /**+ * Update a resource+ */+ async updateResource(id: string, updates: UpdateResourceParams): Promise<ResourceItem> {+ // Check if this is a file or document by fetching it first+ const existing = await this.getResource(id);+ if (!existing) throw new Error('Resource not found');++ if (existing.sourceType === 'file') {+ // Update file (currently only supports parentId)+ if (updates.parentId !== undefined) {+ await fileService.updateFile(id, { parentId: updates.parentId });+ }++ // Fetch updated file+ const updated = await fileService.getKnowledgeItem(id);+ if (!updated) throw new Error('Failed to fetch updated file');++ return mapToResourceItem(updated);+ } else {+ // Update document+ await documentService.updateDocument({+ content: updates.content,+ editorData: updates.editorData ? JSON.stringify(updates.editorData) : undefined,+ id,+ metadata: updates.metadata,+ // Keep null as null (for moving to root), don't convert to undefined+ parentId: updates.parentId !== undefined ? updates.parentId : undefined,+ title: updates.title || updates.name,+ });++ // Fetch updated document+ const updated = await fileService.getKnowledgeItem(id);+ if (!updated) throw new Error('Failed to fetch updated document');++ return mapToResourceItem(updated);+ }+ }++ /**+ * Delete a resource+ */+ async deleteResource(id: string): Promise<void> {+ // Check if this is a file or document+ const existing = await this.getResource(id);+ if (!existing) return; // Already deleted++ if (existing.sourceType === 'file') {+ await fileService.removeFile(id);+ } else {+ await documentService.deleteDocument(id);+ }+ }++ /**+ * Batch delete resources+ */+ async deleteResources(ids: string[]): Promise<void> {+ // Separate files and documents+ const fileIds: string[] = [];+ const documentIds: string[] = [];++ await Promise.all(+ ids.map(async (id) => {+ const item = await this.getResource(id);+ if (item) {+ if (item.sourceType === 'file') {+ fileIds.push(id);+ } else {+ documentIds.push(id);+ }+ }+ }),+ );++ // Batch delete+ await Promise.all([+ fileIds.length > 0 ? fileService.removeFiles(fileIds) : Promise.resolve(),+ documentIds.length > 0 ? documentService.deleteDocuments(documentIds) : Promise.resolve(),+ ]);+ }++ /**+ * Move a resource to a different parent folder+ */+ async moveResource(id: string, parentId: string | null): Promise<ResourceItem> {+ return this.updateResource(id, { parentId });+ }+}++export const resourceService = new ResourceService();diff --git a/src/store/file/slices/chat/action.ts b/src/store/file/slices/chat/action.tsindex 8ed0a8bba1f..c60a98b76d7 100644--- a/src/store/file/slices/chat/action.ts+++ b/src/store/file/slices/chat/action.ts@@ -88,7 +88,8 @@ export const createFileSlice: StateCreator<let fileItem: FileListItem | undefined = undefined;try {- fileItem = await fileService.getKnowledgeItem(id);+ const result = await fileService.getKnowledgeItem(id);+ fileItem = result ?? undefined;} catch (e) {console.error('getFileItem Error:', e);continue;diff --git a/src/store/file/slices/document/action.ts b/src/store/file/slices/document/action.tsindex aca5b10d43c..54260d42b46 100644--- a/src/store/file/slices/document/action.ts+++ b/src/store/file/slices/document/action.ts@@ -194,9 +194,9 @@ export const createDocumentSlice: StateCreator<title: name,});- // Refresh file list to show the new folder- // Note: refreshFileList now keeps cache to avoid skeleton flash- await get().refreshFileList();+ // Refetch resource list to show the new folder+ const { revalidateResources } = await import('../resource/hooks');+ await revalidateResources();return folder.id;},@@ -641,7 +641,10 @@ export const createDocumentSlice: StateCreator<parentId: updates.parentId !== undefined ? updates.parentId : undefined,title: updates.title,});- await get().refreshFileList();++ // Refetch resource list to show updated document+ const { revalidateResources } = await import('../resource/hooks');+ await revalidateResources();},updateDocumentOptimistically: async (documentId, updates) => {@@ -697,9 +700,9 @@ export const createDocumentSlice: StateCreator<title: updatedPage.title || updatedPage.filename,});- // After successful sync, refresh file list to get server state- // This will eventually sync back to the map via syncDocumentMapWithServer- await get().refreshFileList();+ // After successful sync, refetch resources to get server state+ const { revalidateResources } = await import('../resource/hooks');+ await revalidateResources();} catch (error) {console.error('[updateDocumentOptimistically] Failed to sync to DB:', error);// On error, revert the optimistic updatediff --git a/src/store/file/slices/fileManager/action.ts b/src/store/file/slices/fileManager/action.tsindex 801288c3fad..1b7482bf96b 100644--- a/src/store/file/slices/fileManager/action.ts+++ b/src/store/file/slices/fileManager/action.ts@@ -45,6 +45,10 @@ export interface FileManageAction {reEmbeddingChunks: (id: string) => Promise<void>;reParseFile: (id: string) => Promise<void>;+ /**+ * @deprecated Use fetchResources(queryParams) from resource slice instead+ * This method is kept for backward compatibility with non-ResourceManager code+ */refreshFileList: () => Promise<void>;removeAllFiles: () => Promise<void>;removeFileItem: (id: string) => Promise<void>;@@ -53,6 +57,7 @@ export interface FileManageAction {setCurrentFolderId: (folderId: string | null | undefined) => void;setPendingRenameItemId: (id: string | null) => void;+ setUploadDockExpanded: (expanded: boolean) => void;toggleEmbeddingIds: (ids: string[], loading?: boolean) => void;toggleParsingIds: (ids: string[], loading?: boolean) => void;@@ -252,7 +257,7 @@ export const createFileManageSlice: StateCreator<{ concurrency: MAX_UPLOAD_FILE_COUNT },);- // Refresh the file list once after all uploads are complete+ // Refresh file list to show newly uploaded filesawait get().refreshFileList();// 5. auto-embed files that support chunking@@ -349,6 +354,10 @@ export const createFileManageSlice: StateCreator<set({ pendingRenameItemId: id }, false, 'setPendingRenameItemId');},+ setUploadDockExpanded: (expanded) => {+ set({ uploadDockExpanded: expanded }, false, 'setUploadDockExpanded');+ },+toggleEmbeddingIds: (ids, loading) => {set((state) => {const nextValue = new Set(state.creatingEmbeddingTaskIds);@@ -534,9 +543,10 @@ export const createFileManageSlice: StateCreator<}),useFetchKnowledgeItem: (id) =>- useClientDataSWR<FileListItem | undefined>(!id ? null : ['useFetchKnowledgeItem', id], () =>- serverFileService.getKnowledgeItem(id!),- ),+ useClientDataSWR<FileListItem | undefined>(!id ? null : ['useFetchKnowledgeItem', id], async () => {+ const response = await serverFileService.getKnowledgeItem(id!);+ return response ?? undefined;+ }),useFetchKnowledgeItems: (params) =>useClientDataSWR<FileListItem[]>([FETCH_ALL_KNOWLEDGE_KEY, params], async () => {diff --git a/src/store/file/slices/fileManager/initialState.ts b/src/store/file/slices/fileManager/initialState.tsindex eff994bdeec..a8b62cd3f78 100644--- a/src/store/file/slices/fileManager/initialState.ts+++ b/src/store/file/slices/fileManager/initialState.ts@@ -12,6 +12,7 @@ export interface FileManagerState {fileListOffset: number;pendingRenameItemId: string | null;queryListParams?: QueryFileListParams;+ uploadDockExpanded: boolean;}export const initialFileManagerState: FileManagerState = {@@ -23,4 +24,5 @@ export const initialFileManagerState: FileManagerState = {fileListHasMore: false,fileListOffset: 0,pendingRenameItemId: null,+ uploadDockExpanded: true,};diff --git a/src/store/file/slices/resource/action.ts b/src/store/file/slices/resource/action.tsnew file mode 100644index 00000000000..9792b8c4c50--- /dev/null+++ b/src/store/file/slices/resource/action.ts@@ -0,0 +1,432 @@+import debug from 'debug';+import type { StateCreator } from 'zustand/vanilla';++import { resourceService } from '@/services/resource';+import type { CreateResourceParams, ResourceItem, UpdateResourceParams } from '@/types/resource';++import type { FileStore } from '../../store';+import { type ResourceState, initialResourceState } from './initialState';+import { ResourceSyncEngine } from './syncEngine';++const log = debug('resource-manager:action');++/**+ * Resource slice actions+ */+export interface ResourceAction {+ /**+ * Clear all resources and reset state+ */+ clearResources: () => void;++ /**+ * Create a new resource with optimistic update+ * Returns temp ID for immediate UI feedback+ */+ createResource: (params: CreateResourceParams) => Promise<string>;++ /**+ * Create a new resource and wait for sync to complete+ * Returns real ID from server (useful for auto-rename after creation)+ */+ createResourceAndSync: (params: CreateResourceParams) => Promise<string>;++ /**+ * Delete a resource with optimistic update+ */+ deleteResource: (id: string) => Promise<void>;++ /**+ * Flush pending sync operations immediately+ */+ flushSync: () => Promise<void>;++ /**+ * Load more resources (pagination)+ */+ loadMoreResources: () => Promise<void>;++ /**+ * Move a resource to a different parent folder+ */+ moveResource: (id: string, parentId: string | null) => Promise<void>;++ /**+ * Retry a failed sync operation+ */+ retrySync: (resourceId: string) => Promise<void>;++ /**+ * Update a resource with optimistic update+ */+ updateResource: (id: string, updates: UpdateResourceParams) => Promise<void>;+}++let syncEngineInstance: ResourceSyncEngine | null = null;++export const createResourceSlice: StateCreator<+ FileStore,+ [['zustand/devtools', never]],+ [],+ ResourceAction & ResourceState+> = (set, get) => {+ // Initialize sync engine (singleton per store instance)+ const getSyncEngine = () => {+ if (!syncEngineInstance) {+ syncEngineInstance = new ResourceSyncEngine(+ () => {+ const state = get();+ return {+ resourceList: state.resourceList || [],+ resourceMap: state.resourceMap || new Map(),+ syncQueue: state.syncQueue || [],+ syncingIds: state.syncingIds || new Set(),+ };+ },+ (partial) => {+ set(partial as any, false, 'syncEngine/update');+ },+ );+ }+ return syncEngineInstance;+ };++ return {+ ...initialResourceState,++ clearResources: () => {+ set(+ {+ hasMore: false,+ offset: 0,+ queryParams: undefined,+ resourceList: [],+ resourceMap: new Map(),+ syncQueue: [],+ total: 0,+ },+ false,+ 'clearResources',+ );+ },++ createResource: async (params) => {+ const tempId = `temp-resource-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;++ // 1. Create optimistic resource+ const optimisticResource: ResourceItem = {+ _optimistic: { isPending: true, retryCount: 0 },+ createdAt: new Date(),+ fileType: params.fileType,+ id: tempId,+ knowledgeBaseId: params.knowledgeBaseId,+ name: 'title' in params ? params.title : params.name,+ parentId: params.parentId,+ size: 'size' in params ? params.size : 0,+ sourceType: params.sourceType,+ updatedAt: new Date(),+ ...(params.sourceType === 'file'+ ? {+ url: 'url' in params ? params.url : '',+ }+ : {+ content: 'content' in params ? params.content : '',+ editorData: 'editorData' in params ? params.editorData : {},+ slug: 'slug' in params ? params.slug : undefined,+ title: 'title' in params ? params.title : 'Untitled',+ }),+ metadata: params.metadata,+ };++ // 2. Update store immediately (UI instant feedback)+ const { resourceMap, resourceList } = get();+ const newMap = new Map(resourceMap);+ newMap.set(tempId, optimisticResource);++ set(+ {+ resourceList: [optimisticResource, ...resourceList],+ resourceMap: newMap,+ },+ false,+ 'createResource/optimistic',+ );++ // 3. Enqueue sync (background)+ const syncEngine = getSyncEngine();+ syncEngine.enqueue({+ id: `sync-${tempId}`,+ payload: params,+ resourceId: tempId,+ retryCount: 0,+ timestamp: new Date(),+ type: 'create',+ });++ return tempId;+ },++ createResourceAndSync: async (params) => {+ const tempId = `temp-resource-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;++ // 1. Create optimistic resource+ const optimisticResource: ResourceItem = {+ _optimistic: { isPending: true, retryCount: 0 },+ createdAt: new Date(),+ fileType: params.fileType,+ id: tempId,+ knowledgeBaseId: params.knowledgeBaseId,+ name: 'title' in params ? params.title : params.name,+ parentId: params.parentId,+ size: 'size' in params ? params.size : 0,+ sourceType: params.sourceType,+ updatedAt: new Date(),+ ...(params.sourceType === 'file'+ ? {+ url: 'url' in params ? params.url : '',+ }+ : {+ content: 'content' in params ? params.content : '',+ editorData: 'editorData' in params ? params.editorData : {},+ slug: 'slug' in params ? params.slug : undefined,+ title: 'title' in params ? params.title : 'Untitled',+ }),+ metadata: params.metadata,+ };++ // 2. Update store immediately (UI instant feedback)+ const { resourceMap, resourceList } = get();+ const newMap = new Map(resourceMap);+ newMap.set(tempId, optimisticResource);++ set(+ {+ resourceList: [optimisticResource, ...resourceList],+ resourceMap: newMap,+ },+ false,+ 'createResourceAndSync/optimistic',+ );++ // 3. Enqueue sync and wait for completion+ const syncEngine = getSyncEngine();+ const realId = await syncEngine.enqueue({+ id: `sync-${tempId}`,+ payload: params,+ resourceId: tempId,+ retryCount: 0,+ timestamp: new Date(),+ type: 'create',+ });++ return (realId as string) || tempId;+ },++ deleteResource: async (id) => {+ // 1. Remove immediately (optimistic)+ const { resourceMap, resourceList } = get();+ const newMap = new Map(resourceMap);+ newMap.delete(id);++ log('deleteResource', id, newMap, resourceList);++ set(+ {+ resourceList: resourceList.filter((r) => r.id !== id),+ resourceMap: newMap,+ },+ false,+ 'deleteResource/optimistic',+ );++ // 2. Enqueue sync (background)+ const syncEngine = getSyncEngine();+ syncEngine.enqueue({+ id: `sync-${id}-${Date.now()}`,+ payload: {},+ resourceId: id,+ retryCount: 0,+ timestamp: new Date(),+ type: 'delete',+ });++ log('enqueue deleteResource', id, syncEngine);+ },++ flushSync: async () => {+ const syncEngine = getSyncEngine();+ await syncEngine.flush();+ },++ loadMoreResources: async () => {+ const { offset, queryParams, hasMore } = get();+ if (!hasMore || !queryParams) return;++ set({ isLoadingMore: true }, false, 'loadMoreResources/start');++ try {+ const { items } = await resourceService.queryResources({+ ...queryParams,+ limit: 50,+ offset,+ });++ // Merge into existing map/list+ const { resourceMap, resourceList } = get();+ const newMap = new Map(resourceMap);+ items.forEach((item) => newMap.set(item.id, item));++ set(+ {+ hasMore: items.length === 50,+ isLoadingMore: false,+ offset: offset + items.length,+ resourceList: [...resourceList, ...items],+ resourceMap: newMap,+ },+ false,+ 'loadMoreResources/success',+ );+ } catch (error) {+ set({ isLoadingMore: false }, false, 'loadMoreResources/error');+ throw error;+ }+ },++ moveResource: async (id, parentId) => {+ // 1. Optimistically remove from current view (it's moving away)+ const { resourceMap, resourceList } = get();+ const existing = resourceMap.get(id);++ if (!existing) {+ console.warn(`Resource ${id} not found for move`);+ return;+ }++ // Remove from list and map immediately+ const newMap = new Map(resourceMap);+ newMap.delete(id);++ set(+ {+ resourceList: resourceList.filter((r) => r.id !== id),+ resourceMap: newMap,+ },+ false,+ 'moveResource/optimistic',+ );++ // 2. Enqueue move operation (background sync) and wait for it to complete+ const syncEngine = getSyncEngine();+ return syncEngine.enqueue({+ id: `sync-move-${id}-${Date.now()}`,+ payload: { parentId },+ resourceId: id,+ retryCount: 0,+ timestamp: new Date(),+ type: 'move',+ });+ },++ retrySync: async (resourceId) => {+ // Find the resource and re-enqueue if it has an error+ const { resourceMap } = get();+ const resource = resourceMap.get(resourceId);++ if (resource?._optimistic?.error) {+ // Clear error state+ const updated = {+ ...resource,+ _optimistic: {+ isPending: true,+ retryCount: 0,+ },+ };++ const newMap = new Map(resourceMap);+ newMap.set(resourceId, updated);++ const { resourceList } = get();+ const listIndex = resourceList.findIndex((r) => r.id === resourceId);+ const newList = [...resourceList];+ if (listIndex >= 0) {+ newList[listIndex] = updated;+ }++ set(+ {+ resourceList: newList,+ resourceMap: newMap,+ },+ false,+ 'retrySync',+ );++ // Re-enqueue the operation+ // Note: We need to reconstruct the original operation+ // For now, we'll just try an update operation+ const syncEngine = getSyncEngine();+ syncEngine.enqueue({+ id: `sync-retry-${resourceId}-${Date.now()}`,+ payload: {}, // Empty update to trigger re-sync+ resourceId,+ retryCount: 0,+ timestamp: new Date(),+ type: 'update',+ });+ }+ },++ updateResource: async (id, updates) => {+ // 1. Apply updates immediately (optimistic)+ const { resourceMap, resourceList } = get();+ const existing = resourceMap.get(id);++ if (!existing) {+ console.warn(`Resource ${id} not found for update`);+ return;+ }++ log('updateResource', id, existing, updates);++ const updated: ResourceItem = {+ ...existing,+ ...updates,+ _optimistic: { isPending: true, retryCount: 0 },+ name: updates.name || updates.title || existing.name,+ updatedAt: new Date(),+ };++ const newMap = new Map(resourceMap);+ newMap.set(id, updated);++ const listIndex = resourceList.findIndex((r) => r.id === id);+ const newList = [...resourceList];+ if (listIndex >= 0) {+ newList[listIndex] = updated;+ }++ set(+ {+ resourceList: newList,+ resourceMap: newMap,+ },+ false,+ 'updateResource/optimistic',+ );++ // 2. Enqueue sync (background)+ const syncEngine = getSyncEngine();+ syncEngine.enqueue({+ id: `sync-${id}-${Date.now()}`,+ payload: updates,+ resourceId: id,+ retryCount: 0,+ timestamp: new Date(),+ type: 'update',+ });++ log('enqueue updateResource', id, syncEngine);+ },+ };+};diff --git a/src/store/file/slices/resource/hooks.ts b/src/store/file/slices/resource/hooks.tsnew file mode 100644index 00000000000..2bedf49225f--- /dev/null+++ b/src/store/file/slices/resource/hooks.ts@@ -0,0 +1,82 @@+import { isEqual } from 'es-toolkit';+import { shallow } from 'zustand/shallow';++import { mutate, useClientDataSWR } from '@/libs/swr';+import { resourceService } from '@/services/resource';+import type { ResourceQueryParams } from '@/types/resource';++import { useFileStore } from '../../store';++const SWR_KEY_RESOURCES = 'SWR_RESOURCES';++/**+ * Revalidate resources with current or specific query params+ * This can be called from outside React components (e.g., store actions)+ */+export const revalidateResources = async (params?: ResourceQueryParams) => {+ const queryParams = params || useFileStore.getState().queryParams;+ if (queryParams) {+ await mutate([SWR_KEY_RESOURCES, queryParams]);+ }+};++/**+ * Custom SWR hook for fetching resources with caching and revalidation+ */+export const useFetchResources = (params: ResourceQueryParams | null, enable = true) => {+ return useClientDataSWR(+ enable && params ? [SWR_KEY_RESOURCES, params] : null,+ async ([, queryParams]: [string, ResourceQueryParams]) => {+ const response = await resourceService.queryResources({+ ...queryParams,+ limit: queryParams.limit || 50,+ offset: 0,+ });+ return response;+ },+ {+ // SWR configuration for optimal UX+ dedupingInterval: 2000,+ onSuccess: (data: { hasMore: boolean; items: any[]; total?: number }) => {+ const { resourceList, resourceMap } = useFileStore.getState();++ const newResourceMap = new Map(data.items.map((item: any) => [item.id, item]));+ const newResourceList = data.items;++ // Only update store if data actually changed+ if (!isEqual(newResourceList, resourceList) || !isEqual(newResourceMap, resourceMap)) {+ useFileStore.setState(+ {+ hasMore: data.hasMore,+ offset: data.items.length,+ queryParams: params ?? undefined,+ resourceList: newResourceList,+ resourceMap: newResourceMap,+ total: data.total,+ },+ false,+ 'useFetchResources/success',+ );+ }+ },+ revalidateOnFocus: true,+ revalidateOnReconnect: true,+ },+ );+};++/**+ * Hook to access resource store state+ */+export const useResourceStore = () => {+ return useFileStore(+ (s) => ({+ hasMore: s.hasMore,+ queryParams: s.queryParams,+ resourceList: s.resourceList,+ resourceMap: s.resourceMap,+ total: s.total,+ }),+ shallow,+ );+};diff --git a/src/store/file/slices/resource/initialState.ts b/src/store/file/slices/resource/initialState.tsnew file mode 100644index 00000000000..3252b821948--- /dev/null+++ b/src/store/file/slices/resource/initialState.ts@@ -0,0 +1,67 @@+import type { ResourceItem, ResourceQueryParams, SyncOperation } from '@/types/resource';++/**+ * Resource slice state+ */+export interface ResourceState {+ /**+ * Primary store - Map for O(1) lookups+ */+ resourceMap: Map<string, ResourceItem>;++ /**+ * Derived sorted/filtered list (computed from map)+ * Used for rendering in UI+ */+ resourceList: ResourceItem[];++ /**+ * Sync queue (FIFO)+ * Contains pending operations to be synced to server+ */+ syncQueue: SyncOperation[];++ /**+ * Track which resources are currently syncing+ */+ syncingIds: Set<string>;++ /**+ * Pagination state+ */+ hasMore: boolean;+ offset: number;+ total: number;++ /**+ * Current query parameters+ */+ queryParams?: ResourceQueryParams;++ /**+ * Loading states+ */+ isLoadingMore: boolean;+ isSyncing: boolean;++ /**+ * Sync status+ */+ lastSyncTime?: Date;+ syncError?: Error;+}++/**+ * Initial state for resource slice+ */+export const initialResourceState: ResourceState = {+ hasMore: false,+ isLoadingMore: false,+ isSyncing: false,+ offset: 0,+ resourceList: [],+ resourceMap: new Map(),+ syncQueue: [],+ syncingIds: new Set(),+ total: 0,+};diff --git a/src/store/file/slices/resource/syncEngine.ts b/src/store/file/slices/resource/syncEngine.tsnew file mode 100644index 00000000000..051b845667c--- /dev/null+++ b/src/store/file/slices/resource/syncEngine.ts@@ -0,0 +1,326 @@+import { debounce } from 'es-toolkit';+import type { DebouncedFunc } from 'es-toolkit/compat';+import pMap from 'p-map';++import { resourceService } from '@/services/resource';+import type { ResourceItem, SyncOperation } from '@/types/resource';++/**+ * Sync configuration+ */+const SYNC_CONFIG = {+ BACKOFF_MULTIPLIER: 2,+ BATCH_SIZE: 10,+ CONCURRENCY: 3,+ DEBOUNCE_MS: 300, // Wait after last operation+ MAX_RETRIES: 3,+ MAX_WAIT_MS: 2000, // Force sync after 2s+ RETRY_DELAY_MS: 1000,+} as const;++/**+ * State getter/setter interface+ */+interface StateManager {+ getState: () => {+ resourceList: ResourceItem[];+ resourceMap: Map<string, ResourceItem>;+ syncQueue: SyncOperation[];+ syncingIds: Set<string>;+ };+ setState: (partial: {+ resourceList?: ResourceItem[];+ resourceMap?: Map<string, ResourceItem>;+ syncQueue?: SyncOperation[];+ syncingIds?: Set<string>;+ }) => void;+}++/**+ * ResourceSyncEngine - Background sync engine for resource operations+ *+ * Features:+ * - Debounced sync (300ms, max 2s)+ * - Batch processing (10 operations per batch)+ * - Concurrency control (3 parallel requests)+ * - Retry logic with exponential backoff (3 attempts)+ * - Error state marking (no rollback)+ */+export class ResourceSyncEngine {+ private debouncedSync: DebouncedFunc<() => Promise<void>>;+ private stateManager: StateManager;++ constructor(getState: StateManager['getState'], setState: StateManager['setState']) {+ this.stateManager = { getState, setState };++ this.debouncedSync = debounce(() => this.processQueue(), SYNC_CONFIG.DEBOUNCE_MS, {+ edges: ['trailing'],+ }) as DebouncedFunc<() => Promise<void>>;++ // Add maxWait behavior manually since es-toolkit debounce doesn't support it+ let lastExecution = 0;+ const originalSync = this.debouncedSync;++ this.debouncedSync = (() => {+ const now = Date.now();+ if (now - lastExecution >= SYNC_CONFIG.MAX_WAIT_MS) {+ lastExecution = now;+ originalSync.flush?.();+ return originalSync();+ } else {+ return originalSync();+ }+ }) as unknown as DebouncedFunc<() => Promise<void>>;++ this.debouncedSync.flush = originalSync.flush;+ this.debouncedSync.cancel = originalSync.cancel;+ }++ /**+ * Enqueue a sync operation and return a Promise that resolves when it completes+ * For 'create' operations, resolves with the real resource ID+ * For other operations, resolves with void+ */+ enqueue(operation: Omit<SyncOperation, 'resolve' | 'reject'>): Promise<any> {+ return new Promise((resolve, reject) => {+ const { syncQueue } = this.stateManager.getState();+ const operationWithPromise: SyncOperation = {+ ...operation,+ reject,+ resolve,+ };++ this.stateManager.setState({+ syncQueue: [...syncQueue, operationWithPromise],+ });++ // Trigger debounced sync+ this.debouncedSync();+ });+ }++ /**+ * Flush pending operations immediately+ */+ async flush(): Promise<void> {+ this.debouncedSync.flush?.();+ await this.processQueue();+ }++ /**+ * Process the sync queue+ */+ private async processQueue(): Promise<void> {+ const { syncQueue } = this.stateManager.getState();++ if (syncQueue.length === 0) return;++ // Take batch from queue+ const batch = syncQueue.slice(0, SYNC_CONFIG.BATCH_SIZE);+ const remaining = syncQueue.slice(SYNC_CONFIG.BATCH_SIZE);++ // Update queue (remove batch)+ this.stateManager.setState({ syncQueue: remaining });++ // Process batch with concurrency limit+ await pMap(+ batch,+ async (operation) => {+ try {+ await this.processOperation(operation);+ } catch (error) {+ await this.handleOperationError(operation, error as Error);+ }+ },+ { concurrency: SYNC_CONFIG.CONCURRENCY },+ );++ // Continue processing if there are more operations+ if (remaining.length > 0) {+ await this.processQueue();+ }+ }++ /**+ * Process a single sync operation+ */+ private async processOperation(operation: SyncOperation): Promise<void> {+ const { resourceId, type, payload } = operation;++ // Mark as syncing+ const { syncingIds } = this.stateManager.getState();+ syncingIds.add(resourceId);+ this.stateManager.setState({ syncingIds: new Set(syncingIds) });++ try {+ let realId: string | undefined;++ switch (type) {+ case 'create': {+ const created = await resourceService.createResource(payload);+ this.replaceTempResource(resourceId, created);+ realId = created.id;+ break;+ }++ case 'update': {+ const updated = await resourceService.updateResource(resourceId, payload);+ this.updateResourceInStore(updated);+ break;+ }++ case 'delete': {+ await resourceService.deleteResource(resourceId);+ // Resource already removed from store optimistically+ break;+ }++ case 'move': {+ await resourceService.moveResource(resourceId, payload.parentId);+ // Don't update store - resource has already been removed optimistically+ // and should stay removed since it moved to a different location+ break;+ }+ }++ // Clear optimistic state on success+ this.clearOptimisticState(resourceId);++ // Resolve promise for this operation (return real ID for create)+ operation.resolve?.(realId);+ } finally {+ // Unmark as syncing+ const { syncingIds: currentSyncingIds } = this.stateManager.getState();+ currentSyncingIds.delete(resourceId);+ this.stateManager.setState({ syncingIds: new Set(currentSyncingIds) });+ }+ }++ /**+ * Handle operation error+ */+ private async handleOperationError(operation: SyncOperation, error: Error): Promise<void> {+ const { resourceId, retryCount } = operation;++ if (retryCount < SYNC_CONFIG.MAX_RETRIES) {+ // Retry: increment count and re-queue with delay+ const delay = SYNC_CONFIG.RETRY_DELAY_MS * SYNC_CONFIG.BACKOFF_MULTIPLIER ** retryCount;++ setTimeout(() => {+ const { syncQueue } = this.stateManager.getState();+ this.stateManager.setState({+ syncQueue: [+ ...syncQueue,+ {+ ...operation,+ retryCount: retryCount + 1,+ },+ ],+ });+ this.debouncedSync();+ }, delay);+ } else {+ // Max retries reached: mark resource with error state and reject promise+ this.markResourceError(resourceId, error);+ operation.reject?.(error);+ }+ }++ /**+ * Replace temp resource with real resource from server+ */+ private replaceTempResource(tempId: string, realResource: ResourceItem): void {+ const { resourceMap, resourceList } = this.stateManager.getState();++ // Remove temp from map, add real+ resourceMap.delete(tempId);+ resourceMap.set(realResource.id, realResource);++ // Replace in list+ const listIndex = resourceList.findIndex((r) => r.id === tempId);+ if (listIndex >= 0) {+ resourceList[listIndex] = realResource;+ }++ this.stateManager.setState({+ resourceList: [...resourceList],+ resourceMap: new Map(resourceMap),+ });+ }++ /**+ * Update resource in store with fresh data from server+ */+ private updateResourceInStore(resource: ResourceItem): void {+ const { resourceMap, resourceList } = this.stateManager.getState();++ resourceMap.set(resource.id, resource);++ const listIndex = resourceList.findIndex((r) => r.id === resource.id);+ if (listIndex >= 0) {+ resourceList[listIndex] = resource;+ }++ this.stateManager.setState({+ resourceList: [...resourceList],+ resourceMap: new Map(resourceMap),+ });+ }++ /**+ * Clear optimistic state from resource+ */+ private clearOptimisticState(resourceId: string): void {+ const { resourceMap, resourceList } = this.stateManager.getState();+ const resource = resourceMap.get(resourceId);++ if (resource?._optimistic) {+ const updated = { ...resource };+ delete updated._optimistic;++ resourceMap.set(resourceId, updated);++ const listIndex = resourceList.findIndex((r) => r.id === resourceId);+ if (listIndex >= 0) {+ resourceList[listIndex] = updated;+ }++ this.stateManager.setState({+ resourceList: [...resourceList],+ resourceMap: new Map(resourceMap),+ });+ }+ }++ /**+ * Mark resource with error state+ */+ private markResourceError(resourceId: string, error: Error): void {+ const { resourceMap, resourceList } = this.stateManager.getState();+ const resource = resourceMap.get(resourceId);++ if (resource) {+ const updated = {+ ...resource,+ _optimistic: {+ error,+ isPending: false,+ lastSyncAttempt: new Date(),+ retryCount: SYNC_CONFIG.MAX_RETRIES,+ },+ };++ resourceMap.set(resourceId, updated);++ const listIndex = resourceList.findIndex((r) => r.id === resourceId);+ if (listIndex >= 0) {+ resourceList[listIndex] = updated;+ }++ this.stateManager.setState({+ resourceList: [...resourceList],+ resourceMap: new Map(resourceMap),+ });+ }+ }+}diff --git a/src/store/file/store.ts b/src/store/file/store.tsindex 332cc64b4e9..bb8555a720d 100644--- a/src/store/file/store.ts+++ b/src/store/file/store.ts@@ -8,6 +8,8 @@ import { type FileAction, createFileSlice } from './slices/chat';import { type FileChunkAction, createFileChunkSlice } from './slices/chunk';import { type DocumentAction, createDocumentSlice } from './slices/document';import { type FileManageAction, createFileManageSlice } from './slices/fileManager';+import { type ResourceAction, createResourceSlice } from './slices/resource/action';+import { type ResourceState } from './slices/resource/initialState';import { type TTSFileAction, createTTSFileSlice } from './slices/tts';import { type FileUploadAction, createFileUploadSlice } from './slices/upload/action';@@ -19,7 +21,9 @@ export type FileStore = FilesStoreState &TTSFileAction &FileManageAction &FileChunkAction &- FileUploadAction;+ FileUploadAction &+ ResourceAction &+ ResourceState;const createStore: StateCreator<FileStore, [['zustand/devtools', never]]> = (...parameters) => ({...initialState,@@ -29,6 +33,7 @@ const createStore: StateCreator<FileStore, [['zustand/devtools', never]]> = (......createTTSFileSlice(...parameters),...createFileChunkSlice(...parameters),...createFileUploadSlice(...parameters),+ ...createResourceSlice(...parameters),});// =============== Implement useStore ============ //diff --git a/src/store/knowledgeBase/index.ts b/src/store/library/index.tssimilarity index 100%rename from src/store/knowledgeBase/index.tsrename to src/store/library/index.tsdiff --git a/src/store/knowledgeBase/initialState.ts b/src/store/library/initialState.tssimilarity index 67%rename from src/store/knowledgeBase/initialState.tsrename to src/store/library/initialState.tsindex 71ad0ca612a..26100c50072 100644--- a/src/store/knowledgeBase/initialState.ts+++ b/src/store/library/initialState.ts@@ -1,5 +1,5 @@-import { type KnowledgeBaseState, initialKnowledgeBaseState } from '../knowledgeBase/slices/crud';-import { type RAGEvalState, initialDatasetState } from '../knowledgeBase/slices/ragEval';+import { type KnowledgeBaseState, initialKnowledgeBaseState } from '../library/slices/crud';+import { type RAGEvalState, initialDatasetState } from '../library/slices/ragEval';export type KnowledgeBaseStoreState = KnowledgeBaseState & RAGEvalState;diff --git a/src/store/knowledgeBase/selectors.ts b/src/store/library/selectors.tssimilarity index 100%rename from src/store/knowledgeBase/selectors.tsrename to src/store/library/selectors.tsdiff --git a/src/store/knowledgeBase/slices/content/action.test.ts b/src/store/library/slices/content/action.test.tssimilarity index 74%rename from src/store/knowledgeBase/slices/content/action.test.tsrename to src/store/library/slices/content/action.test.tsindex de02aca65b6..177a0aba3da 100644--- a/src/store/knowledgeBase/slices/content/action.test.ts+++ b/src/store/library/slices/content/action.test.ts@@ -2,7 +2,7 @@ import { act, renderHook } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { knowledgeBaseService } from '@/services/knowledgeBase';-import { useFileStore } from '@/store/file';+import * as resourceHooks from '@/store/file/slices/resource/hooks';import { useKnowledgeBaseStore as useStore } from '../../store';@@ -47,10 +47,9 @@ describe('KnowledgeBaseContentActions', () => {},]);- const refreshFileListSpy = vi.fn().mockResolvedValue(undefined);- vi.spyOn(useFileStore, 'getState').mockReturnValue({- refreshFileList: refreshFileListSpy,- } as any);+ const revalidateResourcesSpy = vi+ .spyOn(resourceHooks, 'revalidateResources')+ .mockResolvedValue(undefined);await act(async () => {await result.current.addFilesToKnowledgeBase(knowledgeBaseId, fileIds);@@ -58,8 +57,8 @@ describe('KnowledgeBaseContentActions', () => {expect(addFilesSpy).toHaveBeenCalledWith(knowledgeBaseId, fileIds);expect(addFilesSpy).toHaveBeenCalledTimes(1);- expect(refreshFileListSpy).toHaveBeenCalled();- expect(refreshFileListSpy).toHaveBeenCalledTimes(1);+ expect(revalidateResourcesSpy).toHaveBeenCalled();+ expect(revalidateResourcesSpy).toHaveBeenCalledTimes(1);});it('should handle single file addition', async () => {@@ -79,17 +78,16 @@ describe('KnowledgeBaseContentActions', () => {},]);- const refreshFileListSpy = vi.fn().mockResolvedValue(undefined);- vi.spyOn(useFileStore, 'getState').mockReturnValue({- refreshFileList: refreshFileListSpy,- } as any);+ const revalidateResourcesSpy = vi+ .spyOn(resourceHooks, 'revalidateResources')+ .mockResolvedValue(undefined);await act(async () => {await result.current.addFilesToKnowledgeBase(knowledgeBaseId, fileIds);});expect(addFilesSpy).toHaveBeenCalledWith(knowledgeBaseId, fileIds);- expect(refreshFileListSpy).toHaveBeenCalled();+ expect(revalidateResourcesSpy).toHaveBeenCalled();});it('should handle empty file array', async () => {@@ -102,17 +100,16 @@ describe('KnowledgeBaseContentActions', () => {.spyOn(knowledgeBaseService, 'addFilesToKnowledgeBase').mockResolvedValue([]);- const refreshFileListSpy = vi.fn().mockResolvedValue(undefined);- vi.spyOn(useFileStore, 'getState').mockReturnValue({- refreshFileList: refreshFileListSpy,- } as any);+ const revalidateResourcesSpy = vi+ .spyOn(resourceHooks, 'revalidateResources')+ .mockResolvedValue(undefined);await act(async () => {await result.current.addFilesToKnowledgeBase(knowledgeBaseId, fileIds);});expect(addFilesSpy).toHaveBeenCalledWith(knowledgeBaseId, fileIds);- expect(refreshFileListSpy).toHaveBeenCalled();+ expect(revalidateResourcesSpy).toHaveBeenCalled();});describe('error handling', () => {@@ -125,10 +122,9 @@ describe('KnowledgeBaseContentActions', () => {vi.spyOn(knowledgeBaseService, 'addFilesToKnowledgeBase').mockRejectedValue(serviceError);- const refreshFileListSpy = vi.fn().mockResolvedValue(undefined);- vi.spyOn(useFileStore, 'getState').mockReturnValue({- refreshFileList: refreshFileListSpy,- } as any);+ const revalidateResourcesSpy = vi+ .spyOn(resourceHooks, 'revalidateResources')+ .mockResolvedValue(undefined);await expect(async () => {await act(async () => {@@ -136,7 +132,7 @@ describe('KnowledgeBaseContentActions', () => {});}).rejects.toThrow('Failed to add files to knowledge base');- expect(refreshFileListSpy).not.toHaveBeenCalled();+ expect(revalidateResourcesSpy).not.toHaveBeenCalled();});it('should handle refresh file list errors', async () => {@@ -155,10 +151,7 @@ describe('KnowledgeBaseContentActions', () => {},]);- const refreshFileListSpy = vi.fn().mockRejectedValue(refreshError);- vi.spyOn(useFileStore, 'getState').mockReturnValue({- refreshFileList: refreshFileListSpy,- } as any);+ vi.spyOn(resourceHooks, 'revalidateResources').mockRejectedValue(refreshError);await expect(async () => {await act(async () => {@@ -180,10 +173,9 @@ describe('KnowledgeBaseContentActions', () => {.spyOn(knowledgeBaseService, 'removeFilesFromKnowledgeBase').mockResolvedValue({} as any);- const refreshFileListSpy = vi.fn().mockResolvedValue(undefined);- vi.spyOn(useFileStore, 'getState').mockReturnValue({- refreshFileList: refreshFileListSpy,- } as any);+ const revalidateResourcesSpy = vi+ .spyOn(resourceHooks, 'revalidateResources')+ .mockResolvedValue(undefined);await act(async () => {await result.current.removeFilesFromKnowledgeBase(knowledgeBaseId, fileIds);@@ -191,8 +183,8 @@ describe('KnowledgeBaseContentActions', () => {expect(removeFilesSpy).toHaveBeenCalledWith(knowledgeBaseId, fileIds);expect(removeFilesSpy).toHaveBeenCalledTimes(1);- expect(refreshFileListSpy).toHaveBeenCalled();- expect(refreshFileListSpy).toHaveBeenCalledTimes(1);+ expect(revalidateResourcesSpy).toHaveBeenCalled();+ expect(revalidateResourcesSpy).toHaveBeenCalledTimes(1);});it('should handle single file removal', async () => {@@ -205,17 +197,16 @@ describe('KnowledgeBaseContentActions', () => {.spyOn(knowledgeBaseService, 'removeFilesFromKnowledgeBase').mockResolvedValue({} as any);- const refreshFileListSpy = vi.fn().mockResolvedValue(undefined);- vi.spyOn(useFileStore, 'getState').mockReturnValue({- refreshFileList: refreshFileListSpy,- } as any);+ const revalidateResourcesSpy = vi+ .spyOn(resourceHooks, 'revalidateResources')+ .mockResolvedValue(undefined);await act(async () => {await result.current.removeFilesFromKnowledgeBase(knowledgeBaseId, fileIds);});expect(removeFilesSpy).toHaveBeenCalledWith(knowledgeBaseId, fileIds);- expect(refreshFileListSpy).toHaveBeenCalled();+ expect(revalidateResourcesSpy).toHaveBeenCalled();});it('should handle empty file array', async () => {@@ -228,17 +219,16 @@ describe('KnowledgeBaseContentActions', () => {.spyOn(knowledgeBaseService, 'removeFilesFromKnowledgeBase').mockResolvedValue({} as any);- const refreshFileListSpy = vi.fn().mockResolvedValue(undefined);- vi.spyOn(useFileStore, 'getState').mockReturnValue({- refreshFileList: refreshFileListSpy,- } as any);+ const revalidateResourcesSpy = vi+ .spyOn(resourceHooks, 'revalidateResources')+ .mockResolvedValue(undefined);await act(async () => {await result.current.removeFilesFromKnowledgeBase(knowledgeBaseId, fileIds);});expect(removeFilesSpy).toHaveBeenCalledWith(knowledgeBaseId, fileIds);- expect(refreshFileListSpy).toHaveBeenCalled();+ expect(revalidateResourcesSpy).toHaveBeenCalled();});describe('error handling', () => {@@ -253,10 +243,9 @@ describe('KnowledgeBaseContentActions', () => {serviceError,);- const refreshFileListSpy = vi.fn().mockResolvedValue(undefined);- vi.spyOn(useFileStore, 'getState').mockReturnValue({- refreshFileList: refreshFileListSpy,- } as any);+ const revalidateResourcesSpy = vi+ .spyOn(resourceHooks, 'revalidateResources')+ .mockResolvedValue(undefined);await expect(async () => {await act(async () => {@@ -264,7 +253,7 @@ describe('KnowledgeBaseContentActions', () => {});}).rejects.toThrow('Failed to remove files from knowledge base');- expect(refreshFileListSpy).not.toHaveBeenCalled();+ expect(revalidateResourcesSpy).not.toHaveBeenCalled();});it('should handle refresh file list errors', async () => {@@ -276,10 +265,7 @@ describe('KnowledgeBaseContentActions', () => {vi.spyOn(knowledgeBaseService, 'removeFilesFromKnowledgeBase').mockResolvedValue({} as any);- const refreshFileListSpy = vi.fn().mockRejectedValue(refreshError);- vi.spyOn(useFileStore, 'getState').mockReturnValue({- refreshFileList: refreshFileListSpy,- } as any);+ vi.spyOn(resourceHooks, 'revalidateResources').mockRejectedValue(refreshError);await expect(async () => {await act(async () => {diff --git a/src/store/knowledgeBase/slices/content/action.ts b/src/store/library/slices/content/action.tssimilarity index 70%rename from src/store/knowledgeBase/slices/content/action.tsrename to src/store/library/slices/content/action.tsindex da5845b71a8..38ca36f505c 100644--- a/src/store/knowledgeBase/slices/content/action.ts+++ b/src/store/library/slices/content/action.ts@@ -1,8 +1,8 @@import { type StateCreator } from 'zustand/vanilla';import { knowledgeBaseService } from '@/services/knowledgeBase';-import { useFileStore } from '@/store/file';-import { type KnowledgeBaseStore } from '@/store/knowledgeBase/store';+import { revalidateResources } from '@/store/file/slices/resource/hooks';+import { type KnowledgeBaseStore } from '@/store/library/store';export interface KnowledgeBaseContentAction {addFilesToKnowledgeBase: (knowledgeBaseId: string, ids: string[]) => Promise<void>;@@ -17,11 +17,15 @@ export const createContentSlice: StateCreator<> = () => ({addFilesToKnowledgeBase: async (knowledgeBaseId, ids) => {await knowledgeBaseService.addFilesToKnowledgeBase(knowledgeBaseId, ids);- await useFileStore.getState().refreshFileList();++ // Revalidate resource list to show updated KB associations+ await revalidateResources();},removeFilesFromKnowledgeBase: async (knowledgeBaseId, ids) => {await knowledgeBaseService.removeFilesFromKnowledgeBase(knowledgeBaseId, ids);- await useFileStore.getState().refreshFileList();++ // Revalidate resource list to show updated KB associations+ await revalidateResources();},});diff --git a/src/store/knowledgeBase/slices/content/index.ts b/src/store/library/slices/content/index.tssimilarity index 100%rename from src/store/knowledgeBase/slices/content/index.tsrename to src/store/library/slices/content/index.tsdiff --git a/src/store/knowledgeBase/slices/crud/action.test.ts b/src/store/library/slices/crud/action.test.tssimilarity index 100%rename from src/store/knowledgeBase/slices/crud/action.test.tsrename to src/store/library/slices/crud/action.test.tsdiff --git a/src/store/knowledgeBase/slices/crud/action.ts b/src/store/library/slices/crud/action.tssimilarity index 97%rename from src/store/knowledgeBase/slices/crud/action.tsrename to src/store/library/slices/crud/action.tsindex 11fef363a62..f86dea75616 100644--- a/src/store/knowledgeBase/slices/crud/action.ts+++ b/src/store/library/slices/crud/action.ts@@ -3,7 +3,7 @@ import { type StateCreator } from 'zustand/vanilla';import { mutate, useClientDataSWR } from '@/libs/swr';import { knowledgeBaseService } from '@/services/knowledgeBase';-import { type KnowledgeBaseStore } from '@/store/knowledgeBase/store';+import { type KnowledgeBaseStore } from '@/store/library/store';import { type CreateKnowledgeBaseParams, type KnowledgeBaseItem } from '@/types/knowledgeBase';const FETCH_KNOWLEDGE_BASE_LIST_KEY = 'FETCH_KNOWLEDGE_BASE';diff --git a/src/store/knowledgeBase/slices/crud/index.ts b/src/store/library/slices/crud/index.tssimilarity index 100%rename from src/store/knowledgeBase/slices/crud/index.tsrename to src/store/library/slices/crud/index.tsdiff --git a/src/store/knowledgeBase/slices/crud/initialState.ts b/src/store/library/slices/crud/initialState.tssimilarity index 100%rename from src/store/knowledgeBase/slices/crud/initialState.tsrename to src/store/library/slices/crud/initialState.tsdiff --git a/src/store/knowledgeBase/slices/crud/selectors.ts b/src/store/library/slices/crud/selectors.tssimilarity index 83%rename from src/store/knowledgeBase/slices/crud/selectors.tsrename to src/store/library/slices/crud/selectors.tsindex 0300643b158..c6c1686f775 100644--- a/src/store/knowledgeBase/slices/crud/selectors.ts+++ b/src/store/library/slices/crud/selectors.ts@@ -1,4 +1,4 @@-import { type KnowledgeBaseStoreState } from '@/store/knowledgeBase/initialState';+import { type KnowledgeBaseStoreState } from '@/store/library/initialState';const activeKnowledgeBaseId = (s: KnowledgeBaseStoreState) => s.activeKnowledgeBaseId;diff --git a/src/store/knowledgeBase/slices/ragEval/actions/dataset.ts b/src/store/library/slices/ragEval/actions/dataset.tssimilarity index 97%rename from src/store/knowledgeBase/slices/ragEval/actions/dataset.tsrename to src/store/library/slices/ragEval/actions/dataset.tsindex b5cdab0fb94..c09950950f7 100644--- a/src/store/knowledgeBase/slices/ragEval/actions/dataset.ts+++ b/src/store/library/slices/ragEval/actions/dataset.ts@@ -11,7 +11,7 @@ import { type StateCreator } from 'zustand/vanilla';import { notification } from '@/components/AntdStaticMethods';import { mutate, useClientDataSWR } from '@/libs/swr';import { ragEvalService } from '@/services/ragEval';-import { type KnowledgeBaseStore } from '@/store/knowledgeBase/store';+import { type KnowledgeBaseStore } from '@/store/library/store';const FETCH_DATASET_LIST_KEY = 'FETCH_DATASET_LIST';const FETCH_DATASET_RECORD_KEY = 'FETCH_DATASET_RECORD_KEY';diff --git a/src/store/knowledgeBase/slices/ragEval/actions/evaluation.ts b/src/store/library/slices/ragEval/actions/evaluation.tssimilarity index 96%rename from src/store/knowledgeBase/slices/ragEval/actions/evaluation.tsrename to src/store/library/slices/ragEval/actions/evaluation.tsindex 274a6104fa4..afa507a6c84 100644--- a/src/store/knowledgeBase/slices/ragEval/actions/evaluation.ts+++ b/src/store/library/slices/ragEval/actions/evaluation.ts@@ -4,7 +4,7 @@ import { type StateCreator } from 'zustand/vanilla';import { mutate, useClientDataSWR } from '@/libs/swr';import { ragEvalService } from '@/services/ragEval';-import { type KnowledgeBaseStore } from '@/store/knowledgeBase/store';+import { type KnowledgeBaseStore } from '@/store/library/store';const FETCH_EVALUATION_LIST_KEY = 'FETCH_EVALUATION_LIST_KEY';diff --git a/src/store/knowledgeBase/slices/ragEval/actions/index.ts b/src/store/library/slices/ragEval/actions/index.tssimilarity index 88%rename from src/store/knowledgeBase/slices/ragEval/actions/index.tsrename to src/store/library/slices/ragEval/actions/index.tsindex 87895a58268..18b315863c4 100644--- a/src/store/knowledgeBase/slices/ragEval/actions/index.ts+++ b/src/store/library/slices/ragEval/actions/index.ts@@ -1,6 +1,6 @@import { type StateCreator } from 'zustand/vanilla';-import { type KnowledgeBaseStore } from '@/store/knowledgeBase/store';+import { type KnowledgeBaseStore } from '@/store/library/store';import { type RAGEvalDatasetAction, createRagEvalDatasetSlice } from './dataset';import { type RAGEvalEvaluationAction, createRagEvalEvaluationSlice } from './evaluation';diff --git a/src/store/knowledgeBase/slices/ragEval/index.ts b/src/store/library/slices/ragEval/index.tssimilarity index 100%rename from src/store/knowledgeBase/slices/ragEval/index.tsrename to src/store/library/slices/ragEval/index.tsdiff --git a/src/store/knowledgeBase/slices/ragEval/initialState.ts b/src/store/library/slices/ragEval/initialState.tssimilarity index 100%rename from src/store/knowledgeBase/slices/ragEval/initialState.tsrename to src/store/library/slices/ragEval/initialState.tsdiff --git a/src/store/knowledgeBase/store.ts b/src/store/library/store.tssimilarity index 100%rename from src/store/knowledgeBase/store.tsrename to src/store/library/store.tsdiff --git a/src/types/resource.ts b/src/types/resource.tsnew file mode 100644index 00000000000..b97c2aef58b--- /dev/null+++ b/src/types/resource.ts@@ -0,0 +1,133 @@+import type { FilesTabs, SortType } from '@/types/files';++/**+ * Unified resource item that represents both files and documents+ * Used by ResourceManager for optimistic updates and local-first state management+ */+export interface ResourceItem {+ // Optimistic tracking (UI state, not persisted)+ _optimistic?: {+ error?: Error;+ isPending: boolean;+ lastSyncAttempt?: Date;+ retryCount: number;+ };++ chunkCount?: number | null;+ chunkTaskId?: string | null;+ chunkingError?: any | null;+ chunkingStatus?: string | null;++ // Document-specific (optional)+ content?: string | null;+ // Timestamps+ createdAt: Date;++ editorData?: Record<string, any> | null;+ embeddingError?: any | null;++ embeddingStatus?: string | null;+ embeddingTaskId?: string | null;+ fileType: string;+ finishEmbedding?: boolean;+ // Identity+ id: string;+ knowledgeBaseId?: string;+ // Metadata+ metadata?: Record<string, any>;+ // Real ID or temp-resource-{timestamp}-{random}+ // Common fields+ name: string;+ // Hierarchy+ parentId?: string | null;++ // MIME type or custom/folder, custom/document+ size: number;+ slug?: string | null;+ // bytes for files, char count for documents+ sourceType: 'file' | 'document';+ title?: string;++ updatedAt: Date;++ // File-specific (optional)+ url?: string;+}++/**+ * Sync operation queued for background processing+ */+export interface SyncOperation {+ id: string;+ payload: any;+ // Promise resolver for async operations+ resolve?: (value?: any) => void;+ reject?: (reason?: any) => void;+ // Operation ID (sync-{resourceId}-{timestamp})+ resourceId: string;+ retryCount: number;+ timestamp: Date;+ // Resource ID (temp or real)+ type: 'create' | 'update' | 'delete' | 'move';+}++/**+ * Query parameters for fetching resources+ */+export interface ResourceQueryParams {+ category?: FilesTabs;+ libraryId?: string;+ limit?: number;+ offset?: number;+ parentId?: string | null;+ q?: string;+ showFilesInKnowledgeBase?: boolean;+ sortType?: SortType;+ sorter?: 'name' | 'createdAt' | 'size';+}++/**+ * Create operation payload for files+ */+export interface CreateFileParams {+ fileType: string;+ knowledgeBaseId?: string;+ metadata?: Record<string, any>;+ name: string;+ parentId?: string;+ size: number;+ sourceType: 'file';+ url: string;+}++/**+ * Create operation payload for documents+ */+export interface CreateDocumentParams {+ content: string;+ editorData?: Record<string, any>;+ fileType: 'custom/document' | 'custom/folder';+ knowledgeBaseId?: string;+ metadata?: Record<string, any>;+ parentId?: string;+ slug?: string;+ sourceType: 'document';+ title: string;+}++/**+ * Union type for create operations+ */+export type CreateResourceParams = CreateFileParams | CreateDocumentParams;++/**+ * Update operation payload+ */+export interface UpdateResourceParams {+ content?: string;+ editorData?: Record<string, any>;+ metadata?: Record<string, any>;+ name?: string;+ parentId?: string | null;+ title?: string;+}