Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

⚡️ perf(library): keep the library sidebar tree across remounts and reloads (#20853)

Arvin Xu7b4c7eab8ebe
diff --git a/locales/en-US/components.json b/locales/en-US/components.json
index 9fccdff57cb..6a099865b2e 100644
--- a/locales/en-US/components.json
+++ b/locales/en-US/components.json
@@ -34,11 +34,13 @@
"FileManager.actions.confirmDeleteMultiFiles": "You are about to delete the selected {{count}} files. Once deleted, they cannot be recovered. Please confirm your action.",
"FileManager.actions.confirmRemoveFromLibrary": "You're about to remove {{count}} selected file(s) from the Library. They'll still be available in All Files. Confirm to continue.",
"FileManager.actions.copyUrl": "Copy Link",
+ "FileManager.actions.copyUrlError": "Failed to copy the file link",
"FileManager.actions.copyUrlSuccess": "File url copied successfully.",
"FileManager.actions.createChunkingTask": "Preparing...",
"FileManager.actions.deleteAll": "Delete All Items",
"FileManager.actions.deleteAllOwn": "Delete All Items I Created",
"FileManager.actions.deleteSuccess": "File deleted successfully.",
+ "FileManager.actions.downloadError": "Failed to download the file",
"FileManager.actions.downloadPageEmpty": "Failed to download page: no content available",
"FileManager.actions.downloadPageError": "Failed to download page",
"FileManager.actions.downloading": "Downloading file...",
diff --git a/locales/zh-CN/components.json b/locales/zh-CN/components.json
index 40fe53cc9d6..4c1f8971c1b 100644
--- a/locales/zh-CN/components.json
+++ b/locales/zh-CN/components.json
@@ -34,11 +34,13 @@
"FileManager.actions.confirmDeleteMultiFiles": "将删除选中的 {{count}} 个文件,删除后不可恢复。建议确认无误再继续",
"FileManager.actions.confirmRemoveFromLibrary": "您即将从资料库中移除 {{count}} 个已选文件。它们仍可在“所有文件”中访问。请确认以继续。",
"FileManager.actions.copyUrl": "复制链接",
+ "FileManager.actions.copyUrlError": "复制文件链接失败",
"FileManager.actions.copyUrlSuccess": "文件地址复制成功",
"FileManager.actions.createChunkingTask": "准备中…",
"FileManager.actions.deleteAll": "删除全部资源",
"FileManager.actions.deleteAllOwn": "删除我创建的全部资源",
"FileManager.actions.deleteSuccess": "文件删除成功",
+ "FileManager.actions.downloadError": "下载文件失败",
"FileManager.actions.downloadPageEmpty": "下载页面失败:页面没有内容",
"FileManager.actions.downloadPageError": "下载页面失败",
"FileManager.actions.downloading": "文件下载中…",
diff --git a/packages/locales/src/default/components.ts b/packages/locales/src/default/components.ts
index e9d50de0f83..35f03a7343a 100644
--- a/packages/locales/src/default/components.ts
+++ b/packages/locales/src/default/components.ts
@@ -45,11 +45,13 @@ export default {
'FileManager.actions.confirmRemoveFromLibrary':
"You're about to remove {{count}} selected file(s) from the Library. They'll still be available in All Files. Confirm to continue.",
'FileManager.actions.copyUrl': 'Copy Link',
+ 'FileManager.actions.copyUrlError': 'Failed to copy the file link',
'FileManager.actions.copyUrlSuccess': 'File url copied successfully.',
'FileManager.actions.createChunkingTask': 'Preparing...',
'FileManager.actions.deleteSuccess': 'File deleted successfully.',
'FileManager.actions.deleteAll': 'Delete All Items',
'FileManager.actions.deleteAllOwn': 'Delete All Items I Created',
+ 'FileManager.actions.downloadError': 'Failed to download the file',
'FileManager.actions.downloadPageEmpty': 'Failed to download page: no content available',
'FileManager.actions.downloadPageError': 'Failed to download page',
'FileManager.actions.downloading': 'Downloading file...',
diff --git a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsx b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsx
index 53a404368f3..b538d6f5820 100644
--- a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsx
+++ b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsx
@@ -14,7 +14,9 @@ const mocks = vi.hoisted(() => ({
copyToClipboard: vi.fn(async (_text: string) => undefined),
confirmModal: vi.fn(),
deleteResource: vi.fn<() => Promise<void>>(async () => {}),
+ downloadFile: vi.fn(async (_url: string, _filename: string) => undefined),
dropTreeNodes: vi.fn(async () => undefined),
+ getFile: vi.fn(async (_id: string) => ({ url: 'https://storage.example.com/fresh-signed' })),
publishFileToWorkspace: vi.fn(async (_id: string) => undefined),
setFileVisibility: vi.fn(async (_id: string, _visibility: string) => undefined),
refreshFileList: vi.fn(async () => undefined),
@@ -87,6 +89,9 @@ vi.mock('@/store/tree', () => ({
}),
}));
+vi.mock('@/services/file', () => ({ fileService: { getFile: mocks.getFile } }));
+vi.mock('@/utils/client/downloadFile', () => ({ downloadFile: mocks.downloadFile }));
+
const { useFileItemDropdown } = await import('./useFileItemDropdown');
const baseParams = {
@@ -383,3 +388,55 @@ describe('useFileItemDropdown — workspace resource permissions', () => {
);
});
});
+
+/** @example A sidebar row painted from the persisted tree, before its folder refreshed. */
+describe('useFileItemDropdown — row without a stored URL', () => {
+ const click = async (key: string, params: Record<string, unknown> = {}) => {
+ const { result } = renderHook(() =>
+ useFileItemDropdown({ ...baseParams, fileId: 'file-id', url: '', ...params } as any),
+ );
+ const item = result.current.menuItems().find((entry) => entry?.key === key) as any;
+ await item.onClick({ domEvent: { stopPropagation: vi.fn() } });
+ };
+
+ it('copies a freshly resolved URL instead of an empty string', async () => {
+ await click('copyUrl');
+ expect(mocks.getFile).toHaveBeenCalledWith('file-id');
+ expect(mocks.copyToClipboard).toHaveBeenCalledWith('https://storage.example.com/fresh-signed');
+ });
+
+ it('downloads from a freshly resolved URL', async () => {
+ await click('download');
+ expect(mocks.downloadFile).toHaveBeenCalledWith(
+ 'https://storage.example.com/fresh-signed',
+ 'notes.md',
+ );
+ });
+
+ it('closes the loading toast and reports the failure when the URL lookup fails', async () => {
+ const close = vi.fn();
+ const { toast } = await import('@lobehub/ui');
+ vi.mocked(toast.loading).mockReturnValueOnce({ close } as any);
+ mocks.getFile.mockRejectedValueOnce(new Error('offline'));
+
+ await click('download');
+
+ expect(mocks.downloadFile).not.toHaveBeenCalled();
+ expect(close).toHaveBeenCalled();
+ expect(toast.error).toHaveBeenCalledWith('FileManager.actions.downloadError');
+ });
+
+ it('still offers Send to chat platform, which resolves the file by id', () => {
+ renderHook(() => useFileItemDropdown({ ...baseParams, fileId: 'file-id', url: '' } as any));
+ expect(mocks.useSendToMessengerMenuItem.mock.calls.at(-1)![0].enabled).toBe(true);
+ });
+
+ it('uses the row URL without a request when it has one', async () => {
+ await click('download', { url: 'https://storage.example.com/notes.md' });
+ expect(mocks.getFile).not.toHaveBeenCalled();
+ expect(mocks.downloadFile).toHaveBeenCalledWith(
+ 'https://storage.example.com/notes.md',
+ 'notes.md',
+ );
+ });
+});
diff --git a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
index 987579dacb0..eb1b21fe506 100644
--- a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
+++ b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
@@ -29,6 +29,7 @@ import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';
import { useAppOrigin } from '@/hooks/useAppOrigin';
import { usePermission } from '@/hooks/usePermission';
import { documentService } from '@/services/document';
+import { fileService } from '@/services/file';
import { useFileStore } from '@/store/file';
import { useKnowledgeBaseStore } from '@/store/library';
import { useTreeStore } from '@/store/tree';
@@ -155,15 +156,23 @@ export const useFileItemDropdown = ({
(sourceType === DERIVED_DOCUMENT_SOURCE_TYPE || fileType === PAGE_FILE_TYPE);
// Pages/documents have no storage URL to attach, so only real files get the
- // "Send to chat platform" entry. The server resolves the attachment by
+ // "Send to chat platform" entry. It is gated on the file type, not on `url`:
+ // a row restored from the persisted tree has none, and the server needs only
+ // the id. The server resolves the attachment by
// `files.id`, but a file that backs a derived page is listed under the PAGE
// id — always prefer the row's underlying `fileId` when it carries one.
const sendToMessengerItem = useSendToMessengerMenuItem({
- enabled: !isFolder && !isPage && !!url,
+ enabled: !isFolder && !isPage,
file: { fileType, id: fileId ?? id, name: filename, size },
});
const menuItems = useCallback(() => {
+ // A sidebar row restored from the persisted tree carries no storage URL (a
+ // signed link never reaches storage) until its folder refreshes; fetch it on
+ // demand so Copy URL / Download never act on an empty string.
+ const resolveFileUrl = async (): Promise<string> =>
+ url || (await fileService.getFile(fileId ?? id)).url;
+
// Filter out current knowledge base and constrain by visibility scope:
// a private file can only join a private KB, a workspace-public file can
// only join a public KB. Personal-mode files (visibility null/undefined)
@@ -369,13 +378,17 @@ export const useFileItemDropdown = ({
// routes are mounted under `/:workspaceSlug`, so the shared link must
// carry the active slug or recipients land in the personal scope
// where the page does not resolve.
- let urlToCopy = url;
- if (isPage) {
- urlToCopy = `${appOrigin}${buildPagePath(id, activeWorkspaceSlug, libraryId)}`;
- }
+ try {
+ const urlToCopy = isPage
+ ? `${appOrigin}${buildPagePath(id, activeWorkspaceSlug, libraryId)}`
+ : await resolveFileUrl();
- await copyToClipboard(urlToCopy);
- toast.success(t('FileManager.actions.copyUrlSuccess'));
+ await copyToClipboard(urlToCopy);
+ toast.success(t('FileManager.actions.copyUrlSuccess'));
+ } catch (error) {
+ console.error('Failed to copy file url:', error);
+ toast.error(t('FileManager.actions.copyUrlError'));
+ }
},
sfSymbol: 'doc.on.doc',
},
@@ -414,8 +427,14 @@ export const useFileItemDropdown = ({
toast.error(t('FileManager.actions.downloadPageError'));
}
} else {
- // For regular files, download from URL
- await downloadFile(url, filename);
+ // For regular files, download from URL (resolved first for a row
+ // restored without one, which can fail offline or once deleted).
+ try {
+ await downloadFile(await resolveFileUrl(), filename);
+ } catch (error) {
+ console.error('Failed to download file:', error);
+ toast.error(t('FileManager.actions.downloadError'));
+ }
}
downloadingToast.close();
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/index.tsx b/src/features/ResourceManager/components/LibraryHierarchy/index.tsx
index babcecf97e0..25fbd87a702 100644
--- a/src/features/ResourceManager/components/LibraryHierarchy/index.tsx
+++ b/src/features/ResourceManager/components/LibraryHierarchy/index.tsx
@@ -18,22 +18,23 @@ import { HierarchyNode } from './HierarchyNode';
import SearchResults from './SearchResults';
import { resolveHierarchySelectedKey } from './selection';
import TreeSkeleton from './TreeSkeleton';
+import { useInitLibraryTree } from './useInitLibraryTree';
import { buildVisibleNodes } from './visibleNodes';
const LibraryHierarchy = memo(() => {
const { t } = useTranslation('file');
const { currentFolderSlug } = useFolderPath();
- const [libraryId, currentViewItemId, librarySearchQuery] = useResourceManagerStore((s) => [
- s.libraryId,
+ const [currentViewItemId, librarySearchQuery] = useResourceManagerStore((s) => [
s.currentViewItemId,
s.librarySearchQuery,
]);
+ // Effect 1: Library switch → reset + load root (seeded from the persisted tree)
+ const libraryId = useInitLibraryTree();
const children = useTreeStore((s) => s.children);
const expanded = useTreeStore((s) => s.expanded);
const status = useTreeStore((s) => s.status);
const errors = useTreeStore((s) => s.errors);
- const init = useTreeStore((s) => s.init);
const expandAncestors = useTreeStore((s) => s.expandAncestors);
const toggle = useTreeStore((s) => s.toggle);
const loadChildren = useTreeStore((s) => s.loadChildren);
@@ -43,12 +44,6 @@ const LibraryHierarchy = memo(() => {
const useFetchFolderBreadcrumb = useFileStore((s) => s.useFetchFolderBreadcrumb);
const { data: folderChain } = useFetchFolderBreadcrumb(currentFolderSlug);
- // Effect 1: Library switch → reset + load root
- useEffect(() => {
- if (!libraryId) return;
- init(libraryId);
- }, [libraryId, init]);
-
// Effect 2: Folder navigation → expand ancestors once breadcrumb resolves
useEffect(() => {
if (!folderChain?.length) return;
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/useInitLibraryTree.desktop.test.ts b/src/features/ResourceManager/components/LibraryHierarchy/useInitLibraryTree.desktop.test.ts
new file mode 100644
index 00000000000..f9375dbb8b3
--- /dev/null
+++ b/src/features/ResourceManager/components/LibraryHierarchy/useInitLibraryTree.desktop.test.ts
@@ -0,0 +1,63 @@
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useElectronStore } from '@/store/electron';
+
+import { useInitLibraryTree } from './useInitLibraryTree';
+
+const { mockInit, resourceManagerState } = vi.hoisted(() => {
+ const state = {
+ libraryId: undefined as string | undefined,
+ setLibraryId: (id?: string) => {
+ state.libraryId = id;
+ },
+ };
+ return { mockInit: vi.fn(), resourceManagerState: state };
+});
+
+vi.mock(
+ '@/hooks/useActiveRouteParams',
+ async () => await import('@/hooks/useActiveRouteParams.desktop'),
+);
+
+vi.mock('@/store/tree', () => ({
+ useTreeStore: (selector: (s: { init: typeof mockInit }) => unknown) =>
+ selector({ init: mockInit }),
+}));
+
+vi.mock('@/features/ResourceManager/store', () => ({
+ useResourceManagerStore: (selector: (s: typeof resourceManagerState) => unknown) =>
+ selector(resourceManagerState),
+}));
+
+const tab = (id: string, url: string) => ({ id, lastVisited: 0, url });
+
+describe('useInitLibraryTree (desktop)', () => {
+ beforeEach(() => {
+ mockInit.mockReset();
+ resourceManagerState.libraryId = undefined;
+ });
+
+ afterEach(() => {
+ useElectronStore.setState({ activeTabId: null, tabs: [] });
+ });
+
+ it('follows the active tab, not the portal router the sidebar renders under', () => {
+ useElectronStore.setState({
+ activeTabId: 'tab-a',
+ tabs: [tab('tab-a', '/resource/library/kb-a'), tab('tab-b', '/resource/library/kb-b')],
+ });
+
+ const { result } = renderHook(() => useInitLibraryTree());
+ expect(result.current).toBe('kb-a');
+ expect(mockInit).toHaveBeenLastCalledWith('kb-a');
+
+ act(() => {
+ useElectronStore.setState({ activeTabId: 'tab-b' });
+ });
+
+ expect(result.current).toBe('kb-b');
+ expect(mockInit).toHaveBeenLastCalledWith('kb-b');
+ expect(resourceManagerState.libraryId).toBe('kb-b');
+ });
+});
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/useInitLibraryTree.test.ts b/src/features/ResourceManager/components/LibraryHierarchy/useInitLibraryTree.test.ts
new file mode 100644
index 00000000000..eefec139614
--- /dev/null
+++ b/src/features/ResourceManager/components/LibraryHierarchy/useInitLibraryTree.test.ts
@@ -0,0 +1,93 @@
+import { renderHook } from '@testing-library/react';
+import { createElement, type ReactNode, useEffect } from 'react';
+import { MemoryRouter, Route, Routes } from 'react-router';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useInitLibraryTree } from './useInitLibraryTree';
+
+const { mockInit, resourceManagerState } = vi.hoisted(() => {
+ const state = {
+ libraryId: undefined as string | undefined,
+ setLibraryId: (id?: string) => {
+ state.libraryId = id;
+ },
+ };
+ return { mockInit: vi.fn(), resourceManagerState: state };
+});
+
+vi.mock('@/store/tree', () => ({
+ useTreeStore: (selector: (s: { init: typeof mockInit }) => unknown) =>
+ selector({ init: mockInit }),
+}));
+
+vi.mock('@/features/ResourceManager/store', () => ({
+ useResourceManagerStore: (selector: (s: typeof resourceManagerState) => unknown) =>
+ selector(resourceManagerState),
+}));
+
+const routeWrapper =
+ (path: string, pattern = '/resource/library/:id/*') =>
+ ({ children }: { children: ReactNode }) =>
+ createElement(
+ MemoryRouter,
+ { initialEntries: [path] },
+ createElement(Routes, null, createElement(Route, { element: children, path: pattern })),
+ );
+
+describe('useInitLibraryTree', () => {
+ beforeEach(() => {
+ mockInit.mockReset();
+ resourceManagerState.libraryId = undefined;
+ });
+
+ it('initialises the tree from the route before the page syncs the library into the store', () => {
+ const { result } = renderHook(() => useInitLibraryTree(), {
+ wrapper: routeWrapper('/resource/library/kb-1/some-folder'),
+ });
+
+ expect(result.current).toBe('kb-1');
+ expect(mockInit).toHaveBeenCalledWith('kb-1');
+ });
+
+ it('initialises before passive effects, so the seeded tree is in the first painted frame', () => {
+ const order: string[] = [];
+ mockInit.mockImplementation(() => order.push('init'));
+
+ renderHook(
+ () => {
+ useInitLibraryTree();
+ useEffect(() => {
+ order.push('passive effect');
+ }, []);
+ },
+ { wrapper: routeWrapper('/resource/library/kb-1') },
+ );
+
+ expect(order).toEqual(['init', 'passive effect']);
+ });
+
+ it('points the store at the route library before paint, so row actions never target the previous one', () => {
+ // Coming from library A: the page segment that syncs the store has not mounted yet.
+ resourceManagerState.libraryId = 'kb-a';
+ let storeAtInit: string | undefined;
+ mockInit.mockImplementation(() => {
+ storeAtInit = resourceManagerState.libraryId;
+ });
+
+ renderHook(() => useInitLibraryTree(), { wrapper: routeWrapper('/resource/library/kb-b') });
+
+ expect(storeAtInit).toBe('kb-b');
+ expect(resourceManagerState.libraryId).toBe('kb-b');
+ });
+
+ it('falls back to the store outside a library route', () => {
+ resourceManagerState.libraryId = 'kb-2';
+
+ const { result } = renderHook(() => useInitLibraryTree(), {
+ wrapper: routeWrapper('/resource', '/resource'),
+ });
+
+ expect(result.current).toBe('kb-2');
+ expect(mockInit).toHaveBeenCalledWith('kb-2');
+ });
+});
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/useInitLibraryTree.ts b/src/features/ResourceManager/components/LibraryHierarchy/useInitLibraryTree.ts
new file mode 100644
index 00000000000..035666c6ebc
--- /dev/null
+++ b/src/features/ResourceManager/components/LibraryHierarchy/useInitLibraryTree.ts
@@ -0,0 +1,38 @@
+import { useLayoutEffect } from 'react';
+
+import { useResourceManagerStore } from '@/features/ResourceManager/store';
+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';
+import { useTreeStore } from '@/store/tree';
+
+/**
+ * The library the sidebar tree shows, initialised before the first paint.
+ *
+ * The page segment copies the route's library into the ResourceManager store
+ * only once its own (lazy) chunk mounts. The sidebar mounts with the layout, so
+ * it reads the route first: waiting for the store kept the persisted tree behind
+ * a skeleton for as long as the page took to load. It reads the *active* route:
+ * Electron portals the sidebar into the shell's frozen root router, where raw
+ * `useParams` keeps answering with the boot tab's library.
+ *
+ * The same pre-paint effect copies the route's library into the store: the
+ * sidebar's row actions (navigate, create, upload) read it from there, and must
+ * not act on the previous library while this one's cached rows are on screen.
+ *
+ * `init` runs in a layout effect, so the tree it seeds from the persisted
+ * snapshot is already in the first painted frame.
+ */
+export const useInitLibraryTree = (): string | undefined => {
+ const { id: routeLibraryId } = useActiveRouteParams<{ id?: string }>();
+ const storeLibraryId = useResourceManagerStore((s) => s.libraryId);
+ const setLibraryId = useResourceManagerStore((s) => s.setLibraryId);
+ const init = useTreeStore((s) => s.init);
+ const libraryId = routeLibraryId ?? storeLibraryId;
+
+ useLayoutEffect(() => {
+ if (!libraryId) return;
+ if (routeLibraryId) setLibraryId(routeLibraryId);
+ init(libraryId);
+ }, [libraryId, routeLibraryId, init, setLibraryId]);
+
+ return libraryId;
+};
diff --git a/src/features/ResourceManager/store/action.test.ts b/src/features/ResourceManager/store/action.test.ts
index 44d098ff095..fe2e7d13066 100644
--- a/src/features/ResourceManager/store/action.test.ts
+++ b/src/features/ResourceManager/store/action.test.ts
@@ -8,17 +8,27 @@ import { useResourceManagerStore } from '.';
import { initialState } from './initialState';
import { explorerSearchResource } from './projection';
-const { mockDeleteResourcesByQuery, mockDropNodes, mockResolveSelectionIds, mockRevalidateTree } =
- vi.hoisted(() => ({
- mockDeleteResourcesByQuery: vi.fn(),
- mockDropNodes: vi.fn(async () => undefined),
- mockResolveSelectionIds: vi.fn(),
- mockRevalidateTree: vi.fn(async () => undefined),
- }));
+const {
+ mockDeleteResourcesByQuery,
+ mockDropNodes,
+ mockForgetSnapshot,
+ mockResolveSelectionIds,
+ mockRevalidateTree,
+} = vi.hoisted(() => ({
+ mockDeleteResourcesByQuery: vi.fn(),
+ mockDropNodes: vi.fn(async () => undefined),
+ mockForgetSnapshot: vi.fn(),
+ mockResolveSelectionIds: vi.fn(),
+ mockRevalidateTree: vi.fn(async () => undefined),
+}));
vi.mock('@/store/tree', () => ({
useTreeStore: {
- getState: () => ({ dropNodes: mockDropNodes, revalidate: mockRevalidateTree }),
+ getState: () => ({
+ dropNodes: mockDropNodes,
+ forgetSnapshot: mockForgetSnapshot,
+ revalidate: mockRevalidateTree,
+ }),
},
}));
@@ -262,6 +272,8 @@ describe('resource manager store actions', () => {
// Individual ids never reach the client here, so the whole folder is refetched.
expect(mockRevalidateTree).toHaveBeenCalledWith('folder-a');
expect(mockDropNodes).not.toHaveBeenCalled();
+ // A refetch that never lands must not leave the deleted rows in the persisted tree.
+ expect(mockForgetSnapshot).toHaveBeenCalledTimes(1);
});
});
diff --git a/src/features/ResourceManager/store/action.ts b/src/features/ResourceManager/store/action.ts
index 109c2aa2eab..c8232e7900d 100644
--- a/src/features/ResourceManager/store/action.ts
+++ b/src/features/ResourceManager/store/action.ts
@@ -397,6 +397,9 @@ export class ResourceManagerStoreActionImpl {
await fileStore.evictResourceLists();
// The deleted set is only known to the server here, and every row in
// it was a child of the listed folder, so refetch that one folder.
+ // The persisted tree is dropped first: if that refetch never lands,
+ // a reload must not repaint the deleted rows.
+ useTreeStore.getState().forgetSnapshot();
void useTreeStore.getState().revalidate(currentFolderKey);
this.clearSelectAllState();
diff --git a/src/routes/(main)/resource/library/libraryTreeLoader.ts b/src/routes/(main)/resource/library/libraryTreeLoader.ts
new file mode 100644
index 00000000000..d8fc2e98674
--- /dev/null
+++ b/src/routes/(main)/resource/library/libraryTreeLoader.ts
@@ -0,0 +1,19 @@
+import type { LoaderFunctionArgs } from 'react-router';
+
+import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';
+import { useTreeStore } from '@/store/tree';
+
+/**
+ * Seed the library sidebar's persisted tree before the route commits.
+ *
+ * Route loaders run before React paints the new route, so this is the one place
+ * the (async) persisted read can land in time for the tree's first frame;
+ * without it the sidebar paints its skeleton until the in-tree hydrate resolves.
+ */
+export const libraryTreeLoader = async ({ params }: LoaderFunctionArgs): Promise<null> => {
+ if (params.id) {
+ await settleWithin(useTreeStore.getState().preHydrate(params.id), PRE_PAINT_HYDRATE_TIMEOUT);
+ }
+
+ return null;
+};
diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsx
index c2df6209629..3943ce50aa4 100644
--- a/src/spa/router/desktopRouter.shared.tsx
+++ b/src/spa/router/desktopRouter.shared.tsx
@@ -85,6 +85,7 @@ import { agentDocumentListLoader } from '@/spa/router/agentDocumentListLoader';
import { channelDataLoader } from '@/spa/router/channelDataLoader';
import { contextListLoader } from '@/spa/router/contextListLoader';
import { identitiesListLoader } from '@/spa/router/identitiesListLoader';
+import { libraryTreeLoader } from '@/spa/router/libraryTreeLoader';
import { pageListLoader } from '@/spa/router/pageListLoader';
import { preferenceListLoader } from '@/spa/router/preferenceListLoader';
import { NoRouteSkeleton, routeMeta } from '@/spa/router/routeMeta';
@@ -747,6 +748,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
() => import('@/routes/(main)/resource/library/_layout'),
'Desktop > Resource > Library > Layout',
),
+ loader: libraryTreeLoader,
path: 'library/:id',
},
],
diff --git a/src/spa/router/libraryTreeLoader.ts b/src/spa/router/libraryTreeLoader.ts
new file mode 100644
index 00000000000..60967cd5c69
--- /dev/null
+++ b/src/spa/router/libraryTreeLoader.ts
@@ -0,0 +1,8 @@
+import type { LoaderFunctionArgs } from 'react-router';
+
+// The route tables sit in the entry chunk's static graph; resolving the real
+// loader on first use keeps the tree store in the library route's lazy chunks.
+export const libraryTreeLoader = (args: LoaderFunctionArgs) =>
+ import('@/routes/(main)/resource/library/libraryTreeLoader').then((module) =>
+ module.libraryTreeLoader(args),
+ );
diff --git a/src/store/library/slices/crud/action.test.ts b/src/store/library/slices/crud/action.test.ts
index 6992adcd9b7..6d1c0136ca0 100644
--- a/src/store/library/slices/crud/action.test.ts
+++ b/src/store/library/slices/crud/action.test.ts
@@ -23,7 +23,14 @@ import { initialKnowledgeBaseState } from './initialState';
import { knowledgeBaseItemResource, knowledgeBaseListResource } from './projection';
import { knowledgeBaseSelectors } from './selectors';
-const mocks = vi.hoisted(() => ({ activeWorkspaceId: null as string | null }));
+const mocks = vi.hoisted(() => ({
+ activeWorkspaceId: null as string | null,
+ forgetLibrary: vi.fn(),
+}));
+
+vi.mock('@/store/tree', () => ({
+ useTreeStore: { getState: () => ({ forgetLibrary: mocks.forgetLibrary }) },
+}));
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
getActiveWorkspaceId: () => mocks.activeWorkspaceId,
@@ -236,6 +243,17 @@ describe('knowledgeBase crud replicas', () => {
await expect(operation).rejects.toThrow('boom');
expect(list('private')?.map((kb) => kb.id)).toEqual(['p1', 'p2']);
+ // A failed delete keeps the library's persisted sidebar tree.
+ expect(mocks.forgetLibrary).not.toHaveBeenCalled();
+ });
+
+ it("forgets the deleted library's persisted sidebar tree", async () => {
+ await seedList();
+ vi.mocked(knowledgeBaseService.deleteKnowledgeBase).mockResolvedValue(undefined as any);
+
+ await useKnowledgeBaseStore.getState().removeKnowledgeBase('p1');
+
+ expect(mocks.forgetLibrary).toHaveBeenCalledWith('p1');
});
it('renames across the list and the by-id copy optimistically, then reconciles', async () => {
diff --git a/src/store/library/slices/crud/action.ts b/src/store/library/slices/crud/action.ts
index 0d2962a94ef..8643f28708e 100644
--- a/src/store/library/slices/crud/action.ts
+++ b/src/store/library/slices/crud/action.ts
@@ -155,6 +155,11 @@ export class KnowledgeBaseCrudActionImpl {
knowledgeBaseService.deleteKnowledgeBase(id),
);
+ // The library sidebar persists its tree per library: a revisit of the old
+ // URL must not repaint the deleted library's rows.
+ const { useTreeStore } = await import('@/store/tree');
+ useTreeStore.getState().forgetLibrary(id);
+
await this.#get().refreshKnowledgeBaseList();
};
diff --git a/src/store/tree/actions.persist.test.ts b/src/store/tree/actions.persist.test.ts
new file mode 100644
index 00000000000..d80ce3e0a77
--- /dev/null
+++ b/src/store/tree/actions.persist.test.ts
@@ -0,0 +1,448 @@
+import { CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as ReplicaModule from '@/libs/replica';
+import { createReplicaState } from '@/libs/replica';
+import { broadcastCacheScope, resetCacheScopeBroadcast } from '@/libs/replica/cacheScopeEvents';
+import type * as CacheScopeModule from '@/libs/swr/useCacheScope';
+
+import { TreeActionImpl } from './actions';
+import {
+ buildLibraryTreeSnapshot,
+ MAX_PERSISTED_FOLDERS,
+ MAX_PERSISTED_ITEMS_PER_FOLDER,
+} from './projection';
+import type { TreeItem, TreeState } from './types';
+
+const { mockGetKnowledgeItems, mockUpdateResource, scope } = vi.hoisted(() => ({
+ mockGetKnowledgeItems: vi.fn(),
+ mockUpdateResource: vi.fn(),
+ scope: { current: 'user-a:personal' },
+}));
+
+vi.mock('@/libs/swr/useCacheScope', async () => ({
+ ...(await vi.importActual<typeof CacheScopeModule>('@/libs/swr/useCacheScope')),
+ getCacheScope: () => scope.current,
+}));
+
+vi.mock('@/libs/replica', async () => ({
+ ...(await vi.importActual<typeof ReplicaModule>('@/libs/replica')),
+ revalidateReplica: vi.fn(),
+}));
+
+vi.mock('@/features/ResourceManager/store', () => ({
+ useResourceManagerStore: { getState: () => ({ collapseHierarchySearch: vi.fn() }) },
+}));
+
+vi.mock('@/services/file', () => ({
+ fileService: { getKnowledgeItems: mockGetKnowledgeItems },
+}));
+
+vi.mock('@/services/resource', () => ({
+ resourceService: { updateResource: mockUpdateResource },
+}));
+vi.mock('@/store/file', () => ({ useFileStore: { getState: () => ({}) } }));
+
+const folder = (id: string, name = id): TreeItem => ({
+ fileType: CUSTOM_FOLDER_FILE_TYPE,
+ id,
+ isFolder: true,
+ name,
+ url: '',
+});
+
+const file = (id: string, extra: Partial<TreeItem> = {}): TreeItem => ({
+ fileType: 'text/plain',
+ id,
+ isFolder: false,
+ name: id,
+ url: '',
+ ...extra,
+});
+
+const createState = (): TreeState =>
+ ({
+ children: {},
+ epoch: 0,
+ errors: {},
+ expanded: {},
+ knowledgeBaseId: null,
+ snapshotMap: {},
+ snapshotReplica: createReplicaState(),
+ status: {},
+ }) as unknown as TreeState;
+
+const setup = () => {
+ const state = createState();
+ const get = () => state;
+ const set = (partial: Partial<TreeState> | ((s: TreeState) => Partial<TreeState>)) => {
+ Object.assign(state, typeof partial === 'function' ? partial(state) : partial);
+ };
+ const actions = new TreeActionImpl(set as any, get);
+ return { actions, state };
+};
+
+/** A request that resolves only when the test says so. */
+const deferred = () => {
+ let resolve!: (value: { items: unknown[] }) => void;
+ const promise = new Promise<{ items: unknown[] }>((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+};
+
+const serverRow = (id: string, isFolder = false) => ({
+ fileType: isFolder ? CUSTOM_FOLDER_FILE_TYPE : 'text/plain',
+ id,
+ name: id,
+ url: 'https://s3.example.com/signed?X-Amz-Signature=secret',
+});
+
+describe('TreeActionImpl.init — keep the tree across remounts', () => {
+ beforeEach(() => {
+ mockGetKnowledgeItems.mockReset();
+ });
+
+ it('keeps the loaded tree when the same library mounts again, refreshing it in the background', async () => {
+ const { actions, state } = setup();
+ mockGetKnowledgeItems.mockResolvedValue({ items: [serverRow('folder-a', true)] });
+
+ actions.init('kb-1');
+ await vi.waitFor(() => expect(state.children['']).toHaveLength(1));
+ state.expanded = { 'folder-a': true };
+ state.children['folder-a'] = [file('doc-1')];
+
+ const pending = deferred();
+ mockGetKnowledgeItems.mockReset().mockReturnValue(pending.promise);
+ actions.init('kb-1');
+
+ // Same frame as the remount: nothing was wiped back to the skeleton.
+ expect(state.children[''].map((i) => i.id)).toEqual(['folder-a']);
+ expect(state.children['folder-a'].map((i) => i.id)).toEqual(['doc-1']);
+ expect(state.expanded['folder-a']).toBe(true);
+ // Root and the open folder are confirmed in the background.
+ expect(mockGetKnowledgeItems.mock.calls.map(([args]) => args.parentId)).toEqual([
+ null,
+ 'folder-a',
+ ]);
+ pending.resolve({ items: [] });
+ });
+
+ it('refreshes at most MAX_PERSISTED_FOLDERS folders on remount and collapses the rest', async () => {
+ const { actions, state } = setup();
+ const folders = Array.from({ length: MAX_PERSISTED_FOLDERS + 10 }, (_, i) => folder(`d-${i}`));
+ mockGetKnowledgeItems.mockResolvedValue({ items: folders.map((f) => serverRow(f.id, true)) });
+ actions.init('kb-1');
+ await vi.waitFor(() => expect(state.children['']).toHaveLength(folders.length));
+ for (const f of folders) {
+ state.children[f.id] = [file(`${f.id}-child`)];
+ state.expanded[f.id] = true;
+ }
+
+ mockGetKnowledgeItems.mockReset().mockReturnValue(new Promise(() => {}));
+ actions.init('kb-1');
+
+ // The root plus the first expanded folders, never one request per open folder.
+ expect(mockGetKnowledgeItems).toHaveBeenCalledTimes(MAX_PERSISTED_FOLDERS);
+ expect(state.children['d-0'].map((i) => i.id)).toEqual(['d-0-child']);
+ // Folders past the cap are not left stale: collapsed, so the next expand reloads them.
+ const last = folders.at(-1)!.id;
+ expect(state.children[last]).toBeUndefined();
+ expect(state.expanded[last]).toBeFalsy();
+ });
+
+ it('drops a folder loaded but collapsed before leaving, so expanding it after the return refetches', async () => {
+ const { actions, state } = setup();
+ mockGetKnowledgeItems.mockResolvedValue({ items: [serverRow('folder-a', true)] });
+ actions.init('kb-1');
+ await vi.waitFor(() => expect(state.children['']).toHaveLength(1));
+ // Loaded once, then collapsed before the user left the library.
+ state.children['folder-a'] = [file('stale-doc')];
+ state.expanded = { 'folder-a': false };
+
+ mockGetKnowledgeItems.mockReset().mockResolvedValue({ items: [] });
+ actions.init('kb-1');
+ expect(state.children['folder-a']).toBeUndefined();
+
+ mockGetKnowledgeItems.mockClear().mockResolvedValue({ items: [serverRow('fresh-doc')] });
+ actions.toggle('folder-a');
+
+ expect(mockGetKnowledgeItems.mock.calls.map(([args]) => args.parentId)).toEqual(['folder-a']);
+ await vi.waitFor(() =>
+ expect(state.children['folder-a'].map((i) => i.id)).toEqual(['fresh-doc']),
+ );
+ });
+
+ it('still resets when a different library mounts', () => {
+ const { actions, state } = setup();
+ mockGetKnowledgeItems.mockReturnValue(new Promise(() => {}));
+ state.knowledgeBaseId = 'kb-1';
+ state.children = { '': [folder('folder-a')] };
+
+ actions.init('kb-2');
+
+ expect(state.knowledgeBaseId).toBe('kb-2');
+ expect(state.children).toEqual({});
+ });
+});
+
+describe('TreeActionImpl.init — persisted snapshot', () => {
+ beforeEach(() => {
+ mockGetKnowledgeItems.mockReset();
+ });
+
+ it('paints the persisted tree in the init commit, before the network answers', async () => {
+ const { actions, state } = setup();
+ state.snapshotMap = {
+ 'kb-1': {
+ children: { '': [folder('folder-a')], 'folder-a': [file('doc-1')] },
+ expanded: ['folder-a'],
+ },
+ };
+ const root = deferred();
+ const sub = deferred();
+ mockGetKnowledgeItems.mockImplementation(({ parentId }) =>
+ parentId ? sub.promise : root.promise,
+ );
+
+ actions.init('kb-1');
+
+ expect(state.children[''].map((i) => i.id)).toEqual(['folder-a']);
+ expect(state.children['folder-a'].map((i) => i.id)).toEqual(['doc-1']);
+ expect(state.expanded['folder-a']).toBe(true);
+
+ // The server's answer replaces the stale rows.
+ root.resolve({ items: [serverRow('folder-a', true), serverRow('doc-new')] });
+ sub.resolve({ items: [serverRow('doc-2')] });
+ await vi.waitFor(() => {
+ expect(state.children[''].map((i) => i.id)).toEqual(['folder-a', 'doc-new']);
+ expect(state.children['folder-a'].map((i) => i.id)).toEqual(['doc-2']);
+ });
+ });
+
+ it('records the confirmed tree as the library snapshot without signed urls', async () => {
+ const { actions, state } = setup();
+ mockGetKnowledgeItems.mockResolvedValue({ items: [serverRow('doc-1')] });
+
+ actions.init('kb-1');
+
+ await vi.waitFor(() => expect(state.snapshotMap['kb-1']).toBeDefined());
+ expect(state.snapshotMap['kb-1'].children[''].map((i) => i.id)).toEqual(['doc-1']);
+ expect(state.snapshotMap['kb-1'].children[''][0].url).toBe('');
+ });
+});
+
+describe('TreeActionImpl.reconcile — optimistic explorer rows', () => {
+ beforeEach(() => {
+ mockGetKnowledgeItems.mockReset();
+ });
+
+ it('renders an unconfirmed explorer list without persisting it, then persists once it settles', async () => {
+ const { actions, state } = setup();
+ mockGetKnowledgeItems.mockResolvedValue({ items: [serverRow('doc-1')] });
+ actions.init('kb-1');
+ await vi.waitFor(() => expect(state.snapshotMap['kb-1']).toBeDefined());
+
+ // A pending create: the row shows, but a reload must not repaint it.
+ actions.reconcile('', [file('doc-1'), file('temp-row')], { confirmed: false });
+ expect(state.children[''].map((i) => i.id)).toEqual(['doc-1', 'temp-row']);
+ // Nor may an unrelated write persist it meanwhile.
+ actions.reconcile('folder-y', [file('doc-y')]);
+ expect(state.snapshotMap['kb-1'].children[''].map((i) => i.id)).toEqual(['doc-1']);
+
+ actions.reconcile('', [file('doc-1'), file('doc-2')], { confirmed: true });
+ expect(state.snapshotMap['kb-1'].children[''].map((i) => i.id)).toEqual(['doc-1', 'doc-2']);
+ });
+});
+
+describe('TreeActionImpl — sidebar transactions and the snapshot', () => {
+ beforeEach(() => {
+ mockGetKnowledgeItems.mockReset();
+ mockUpdateResource.mockReset();
+ });
+
+ it('never persists a pending rename, and a rejected one leaves the stored name intact', async () => {
+ const { actions, state } = setup();
+ mockGetKnowledgeItems.mockResolvedValue({ items: [serverRow('doc-1')] });
+ actions.init('kb-1');
+ await vi.waitFor(() => expect(state.snapshotMap['kb-1']).toBeDefined());
+
+ let reject!: (error: Error) => void;
+ mockUpdateResource.mockReturnValue(
+ new Promise((_resolve, r) => {
+ reject = r;
+ }),
+ );
+ const renaming = actions.renameItem('doc-1', '', 'renamed');
+ await vi.waitFor(() => expect(state.children[''][0].name).toBe('renamed'));
+
+ // An unrelated write while the rename is in flight must not persist it.
+ actions.reconcile('folder-y', [file('doc-y')]);
+ expect(state.snapshotMap['kb-1'].children[''][0].name).toBe('doc-1');
+
+ reject(new Error('rename failed'));
+ await renaming.catch(() => {});
+ await vi.waitFor(() => expect(state.children[''][0].name).toBe('doc-1'));
+ expect(state.snapshotMap['kb-1'].children[''][0].name).toBe('doc-1');
+ });
+});
+
+describe('TreeActionImpl — reset during a sidebar transaction', () => {
+ beforeEach(() => {
+ mockGetKnowledgeItems.mockReset();
+ mockUpdateResource.mockReset();
+ });
+
+ it("does not roll a previous library's failed rename back onto the new tree", async () => {
+ const { actions, state } = setup();
+ mockGetKnowledgeItems.mockResolvedValue({ items: [serverRow('doc-1')] });
+ actions.init('kb-1');
+ await vi.waitFor(() => expect(state.children['']).toHaveLength(1));
+
+ let reject!: (error: Error) => void;
+ mockUpdateResource.mockReturnValue(
+ new Promise((_resolve, r) => {
+ reject = r;
+ }),
+ );
+ const renaming = actions.renameItem('doc-1', '', 'renamed');
+ await vi.waitFor(() => expect(mockUpdateResource).toHaveBeenCalled());
+
+ mockGetKnowledgeItems.mockResolvedValue({ items: [serverRow('other-doc')] });
+ actions.init('kb-2');
+ await vi.waitFor(() => expect(state.children[''][0].id).toBe('other-doc'));
+ mockGetKnowledgeItems.mockClear();
+
+ reject(new Error('rename failed'));
+ await renaming.catch(() => {});
+
+ expect(state.children[''].map((i) => i.id)).toEqual(['other-doc']);
+ // Nor does the settled transaction refresh the previous library's folders.
+ expect(mockGetKnowledgeItems).not.toHaveBeenCalled();
+ });
+});
+
+describe('TreeActionImpl — abandoned optimistic folders', () => {
+ beforeEach(() => {
+ mockGetKnowledgeItems.mockReset();
+ });
+
+ it('keeps persisting the rest of the tree when a folder left mid-mutation stays unconfirmed', async () => {
+ const { actions, state } = setup();
+ mockGetKnowledgeItems.mockImplementation(({ parentId }) =>
+ Promise.resolve({
+ items: parentId ? [serverRow('doc-a')] : [serverRow('folder-a', true), serverRow('doc-1')],
+ }),
+ );
+ actions.init('kb-1');
+ await vi.waitFor(() => expect(state.children['']).toHaveLength(2));
+ actions.toggle('folder-a');
+ await vi.waitFor(() => expect(state.snapshotMap['kb-1'].children['folder-a']).toBeDefined());
+
+ // A create in folder A, then the user navigates away before it settles.
+ actions.reconcile('folder-a', [file('doc-a'), file('temp-row')], { confirmed: false });
+
+ // A later confirmed write elsewhere still reaches the snapshot...
+ actions.reconcile('', [folder('folder-a'), file('doc-1'), file('doc-2')], { confirmed: true });
+ const stored = state.snapshotMap['kb-1'].children;
+ expect(stored[''].map((i) => i.id)).toEqual(['folder-a', 'doc-1', 'doc-2']);
+ // ...while folder A keeps its last confirmed rows.
+ expect(stored['folder-a'].map((i) => i.id)).toEqual(['doc-a']);
+ });
+});
+
+describe('TreeActionImpl.forgetLibrary', () => {
+ beforeEach(() => {
+ mockGetKnowledgeItems.mockReset();
+ });
+
+ it("drops a deleted library's persisted and rendered tree", async () => {
+ const { actions, state } = setup();
+ mockGetKnowledgeItems.mockResolvedValue({ items: [serverRow('doc-1')] });
+ actions.init('kb-1');
+ await vi.waitFor(() => expect(state.snapshotMap['kb-1']).toBeDefined());
+
+ actions.forgetLibrary('kb-1');
+
+ expect(state.snapshotMap['kb-1']).toBeUndefined();
+ expect(state.knowledgeBaseId).toBeNull();
+ expect(state.children).toEqual({});
+ });
+});
+
+describe('TreeActionImpl — cache scope switch', () => {
+ beforeEach(() => {
+ mockGetKnowledgeItems.mockReset();
+ resetCacheScopeBroadcast();
+ scope.current = 'user-a:personal';
+ });
+
+ it("drops the previous identity's rendered tree when the scope changes", async () => {
+ const { actions, state } = setup();
+ mockGetKnowledgeItems.mockResolvedValue({ items: [serverRow('secret-folder', true)] });
+ actions.init('kb-1');
+ await vi.waitFor(() => expect(state.children['']).toHaveLength(1));
+ broadcastCacheScope('user-a:personal');
+
+ // The new identity's request fails: nothing of user-a may stay on screen.
+ mockGetKnowledgeItems.mockReset().mockRejectedValue(new Error('unauthorized'));
+ scope.current = 'user-b:personal';
+ broadcastCacheScope('user-b:personal');
+
+ expect(state.children['']).toBeUndefined();
+ expect(state.snapshotMap['kb-1']).toBeUndefined();
+ await vi.waitFor(() => expect(state.status['']).toBe('error'));
+ expect(state.children['']).toBeUndefined();
+ });
+
+ it('keeps the tree when the resolved scope is the one it was built for', async () => {
+ const { actions, state } = setup();
+ mockGetKnowledgeItems.mockResolvedValue({ items: [serverRow('folder-a', true)] });
+ actions.init('kb-1');
+ await vi.waitFor(() => expect(state.children['']).toHaveLength(1));
+ const epoch = state.epoch;
+
+ broadcastCacheScope('user-a:personal');
+
+ expect(state.epoch).toBe(epoch);
+ expect(state.children[''].map((i) => i.id)).toEqual(['folder-a']);
+ });
+});
+
+describe('buildLibraryTreeSnapshot', () => {
+ it('keeps only the visible tree and bounds its size', () => {
+ const many = Array.from({ length: MAX_PERSISTED_ITEMS_PER_FOLDER + 5 }, (_, i) =>
+ file(`f-${i}`, { metadata: { emoji: '📄', huge: 'x'.repeat(100) } }),
+ );
+ const snapshot = buildLibraryTreeSnapshot(
+ {
+ '': [folder('open'), folder('closed'), ...many],
+ 'closed': [file('hidden')],
+ 'open': [file('visible')],
+ },
+ { open: true },
+ )!;
+
+ expect(Object.keys(snapshot.children).sort()).toEqual(['', 'open']);
+ expect(snapshot.expanded).toEqual(['open']);
+ expect(snapshot.children['']).toHaveLength(MAX_PERSISTED_ITEMS_PER_FOLDER);
+ expect(snapshot.children[''][2].metadata).toEqual({ emoji: '📄' });
+ });
+
+ it('caps the number of persisted folders', () => {
+ const folders = Array.from({ length: MAX_PERSISTED_FOLDERS + 5 }, (_, i) => folder(`d-${i}`));
+ const children: Record<string, TreeItem[]> = { '': folders };
+ const expanded: Record<string, boolean> = {};
+ for (const f of folders) {
+ children[f.id] = [file(`${f.id}-child`)];
+ expanded[f.id] = true;
+ }
+
+ const snapshot = buildLibraryTreeSnapshot(children, expanded)!;
+ expect(Object.keys(snapshot.children)).toHaveLength(MAX_PERSISTED_FOLDERS);
+ });
+
+ it('has nothing to persist before the root loads', () => {
+ expect(buildLibraryTreeSnapshot({}, {})).toBeUndefined();
+ });
+});
diff --git a/src/store/tree/actions.test.ts b/src/store/tree/actions.test.ts
index f6c0f32cb91..ea4d33485ad 100644
--- a/src/store/tree/actions.test.ts
+++ b/src/store/tree/actions.test.ts
@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { hierarchySearchResource } from '@/features/ResourceManager/store/projection';
import type * as ReplicaModule from '@/libs/replica';
+import { createReplicaState } from '@/libs/replica';
import { sortTreeItems, toTreeItem, toTreeItemFromResource, TreeActionImpl } from './actions';
import type { TreeState } from './types';
@@ -94,8 +95,13 @@ const createState = (): TreeState => ({
reconcile: vi.fn(),
removeItems: vi.fn(),
renameItem: vi.fn(),
+ forgetLibrary: vi.fn(),
+ forgetSnapshot: vi.fn(),
reset: vi.fn(),
+ preHydrate: vi.fn(),
revalidate: vi.fn(),
+ snapshotMap: {},
+ snapshotReplica: createReplicaState(),
status: {},
toggle: vi.fn(),
});
diff --git a/src/store/tree/actions.ts b/src/store/tree/actions.ts
index a9657006075..76a8594e21e 100644
--- a/src/store/tree/actions.ts
+++ b/src/store/tree/actions.ts
@@ -1,132 +1,48 @@
-import { CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';
-
-import { hierarchySearchResource } from '@/features/ResourceManager/store/projection';
-import { revalidateReplica } from '@/libs/replica';
+import { createReplicaSlice, recordLens } from '@/libs/replica';
+import { subscribeCacheScope } from '@/libs/replica/cacheScopeEvents';
+import { getCacheScope } from '@/libs/swr/useCacheScope';
import { fileService } from '@/services/file';
import { resourceService } from '@/services/resource';
import type { StoreSetter } from '@/store/types';
import { OptimisticEngine } from '@/store/utils/optimisticEngine';
+import { revalidateHierarchySearch, sortTreeItems, toTreeItem } from './items';
+import {
+ buildLibraryTreeSnapshot,
+ libraryTreeResource,
+ type LibraryTreeSnapshot,
+ MAX_PERSISTED_FOLDERS,
+} from './projection';
import type { TreeDataState, TreeItem, TreeState, TreeStoreHandle } from './types';
-/**
- * The library sidebar swaps the tree for a flat search list while a query is
- * typed; its rows reuse the tree's rename/move/delete actions. Those actions
- * only know the affected folder, so every tree revalidation also refreshes the
- * hierarchy search replica or a renamed/deleted hit would linger there.
- *
- * A revalidation only re-runs the *head* request, and the replica deliberately
- * keeps the rows the user already scrolled to. So dropping the loaded depth is
- * part of the refresh: without it a rename / move / deletion of a row past the
- * first page would leave the stale hit in the loaded tail. The same call drops
- * the searches only a previous session had persisted (never loaded here), which
- * no revalidation could otherwise reach.
- */
-export const revalidateHierarchySearch = async (): Promise<void> => {
- const { useResourceManagerStore } = await import('@/features/ResourceManager/store');
- await useResourceManagerStore.getState().collapseHierarchySearch();
- await revalidateReplica(hierarchySearchResource);
-};
-
-const createdTime = (value?: Date | string): number => {
- if (!value) return 0;
- const time = new Date(value).getTime();
- return Number.isNaN(time) ? 0 : time;
-};
-
-/**
- * Folders first, then newest first inside each group.
- *
- * Every write path (`loadChildren`, `revalidate`, `reconcile`, the optimistic
- * move inserts) runs rows through this, so it — not the server — decides what
- * the sidebar shows. Ordering by name dropped a just-created row into the
- * middle of an A-Z list, which is neither where the user was looking nor what
- * the explorer shows: the resource query returns `created_at desc` and the
- * explorer's default sorter is `createdAt` / `Desc`. Name only breaks ties, and
- * rows with no timestamp (optimistic stubs, older cached payloads) sort as 0 so
- * they keep a stable A-Z tail instead of drifting.
- */
-export const sortTreeItems = <T extends TreeItem>(items: T[]): T[] => {
- return [...items].sort((a, b) => {
- if (a.isFolder && !b.isFolder) return -1;
- if (!a.isFolder && b.isFolder) return 1;
-
- const aTime = createdTime(a.createdAt);
- const bTime = createdTime(b.createdAt);
- if (aTime !== bTime) return bTime - aTime;
-
- return a.name.localeCompare(b.name);
- });
-};
-
-export const toTreeItem = (item: {
- createdAt?: Date | string | null;
- fileId?: string | null;
- fileType: string;
- id: string;
- metadata?: Record<string, any> | null;
- name: string;
- parentId?: string | null;
- size?: number | null;
- slug?: string | null;
- sourceType?: string;
- url?: string;
- userId?: string | null;
- visibility?: 'private' | 'public' | null;
-}): TreeItem => ({
- createdAt: item.createdAt ?? undefined,
- fileId: item.fileId,
- fileType: item.fileType,
- id: item.id,
- isFolder: item.fileType === CUSTOM_FOLDER_FILE_TYPE,
- metadata: item.metadata ?? undefined,
- name: item.name,
- parentId: item.parentId,
- size: item.size ?? undefined,
- slug: item.slug,
- sourceType: item.sourceType,
- url: item.url ?? '',
- userId: item.userId,
- visibility: item.visibility,
-});
-
-/**
- * Explorer row → tree row.
- *
- * Kept next to {@link toTreeItem} and named, rather than inlined at the
- * subscription that reconciles the explorer list into the sidebar, because it
- * is the one place tree rows are rebuilt from a *different* source: anything it
- * forgets to carry is silently dropped from every row the next time the list
- * refreshes. `visibility` and `userId` were lost that way — the sidebar stopped
- * marking private rows and the row menu mis-gated publish / make-private.
- */
-export const toTreeItemFromResource = (item: {
- createdAt?: Date | string | null;
- fileId?: string | null;
- fileType: string;
- id: string;
- metadata?: Record<string, any> | null;
- name: string;
- parentId?: string | null;
- size?: number | null;
- slug?: string | null;
- sourceType?: string;
- url?: string;
- userId?: string | null;
- visibility?: 'private' | 'public' | null;
-}): TreeItem => toTreeItem(item);
+export {
+ revalidateHierarchySearch,
+ sortTreeItems,
+ toTreeItem,
+ toTreeItemFromResource,
+} from './items';
type Setter = StoreSetter<TreeState>;
export class TreeActionImpl {
readonly #get: () => TreeState;
readonly #set: Setter;
- #engine?: OptimisticEngine<TreeDataState>;
+ #engine?: { engine: OptimisticEngine<TreeDataState>; epoch: number };
+ readonly #snapshot;
#storeHandle: TreeStoreHandle;
+ /** Cache scope the rendered tree was loaded under. */
+ #treeScope?: string;
constructor(set: Setter, get: () => TreeState) {
this.#set = set;
this.#get = get;
+ this.#snapshot = createReplicaSlice(libraryTreeResource, {
+ actionPrefix: 'libraryTree',
+ get,
+ set,
+ stateKey: 'snapshotReplica',
+ view: recordLens<TreeState, LibraryTreeSnapshot>('snapshotMap'),
+ });
this.#storeHandle = {
getState: () => ({
children: get().children,
@@ -134,12 +50,45 @@ export class TreeActionImpl {
}),
setState: (next) => set(next as Partial<TreeState>, false, 'tree/engineSetState'),
};
+
+ // Nothing renders this store's replica through `useSync`, so it would never
+ // see an identity switch: a cold boot can seed the tree from the last
+ // user's partition before identity resolves to someone else. The store is
+ // an app-lifetime singleton, so the subscription is never torn down.
+ subscribeCacheScope((scope) => this.#dropStaleScope(scope));
}
+ /**
+ * Drop the previous identity's snapshot and rendered tree, then load the open
+ * library again under the new scope. A no-op when the tree already belongs to
+ * `scope`, which is the common case: identity resolving to the scope the cold
+ * boot guessed.
+ */
+ #dropStaleScope = (scope: string): void => {
+ this.#snapshot.ensureScope(scope);
+ const { knowledgeBaseId } = this.#get();
+ if (!knowledgeBaseId || this.#treeScope === scope) return;
+
+ this.reset();
+ this.init(knowledgeBaseId);
+ };
+
+ /**
+ * One engine per tree epoch. A reset (scope switch, another library) retires
+ * the previous engine: a transaction still in flight there must not roll its
+ * inverse patches onto the tree that replaced the one it patched.
+ */
#getEngine = () => {
- if (this.#engine) return this.#engine;
- this.#engine = new OptimisticEngine(this.#storeHandle, { maxRetries: 1 });
- return this.#engine;
+ const { epoch } = this.#get();
+ if (this.#engine?.epoch === epoch) return this.#engine.engine;
+ const handle: TreeStoreHandle = {
+ getState: this.#storeHandle.getState,
+ setState: (next) => {
+ if (this.#get().epoch === epoch) this.#storeHandle.setState(next);
+ },
+ };
+ this.#engine = { engine: new OptimisticEngine(handle, { maxRetries: 1 }), epoch };
+ return this.#engine.engine;
};
/**
@@ -153,6 +102,34 @@ export class TreeActionImpl {
*/
#queuedRevalidate = new Set<string>();
+ /**
+ * Folders whose rendered rows came from an explorer list with optimistic
+ * overlays still pending (see `reconcile`). The snapshot keeps their last
+ * confirmed rows; the explorer's settle or a server answer for the folder clears it.
+ */
+ #unconfirmedFolders = new Set<string>();
+
+ /** Sidebar transactions (move, rename, delete) whose optimistic patch is not confirmed. */
+ #pendingTx = new Set<symbol>();
+
+ /**
+ * Commit with the snapshot paused, then persist what survived (applied or
+ * rolled back). Resolves `false` when the tree was reset meanwhile: the
+ * caller's follow-up refresh would address the previous scope's folders.
+ */
+ #commitTracked = async (tx: { commit: () => Promise<unknown> }): Promise<boolean> => {
+ const { epoch } = this.#get();
+ const token = Symbol('tx');
+ this.#pendingTx.add(token);
+ try {
+ await tx.commit();
+ } finally {
+ this.#pendingTx.delete(token);
+ if (this.#get().epoch === epoch) this.#persistSnapshot();
+ }
+ return this.#get().epoch === epoch;
+ };
+
#runQueuedRevalidate = (folderId: string) => {
if (!this.#queuedRevalidate.delete(folderId)) return;
void this.revalidate(folderId);
@@ -180,12 +157,84 @@ export class TreeActionImpl {
return key;
};
+ /**
+ * Store the visible tree as the library's persisted snapshot. Runs after the
+ * writes that settle a folder; the replica skips a write whose value did not
+ * change, so a revalidation that confirms the tree costs no storage write.
+ */
+ #persistSnapshot = () => {
+ if (this.#pendingTx.size > 0) return;
+ const { children, expanded, knowledgeBaseId, snapshotMap } = this.#get();
+ if (!knowledgeBaseId) return;
+ // A folder showing the explorer's optimistic overlay keeps its last stored
+ // rows (or is left out): a reload never repaints unconfirmed rows, and a
+ // marker a navigation abandoned only pins its own folder.
+ const confirmed = { ...children };
+ const stored = snapshotMap[knowledgeBaseId]?.children ?? {};
+ for (const id of this.#unconfirmedFolders) {
+ if (stored[id]) confirmed[id] = stored[id];
+ else delete confirmed[id];
+ }
+ const snapshot = buildLibraryTreeSnapshot(confirmed, expanded);
+ if (!snapshot) return;
+ this.#snapshot.update(knowledgeBaseId, () => snapshot);
+ };
+
+ /**
+ * Fill in folders the network has not answered yet from the library's
+ * persisted snapshot, then confirm each of them in the background. A folder
+ * the network already settled keeps its fresh rows.
+ */
+ #seedFromSnapshot = (snapshot: LibraryTreeSnapshot) => {
+ const { children, expanded } = this.#get();
+ const seeded = Object.keys(snapshot.children).filter((folderId) => !children[folderId]);
+ if (seeded.length === 0) return;
+
+ const nextChildren = { ...children };
+ for (const folderId of seeded) nextChildren[folderId] = snapshot.children[folderId];
+ const nextExpanded = { ...expanded };
+ for (const folderId of snapshot.expanded) {
+ if (nextExpanded[folderId] === undefined) nextExpanded[folderId] = true;
+ }
+ this.#set({ children: nextChildren, expanded: nextExpanded }, false, 'tree/seedFromSnapshot');
+
+ // The root's own fetch (started by `init`) is already confirming it.
+ for (const folderId of seeded) if (folderId) void this.#revalidateFolder(folderId);
+ };
+
+ #hydrateSnapshot = async (knowledgeBaseId: string, epoch: number) => {
+ await this.preHydrate(knowledgeBaseId);
+ if (this.#get().epoch !== epoch) return;
+ const snapshot = this.#get().snapshotMap[knowledgeBaseId];
+ if (snapshot) this.#seedFromSnapshot(snapshot);
+ };
+
+ preHydrate = (knowledgeBaseId: string): Promise<boolean> => {
+ const scope = getCacheScope();
+ // The slot may still hold the previous identity's rows; drop them before seeding.
+ this.#snapshot.ensureScope(scope);
+ return this.#snapshot.hydrate({ libraryId: knowledgeBaseId }, scope);
+ };
+
init = (knowledgeBaseId: string) => {
+ const current = this.#get();
+ // Remounting the library already in memory (leaving the page and coming
+ // back): keep the tree on screen and confirm what is loaded in the
+ // background, instead of wiping it back to a skeleton.
+ if (current.knowledgeBaseId === knowledgeBaseId && current.children['']) {
+ this.#revalidateOnRemount();
+ return;
+ }
+
this.#queuedRevalidate.clear();
+ this.#unconfirmedFolders.clear();
+ this.#pendingTx.clear();
+ this.#treeScope = getCacheScope();
+ const epoch = current.epoch + 1;
this.#set(
{
children: {},
- epoch: this.#get().epoch + 1,
+ epoch,
errors: {},
expanded: {},
knowledgeBaseId,
@@ -194,11 +243,80 @@ export class TreeActionImpl {
false,
'tree/init',
);
+
+ // The route loader usually hydrated the snapshot already, so the tree
+ // paints in this very commit; otherwise it lands as soon as storage answers.
+ const snapshot = current.snapshotMap[knowledgeBaseId];
+ if (snapshot) this.#seedFromSnapshot(snapshot);
void this.loadChildren('');
+ if (!snapshot) void this.#hydrateSnapshot(knowledgeBaseId, epoch);
+ };
+
+ /**
+ * Confirm the visible tree after a remount, bounded like the persisted
+ * snapshot: the root and the first expanded folders are refreshed in place.
+ * Open folders past the cap are collapsed and forgotten instead of left stale,
+ * so a long session with hundreds of open folders does not fire one request
+ * per folder on every return; expanding one again loads it fresh.
+ */
+ #revalidateOnRemount = () => {
+ const visible = this.#loadedVisibleFolders();
+ const kept = new Set(visible.slice(0, MAX_PERSISTED_FOLDERS));
+ // Everything else loaded is dropped: open folders past the cap, and folders
+ // loaded earlier but collapsed (or under a collapsed parent). Their rows
+ // would not be refreshed here, and expanding a folder that still has rows
+ // skips the fetch, so they would stay stale for the rest of the session.
+ const dropped = Object.keys(this.#get().children).filter((id) => !kept.has(id));
+ if (dropped.length > 0) {
+ const children = { ...this.#get().children };
+ const expanded = { ...this.#get().expanded };
+ for (const folderId of dropped) {
+ delete children[folderId];
+ if (expanded[folderId]) expanded[folderId] = false;
+ }
+ this.#set({ children, expanded }, false, 'tree/dropUnrefreshed');
+ }
+
+ for (const folderId of visible.slice(0, MAX_PERSISTED_FOLDERS)) {
+ void this.#revalidateFolder(folderId);
+ }
+ };
+
+ /** The root plus every expanded folder reachable from it that has rows loaded. */
+ #loadedVisibleFolders = (): string[] => {
+ const { children, expanded } = this.#get();
+ const result: string[] = [];
+ const queue = [''];
+ while (queue.length > 0) {
+ const folderId = queue.shift()!;
+ const items = children[folderId];
+ if (!items || result.includes(folderId)) continue;
+ result.push(folderId);
+ for (const item of items) if (item.isFolder && expanded[item.id]) queue.push(item.id);
+ }
+ return result;
+ };
+
+ /**
+ * Forget the open library's persisted tree after a deletion only the server
+ * can enumerate (delete-by-query): a reload must not repaint the deleted rows
+ * if the follow-up refresh never lands. That refresh stores the survivors.
+ */
+ forgetSnapshot = () => {
+ const { knowledgeBaseId } = this.#get();
+ if (knowledgeBaseId) void this.#snapshot.remove(knowledgeBaseId);
+ };
+
+ /** A deleted library: drop its persisted tree, and the rendered one if it is open. */
+ forgetLibrary = (knowledgeBaseId: string) => {
+ void this.#snapshot.remove(knowledgeBaseId);
+ if (this.#get().knowledgeBaseId === knowledgeBaseId) this.reset();
};
reset = () => {
this.#queuedRevalidate.clear();
+ this.#unconfirmedFolders.clear();
+ this.#pendingTx.clear();
this.#set(
{
children: {},
@@ -220,7 +338,9 @@ export class TreeActionImpl {
if (!isExpanded && !this.#get().children[folderId]) {
void this.loadChildren(folderId);
+ return;
}
+ this.#persistSnapshot();
};
loadChildren = async (folderId: string) => {
@@ -257,6 +377,8 @@ export class TreeActionImpl {
false,
'tree/loadChildren/success',
);
+ this.#unconfirmedFolders.delete(folderId);
+ this.#persistSnapshot();
this.#runQueuedRevalidate(folderId);
} catch (error) {
if (this.#get().epoch !== epoch) return;
@@ -278,8 +400,14 @@ export class TreeActionImpl {
revalidate = async (folderKey: string) => {
void revalidateHierarchySearch();
+ await this.#revalidateFolder(this.#resolveFolderKey(folderKey));
+ };
- const folderId = this.#resolveFolderKey(folderKey);
+ /**
+ * Refetch one folder while its current rows stay on screen. A failure keeps
+ * them (status back to idle) rather than flagging the folder as errored.
+ */
+ #revalidateFolder = async (folderId: string) => {
const { epoch, knowledgeBaseId, status } = this.#get();
if (status[folderId] === 'loading' || status[folderId] === 'revalidating') {
this.#queuedRevalidate.add(folderId);
@@ -313,6 +441,8 @@ export class TreeActionImpl {
false,
'tree/revalidate/success',
);
+ this.#unconfirmedFolders.delete(folderId);
+ this.#persistSnapshot();
this.#runQueuedRevalidate(folderId);
} catch {
if (this.#get().epoch !== epoch) return;
@@ -325,7 +455,12 @@ export class TreeActionImpl {
}
};
- reconcile = (folderKey: string, items: TreeItem[]) => {
+ /**
+ * `confirmed: false` — the explorer list still carries optimistic overlays
+ * (a pending create, rename, move or delete): render the rows, but keep them
+ * out of the persisted snapshot until the explorer settles.
+ */
+ reconcile = (folderKey: string, items: TreeItem[], options?: { confirmed?: boolean }) => {
const folderId = this.#resolveFolderKey(folderKey);
// The explorer list can hold a row just created for ANOTHER folder (a folder
// row's "+" while a different folder is open): it cannot tell without the
@@ -342,6 +477,12 @@ export class TreeActionImpl {
false,
'tree/reconcile',
);
+ if (options?.confirmed === false) {
+ this.#unconfirmedFolders.add(folderId);
+ return;
+ }
+ this.#unconfirmedFolders.delete(folderId);
+ this.#persistSnapshot();
};
expandAncestors = async (folderIds: string[]) => {
@@ -417,9 +558,11 @@ export class TreeActionImpl {
delete expanded[id];
delete status[id];
delete errors[id];
+ this.#unconfirmedFolders.delete(id);
}
this.#set({ children, errors, expanded, status }, false, 'tree/dropNodes');
+ this.#persistSnapshot();
// A parent that is itself being removed has no list left to refresh, and
// fetching it would recreate the orphan entry the purge just dropped.
@@ -485,8 +628,7 @@ export class TreeActionImpl {
}
};
- await tx.commit();
- await this.#revalidateSettled([fromParent, toParent]);
+ if (await this.#commitTracked(tx)) await this.#revalidateSettled([fromParent, toParent]);
};
moveItems = async (itemIds: string[], fromParent: string, toParent: string): Promise<void> => {
@@ -550,8 +692,7 @@ export class TreeActionImpl {
}
};
- await tx.commit();
- await this.#revalidateSettled([fromParent, toParent]);
+ if (await this.#commitTracked(tx)) await this.#revalidateSettled([fromParent, toParent]);
};
renameItem = async (itemId: string, parentId: string, newName: string): Promise<void> => {
@@ -574,8 +715,7 @@ export class TreeActionImpl {
await useFileStore.getState().refreshFileList();
};
- await tx.commit();
- await this.#revalidateSettled([parentId]);
+ if (await this.#commitTracked(tx)) await this.#revalidateSettled([parentId]);
};
removeItems = async (itemIds: string[], parentId: string): Promise<void> => {
@@ -593,7 +733,6 @@ export class TreeActionImpl {
await useFileStore.getState().refreshFileList();
};
- await tx.commit();
- await this.dropNodes(itemIds, parentId);
+ if (await this.#commitTracked(tx)) await this.dropNodes(itemIds, parentId);
};
}
diff --git a/src/store/tree/initialState.ts b/src/store/tree/initialState.ts
index eb494c1a954..2800d2b10d4 100644
--- a/src/store/tree/initialState.ts
+++ b/src/store/tree/initialState.ts
@@ -1,3 +1,6 @@
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+
+import type { LibraryTreeSnapshot } from './projection';
import type { TreeDataState } from './types';
export interface TreeInitialState extends TreeDataState {
@@ -5,6 +8,9 @@ export interface TreeInitialState extends TreeDataState {
errors: Record<string, unknown>;
expanded: Record<string, boolean>;
knowledgeBaseId: string | null;
+ /** Last confirmed tree per library, as persisted (see `libraryTreeResource`). */
+ snapshotMap: Record<string, LibraryTreeSnapshot>;
+ snapshotReplica: ReplicaState<LibraryTreeSnapshot>;
}
export const initialTreeState: TreeInitialState = {
@@ -13,5 +19,7 @@ export const initialTreeState: TreeInitialState = {
errors: {},
expanded: {},
knowledgeBaseId: null,
+ snapshotMap: {},
+ snapshotReplica: createReplicaState(),
status: {},
};
diff --git a/src/store/tree/items.ts b/src/store/tree/items.ts
new file mode 100644
index 00000000000..c6b19e7ff58
--- /dev/null
+++ b/src/store/tree/items.ts
@@ -0,0 +1,113 @@
+import { CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';
+
+import { hierarchySearchResource } from '@/features/ResourceManager/store/projection';
+import { revalidateReplica } from '@/libs/replica';
+
+import type { TreeItem } from './types';
+
+/**
+ * The library sidebar swaps the tree for a flat search list while a query is
+ * typed; its rows reuse the tree's rename/move/delete actions. Those actions
+ * only know the affected folder, so every tree revalidation also refreshes the
+ * hierarchy search replica or a renamed/deleted hit would linger there.
+ *
+ * A revalidation only re-runs the *head* request, and the replica deliberately
+ * keeps the rows the user already scrolled to. So dropping the loaded depth is
+ * part of the refresh: without it a rename / move / deletion of a row past the
+ * first page would leave the stale hit in the loaded tail. The same call drops
+ * the searches only a previous session had persisted (never loaded here), which
+ * no revalidation could otherwise reach.
+ */
+export const revalidateHierarchySearch = async (): Promise<void> => {
+ const { useResourceManagerStore } = await import('@/features/ResourceManager/store');
+ await useResourceManagerStore.getState().collapseHierarchySearch();
+ await revalidateReplica(hierarchySearchResource);
+};
+
+const createdTime = (value?: Date | string): number => {
+ if (!value) return 0;
+ const time = new Date(value).getTime();
+ return Number.isNaN(time) ? 0 : time;
+};
+
+/**
+ * Folders first, then newest first inside each group.
+ *
+ * Every write path (`loadChildren`, `revalidate`, `reconcile`, the optimistic
+ * move inserts) runs rows through this, so it — not the server — decides what
+ * the sidebar shows. Ordering by name dropped a just-created row into the
+ * middle of an A-Z list, which is neither where the user was looking nor what
+ * the explorer shows: the resource query returns `created_at desc` and the
+ * explorer's default sorter is `createdAt` / `Desc`. Name only breaks ties, and
+ * rows with no timestamp (optimistic stubs, older cached payloads) sort as 0 so
+ * they keep a stable A-Z tail instead of drifting.
+ */
+export const sortTreeItems = <T extends TreeItem>(items: T[]): T[] => {
+ return [...items].sort((a, b) => {
+ if (a.isFolder && !b.isFolder) return -1;
+ if (!a.isFolder && b.isFolder) return 1;
+
+ const aTime = createdTime(a.createdAt);
+ const bTime = createdTime(b.createdAt);
+ if (aTime !== bTime) return bTime - aTime;
+
+ return a.name.localeCompare(b.name);
+ });
+};
+
+export const toTreeItem = (item: {
+ createdAt?: Date | string | null;
+ fileId?: string | null;
+ fileType: string;
+ id: string;
+ metadata?: Record<string, any> | null;
+ name: string;
+ parentId?: string | null;
+ size?: number | null;
+ slug?: string | null;
+ sourceType?: string;
+ url?: string;
+ userId?: string | null;
+ visibility?: 'private' | 'public' | null;
+}): TreeItem => ({
+ createdAt: item.createdAt ?? undefined,
+ fileId: item.fileId,
+ fileType: item.fileType,
+ id: item.id,
+ isFolder: item.fileType === CUSTOM_FOLDER_FILE_TYPE,
+ metadata: item.metadata ?? undefined,
+ name: item.name,
+ parentId: item.parentId,
+ size: item.size ?? undefined,
+ slug: item.slug,
+ sourceType: item.sourceType,
+ url: item.url ?? '',
+ userId: item.userId,
+ visibility: item.visibility,
+});
+
+/**
+ * Explorer row → tree row.
+ *
+ * Kept next to {@link toTreeItem} and named, rather than inlined at the
+ * subscription that reconciles the explorer list into the sidebar, because it
+ * is the one place tree rows are rebuilt from a *different* source: anything it
+ * forgets to carry is silently dropped from every row the next time the list
+ * refreshes. `visibility` and `userId` were lost that way — the sidebar stopped
+ * marking private rows and the row menu mis-gated publish / make-private.
+ */
+export const toTreeItemFromResource = (item: {
+ createdAt?: Date | string | null;
+ fileId?: string | null;
+ fileType: string;
+ id: string;
+ metadata?: Record<string, any> | null;
+ name: string;
+ parentId?: string | null;
+ size?: number | null;
+ slug?: string | null;
+ sourceType?: string;
+ url?: string;
+ userId?: string | null;
+ visibility?: 'private' | 'public' | null;
+}): TreeItem => toTreeItem(item);
diff --git a/src/store/tree/projection.ts b/src/store/tree/projection.ts
new file mode 100644
index 00000000000..1714c4daf5b
--- /dev/null
+++ b/src/store/tree/projection.ts
@@ -0,0 +1,88 @@
+import { defineReplica } from '@/libs/replica';
+
+import type { TreeItem } from './types';
+
+/**
+ * What a reload paints for one library's sidebar before the network answers:
+ * the rows of the root and of every expanded folder the user can see, plus
+ * which of those folders were open.
+ */
+export interface LibraryTreeSnapshot {
+ children: Record<string, TreeItem[]>;
+ expanded: string[];
+}
+
+/** Folders kept per library (the root counts), walked depth first from the root. */
+export const MAX_PERSISTED_FOLDERS = 20;
+/** Rows kept per folder; the first network answer brings the rest back. */
+export const MAX_PERSISTED_ITEMS_PER_FOLDER = 200;
+
+/**
+ * Only the fields a sidebar row paints with. `url` can be a signed link, so it
+ * never reaches storage; `metadata` keeps only the page emoji the row shows.
+ */
+const compactItem = (item: TreeItem): TreeItem => {
+ const emoji = item.metadata?.emoji;
+ return {
+ createdAt: item.createdAt,
+ fileId: item.fileId,
+ fileType: item.fileType,
+ id: item.id,
+ isFolder: item.isFolder,
+ metadata: emoji ? { emoji } : undefined,
+ name: item.name,
+ parentId: item.parentId,
+ size: item.size,
+ slug: item.slug,
+ sourceType: item.sourceType,
+ url: '',
+ userId: item.userId,
+ visibility: item.visibility,
+ };
+};
+
+/**
+ * The visible part of the tree, bounded. Collapsed folders are left out: their
+ * rows would be a second, unrefreshed copy the next expand has to refetch anyway.
+ */
+export const buildLibraryTreeSnapshot = (
+ children: Record<string, TreeItem[]>,
+ expanded: Record<string, boolean>,
+): LibraryTreeSnapshot | undefined => {
+ if (!children['']) return undefined;
+
+ const snapshot: LibraryTreeSnapshot = { children: {}, expanded: [] };
+ const queue = [''];
+ let folders = 0;
+
+ while (queue.length > 0 && folders < MAX_PERSISTED_FOLDERS) {
+ const folderId = queue.shift()!;
+ const items = children[folderId];
+ if (!items || folderId in snapshot.children) continue;
+
+ const kept = items.slice(0, MAX_PERSISTED_ITEMS_PER_FOLDER);
+ snapshot.children[folderId] = kept.map(compactItem);
+ if (folderId) snapshot.expanded.push(folderId);
+ folders += 1;
+
+ for (const item of kept) {
+ if (item.isFolder && expanded[item.id] && children[item.id]) queue.push(item.id);
+ }
+ }
+
+ return snapshot;
+};
+
+/**
+ * The library sidebar tree, one persisted row per library. The tree store keeps
+ * its own `children` / `expanded` as the rendered state (its optimistic moves and
+ * explorer reconciles write there); this replica only carries the last confirmed
+ * view across reloads, partitioned by user + workspace like every replica.
+ */
+export const libraryTreeResource = defineReplica<{ libraryId: string }, LibraryTreeSnapshot>({
+ key: ({ libraryId }) => libraryId,
+ name: 'libraryTree',
+ persist: { maxEntries: 20 },
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/tree/store.ts b/src/store/tree/store.ts
index 763db621fdb..b16cdb98f30 100644
--- a/src/store/tree/store.ts
+++ b/src/store/tree/store.ts
@@ -3,6 +3,7 @@ import { createWithEqualityFn } from 'zustand/traditional';
import type { StateCreator } from 'zustand/vanilla';
import { useFileStore } from '@/store/file';
+import { RESOURCE_LIST_KEY } from '@/store/file/slices/resource/projection';
import { createDevtools } from '../middleware/createDevtools';
import { flattenActions } from '../utils/flattenActions';
@@ -22,20 +23,34 @@ export const useTreeStore = createWithEqualityFn<TreeState>()(devtools(createSto
// --- Module-level subscription: Explorer → Tree ---
let prevResourceList: unknown[] = [];
let prevQueryParamsRef: unknown = null;
+let prevPendingCount = 0;
useFileStore.subscribe((state) => {
const { resourceList, queryParams } = state;
- if (resourceList === prevResourceList && queryParams === prevQueryParamsRef) return;
+ // A settled delete leaves `resourceList` as it was (the overlay already
+ // removed the row); the drop in pending overlays is what confirms it.
+ const pendingCount = state.resourceListReplica?.entries[RESOURCE_LIST_KEY]?.pending.length ?? 0;
+ if (
+ resourceList === prevResourceList &&
+ queryParams === prevQueryParamsRef &&
+ pendingCount === prevPendingCount
+ )
+ return;
prevResourceList = resourceList;
prevQueryParamsRef = queryParams;
+ prevPendingCount = pendingCount;
const { knowledgeBaseId } = useTreeStore.getState();
if (!queryParams || queryParams.libraryId !== knowledgeBaseId) return;
if (queryParams.q) return;
+ // `toTreeItemFromResource` drops `_optimistic`, so decide here whether the
+ // list is server-confirmed: only then may the tree persist it.
+ const confirmed = pendingCount === 0 && !resourceList.some((item) => item._optimistic);
const parentKey = queryParams.parentId ?? '';
useTreeStore.getState().reconcile(
parentKey,
resourceList.map((item) => toTreeItemFromResource(item)),
+ { confirmed },
);
});
diff --git a/src/store/tree/types.ts b/src/store/tree/types.ts
index 96e84a04dc7..323f8b06be8 100644
--- a/src/store/tree/types.ts
+++ b/src/store/tree/types.ts
@@ -1,5 +1,8 @@
+import type { ReplicaState } from '@/libs/replica';
import type { StoreHandle } from '@/store/utils/optimisticEngine';
+import type { LibraryTreeSnapshot } from './projection';
+
export interface TreeItem {
/**
* Row creation time, so the sidebar can order a folder newest-first like the
@@ -52,6 +55,9 @@ export interface TreeState extends TreeDataState {
errors: Record<string, unknown>;
expandAncestors: (folderIds: string[]) => Promise<void>;
expanded: Record<string, boolean>;
+ /** Drop the open library's persisted tree (a server-side bulk delete, see `forgetSnapshot`). */
+ forgetLibrary: (knowledgeBaseId: string) => void;
+ forgetSnapshot: () => void;
// actions
init: (knowledgeBaseId: string) => void;
@@ -59,10 +65,18 @@ export interface TreeState extends TreeDataState {
loadChildren: (folderId: string) => Promise<void>;
moveItem: (itemId: string, fromParent: string, toParent: string) => Promise<void>;
moveItems: (itemIds: string[], fromParent: string, toParent: string) => Promise<void>;
- reconcile: (folderId: string, items: TreeItem[]) => void;
+ /**
+ * Read the library's persisted tree into `snapshotMap` so the next `init`
+ * paints it on its first frame. Called from the route loader.
+ */
+ preHydrate: (knowledgeBaseId: string) => Promise<boolean>;
+ /** `confirmed: false` renders the rows without persisting them (pending explorer overlays). */
+ reconcile: (folderId: string, items: TreeItem[], options?: { confirmed?: boolean }) => void;
removeItems: (itemIds: string[], parentId: string) => Promise<void>;
renameItem: (itemId: string, parentId: string, newName: string) => Promise<void>;
reset: () => void;
revalidate: (folderId: string) => Promise<void>;
+ snapshotMap: Record<string, LibraryTreeSnapshot>;
+ snapshotReplica: ReplicaState<LibraryTreeSnapshot>;
toggle: (folderId: string) => void;
}