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.

πŸ› fix(resource): settle tree moves, create from sidebar "+" at root (#19047)

Rdmclin24e2b3230c050
diff --git a/src/features/ResourceLibrary/Layout/Header/index.tsx b/src/features/ResourceLibrary/Layout/Header/index.tsx
index 59513f26008..b1f40c4970d 100644
--- a/src/features/ResourceLibrary/Layout/Header/index.tsx
+++ b/src/features/ResourceLibrary/Layout/Header/index.tsx
@@ -31,10 +31,14 @@ const Header = memo(() => {
content area shows. The Explorer toolbar carries the same actions, but
it is covered as soon as a page or file is opened, which left no way
to add or find anything without backing out of the document first.
+
+ This "+" sits beside the library name, so it creates at the library's
+ root rather than in whatever folder the URL happens to be in; each
+ folder row carries its own "+" for creating inside that folder.
*/}
<Flexbox horizontal align={'center'} gap={8} paddingBlock={'0 8px'} paddingInline={8}>
<LibrarySearchBar />
- <AddButton iconOnly />
+ <AddButton iconOnly rootLevel />
</Flexbox>
</>
);
diff --git a/src/features/ResourceManager/DndContextWrapper.tsx b/src/features/ResourceManager/DndContextWrapper.tsx
index 1ad1b46197e..56f36f9b4fa 100644
--- a/src/features/ResourceManager/DndContextWrapper.tsx
+++ b/src/features/ResourceManager/DndContextWrapper.tsx
@@ -160,11 +160,15 @@ export const DndContextWrapper = memo<PropsWithChildren>(({ children }) => {
? treeState.moveItems(itemsToMove, fromParent, toParent)
: treeState.moveItem(drag.id, fromParent, toParent);
- movePromise.catch(() => {
- toast.error(t('FileManager.actions.moveError'));
- });
-
- toast.success(t('FileManager.actions.moveSuccess'));
+ // Report once the server has the move: the tree's optimistic rows are
+ // not proof it landed, and a rejected move must not read as success.
+ movePromise
+ .then(() => {
+ toast.success(t('FileManager.actions.moveSuccess'));
+ })
+ .catch(() => {
+ toast.error(t('FileManager.actions.moveError'));
+ });
if (isDraggingSelection) {
setSelectedFileIds([]);
diff --git a/src/features/ResourceManager/components/Header/AddButton.tsx b/src/features/ResourceManager/components/Header/AddButton.tsx
index 6cca4fad33a..58a1b9a8061 100644
--- a/src/features/ResourceManager/components/Header/AddButton.tsx
+++ b/src/features/ResourceManager/components/Header/AddButton.tsx
@@ -20,6 +20,7 @@ import { useTopLevelFileUpload } from '@/features/ResourceManager/hooks/useTopLe
import { useResourceManagerStore } from '@/features/ResourceManager/store';
import { usePermission } from '@/hooks/usePermission';
import { useFileStore } from '@/store/file';
+import { useTreeStore } from '@/store/tree';
import { FilesTabs } from '@/types/files';
import useNotionImport from './hooks/useNotionImport';
@@ -51,9 +52,16 @@ interface AddButtonProps {
* labelled primary button used in the Explorer header.
*/
iconOnly?: boolean;
+ /**
+ * Create and upload at the library's top level instead of the folder the
+ * URL is currently in. The sidebar toolbar sits beside the library name, so
+ * its entries read as library-level; creating inside a specific folder is
+ * what that folder row's own "+" (`FolderAddButton`) is for.
+ */
+ rootLevel?: boolean;
}
-const AddButton = ({ iconOnly }: AddButtonProps = {}) => {
+const AddButton = ({ iconOnly, rootLevel }: AddButtonProps = {}) => {
const { t } = useTranslation('file');
// Several instances can be mounted at once (Explorer header, sidebar toolbar,
// empty state); a fixed id would make every "Upload folder" label open the
@@ -62,23 +70,40 @@ const AddButton = ({ iconOnly }: AddButtonProps = {}) => {
const uploadFolderWithStructure = useFileStore((s) => s.uploadFolderWithStructure);
const createResourceAndSync = useFileStore((s) => s.createResourceAndSync);
const [menuOpen, setMenuOpen] = useState(false);
- const currentFolderId = useCurrentFolderId();
+ const urlFolderId = useCurrentFolderId();
+ const currentFolderId = rootLevel ? null : urlFolderId;
const { allowed: canCreate, reason } = usePermission('create_content');
- const uploadTopLevel = useTopLevelFileUpload();
+ const uploadTopLevel = useTopLevelFileUpload({ rootLevel });
// TODO: Migrate Notion import to use createResource
// Keep old functions temporarily for components not yet migrated
const createDocument = useFileStore((s) => s.createDocument);
- const [libraryId, category, setCategory, setCurrentViewItemId, setMode, setPendingRenameItemId] =
- useResourceManagerStore((s) => [
- s.libraryId,
- s.category,
- s.setCategory,
- s.setCurrentViewItemId,
- s.setMode,
- s.setPendingRenameItemId,
- ]);
+ const [
+ libraryId,
+ category,
+ setCategory,
+ setCurrentViewItemId,
+ setMode,
+ setPendingRenameItemId,
+ setPendingTreeRenameItemId,
+ ] = useResourceManagerStore((s) => [
+ s.libraryId,
+ s.category,
+ s.setCategory,
+ s.setCurrentViewItemId,
+ s.setMode,
+ s.setPendingRenameItemId,
+ s.setPendingTreeRenameItemId,
+ ]);
+
+ // The sidebar tree only mirrors the folder the Explorer is showing, so a
+ // root-level create made while a folder is open has to refresh the root
+ // itself for the new row to appear.
+ const revealRoot = useCallback(() => {
+ if (!rootLevel) return;
+ void useTreeStore.getState().revalidate('');
+ }, [rootLevel]);
const handleOpenPageEditor = useCallback(async () => {
// Navigate to "All" category first if not already there. The home
@@ -97,6 +122,7 @@ const AddButton = ({ iconOnly }: AddButtonProps = {}) => {
sourceType: DERIVED_DOCUMENT_SOURCE_TYPE,
title: untitledTitle,
});
+ revealRoot();
// Switch to page view mode with real ID
setCurrentViewItemId(realId);
@@ -106,6 +132,7 @@ const AddButton = ({ iconOnly }: AddButtonProps = {}) => {
createResourceAndSync,
currentFolderId,
libraryId,
+ revealRoot,
setCategory,
setCurrentViewItemId,
setMode,
@@ -120,19 +147,24 @@ const AddButton = ({ iconOnly }: AddButtonProps = {}) => {
// 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_FILE_TYPE &&
- (item.parentId ?? null) === (currentFolderId ?? null),
- );
+ // Unique "Untitled N" among the sibling folders. At the root the tree's
+ // own root cache is the reliable sibling list β€” the Explorer may be
+ // showing a different folder entirely.
+ const siblingFolderNames = rootLevel
+ ? (useTreeStore.getState().children[''] ?? [])
+ .filter((item) => item.isFolder)
+ .map((item) => item.name)
+ : (useFileStore.getState().resourceList || [])
+ .filter(
+ (item) =>
+ item.fileType === CUSTOM_FOLDER_FILE_TYPE &&
+ (item.parentId ?? null) === (currentFolderId ?? null),
+ )
+ .map((folder) => folder.name);
// Generate unique folder name
const baseName = t('pageList.untitled');
- const existingNames = new Set(foldersAtSameLevel.map((folder) => folder.name));
+ const existingNames = new Set(siblingFolderNames);
let uniqueName = baseName;
let counter = 1;
@@ -152,8 +184,15 @@ const AddButton = ({ iconOnly }: AddButtonProps = {}) => {
title: uniqueName,
});
- // Trigger auto-rename with the real ID (after sync completes)
- setPendingRenameItemId(realId);
+ // Trigger auto-rename with the real ID (after sync completes). The
+ // sidebar's create renames inline in the tree row, where the user
+ // clicked; the Explorer's create renames in its own list.
+ if (rootLevel) {
+ revealRoot();
+ setPendingTreeRenameItemId(realId);
+ } else {
+ setPendingRenameItemId(realId);
+ }
} catch (error) {
toast.error(t('header.actions.createFolderError'));
console.error('Failed to create folder:', error);
@@ -163,8 +202,11 @@ const AddButton = ({ iconOnly }: AddButtonProps = {}) => {
createResourceAndSync,
currentFolderId,
libraryId,
+ revealRoot,
+ rootLevel,
setCategory,
setPendingRenameItemId,
+ setPendingTreeRenameItemId,
t,
]);
@@ -172,12 +214,14 @@ const AddButton = ({ iconOnly }: AddButtonProps = {}) => {
createDocument,
currentFolderId,
libraryId,
+ refetchResources: rootLevel ? async () => revealRoot() : undefined,
t,
});
const { handleFolderUpload } = useUploadFolder({
currentFolderId,
libraryId,
+ onUploaded: revealRoot,
t,
uploadFolderWithStructure,
});
@@ -222,6 +266,7 @@ const AddButton = ({ iconOnly }: AddButtonProps = {}) => {
beforeUpload={async (file) => {
setMenuOpen(false);
await uploadTopLevel([file]);
+ revealRoot();
return false;
}}
>
@@ -260,6 +305,7 @@ const AddButton = ({ iconOnly }: AddButtonProps = {}) => {
handleOpenPageEditor,
handleOpenNotionGuide,
libraryId,
+ revealRoot,
uploadTopLevel,
t,
],
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/index.tsx b/src/features/ResourceManager/components/LibraryHierarchy/index.tsx
index 907a20910b2..18830e17f6f 100644
--- a/src/features/ResourceManager/components/LibraryHierarchy/index.tsx
+++ b/src/features/ResourceManager/components/LibraryHierarchy/index.tsx
@@ -12,7 +12,6 @@ import AsyncBoundary from '@/components/AsyncBoundary';
import { useFolderPath } from '@/features/ResourceManager/hooks/useFolderPath';
import { useResourceManagerStore } from '@/features/ResourceManager/store';
import { useFileStore } from '@/store/file';
-import type { TreeItem } from '@/store/tree';
import { useTreeStore } from '@/store/tree';
import AddButton from '../Header/AddButton';
@@ -21,13 +20,7 @@ import { HierarchyNode } from './HierarchyNode';
import SearchResults from './SearchResults';
import { resolveHierarchySelectedKey } from './selection';
import TreeSkeleton from './TreeSkeleton';
-
-interface VisibleNode {
- item: TreeItem;
- key: string;
- level: number;
- parentKey: string;
-}
+import { buildVisibleNodes } from './visibleNodes';
const LibraryHierarchy = memo(() => {
const { t } = useTranslation('file');
@@ -66,21 +59,7 @@ const LibraryHierarchy = memo(() => {
const isLoading = status[''] === 'loading';
- const visibleNodes = useMemo(() => {
- const result: VisibleNode[] = [];
-
- const walk = (parentKey: string, level: number) => {
- for (const node of children[parentKey] ?? []) {
- result.push({ item: node, key: node.id, level, parentKey });
- if (node.isFolder && expanded[node.id]) {
- walk(node.id, level + 1);
- }
- }
- };
-
- walk('', 0);
- return result;
- }, [children, expanded]);
+ const visibleNodes = useMemo(() => buildVisibleNodes(children, expanded), [children, expanded]);
const selectedKey = resolveHierarchySelectedKey({ currentFolderSlug, currentViewItemId });
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/visibleNodes.test.ts b/src/features/ResourceManager/components/LibraryHierarchy/visibleNodes.test.ts
new file mode 100644
index 00000000000..e26dd56fef5
--- /dev/null
+++ b/src/features/ResourceManager/components/LibraryHierarchy/visibleNodes.test.ts
@@ -0,0 +1,42 @@
+import { CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';
+import { describe, expect, it } from 'vitest';
+
+import { toTreeItem } from '@/store/tree';
+
+import { buildVisibleNodes } from './visibleNodes';
+
+const folder = toTreeItem({ fileType: CUSTOM_FOLDER_FILE_TYPE, id: 'folder', name: 'test' });
+const nested = toTreeItem({ fileType: CUSTOM_FOLDER_FILE_TYPE, id: 'nested', name: 'inner' });
+const docA = toTreeItem({ fileType: 'custom/document', id: 'doc-a', name: 'A' });
+const docB = toTreeItem({ fileType: 'custom/document', id: 'doc-b', name: 'B' });
+
+describe('buildVisibleNodes', () => {
+ it('walks expanded folders depth first with their level and parent key', () => {
+ const nodes = buildVisibleNodes(
+ { '': [folder, docB], 'folder': [nested, docA], 'nested': [] },
+ { folder: true },
+ );
+
+ expect(nodes.map((n) => [n.key, n.level, n.parentKey])).toEqual([
+ ['folder', 0, ''],
+ ['nested', 1, 'folder'],
+ ['doc-a', 1, 'folder'],
+ ['doc-b', 0, ''],
+ ]);
+ });
+
+ it('skips the children of a collapsed folder', () => {
+ const nodes = buildVisibleNodes({ '': [folder], 'folder': [docA] }, {});
+
+ expect(nodes.map((n) => n.key)).toEqual(['folder']);
+ });
+
+ it('renders a row that two folder caches both list only once', () => {
+ // Optimistic move put doc-a under the folder while the Explorer's
+ // reconcile still lists it at the root.
+ const nodes = buildVisibleNodes({ '': [folder, docA], 'folder': [docA] }, { folder: true });
+
+ expect(nodes.map((n) => n.key)).toEqual(['folder', 'doc-a']);
+ expect(nodes.filter((n) => n.key === 'doc-a')).toHaveLength(1);
+ });
+});
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/visibleNodes.ts b/src/features/ResourceManager/components/LibraryHierarchy/visibleNodes.ts
new file mode 100644
index 00000000000..a86e687c04f
--- /dev/null
+++ b/src/features/ResourceManager/components/LibraryHierarchy/visibleNodes.ts
@@ -0,0 +1,42 @@
+import type { TreeItem } from '@/store/tree';
+
+export interface VisibleNode {
+ item: TreeItem;
+ key: string;
+ level: number;
+ parentKey: string;
+}
+
+/**
+ * Flattens the expanded tree into the rows the virtual list renders, depth
+ * first from the root.
+ *
+ * A node id renders at most once. `children` is a per-folder cache that the
+ * Explorer reconciles independently of the tree's own optimistic moves, so the
+ * same row can briefly sit under two folders while a move settles. Two rows
+ * sharing one React key make the virtual list paint them on top of each
+ * other, so the first occurrence wins and the rest are skipped until the
+ * caches agree again.
+ */
+export const buildVisibleNodes = (
+ children: Record<string, TreeItem[]>,
+ expanded: Record<string, boolean>,
+): VisibleNode[] => {
+ const result: VisibleNode[] = [];
+ const seen = new Set<string>();
+
+ const walk = (parentKey: string, level: number) => {
+ for (const node of children[parentKey] ?? []) {
+ if (seen.has(node.id)) continue;
+ seen.add(node.id);
+
+ result.push({ item: node, key: node.id, level, parentKey });
+ if (node.isFolder && expanded[node.id]) {
+ walk(node.id, level + 1);
+ }
+ }
+ };
+
+ walk('', 0);
+ return result;
+};
diff --git a/src/features/ResourceManager/hooks/useTopLevelFileUpload.ts b/src/features/ResourceManager/hooks/useTopLevelFileUpload.ts
index dfd90840af4..b55873900ae 100644
--- a/src/features/ResourceManager/hooks/useTopLevelFileUpload.ts
+++ b/src/features/ResourceManager/hooks/useTopLevelFileUpload.ts
@@ -21,9 +21,18 @@ import { useFileStore } from '@/store/file';
* - **personal mode** (no `activeWorkspaceId`): also `undefined`; personal
* rows have no visibility column semantics.
*/
-export const useTopLevelFileUpload = () => {
+interface UseTopLevelFileUploadOptions {
+ /**
+ * Upload to the library's root instead of the folder the URL is in (the
+ * sidebar toolbar's library-level "+").
+ */
+ rootLevel?: boolean;
+}
+
+export const useTopLevelFileUpload = ({ rootLevel }: UseTopLevelFileUploadOptions = {}) => {
const activeWorkspaceId = useActiveWorkspaceId();
- const currentFolderId = useCurrentFolderId();
+ const urlFolderId = useCurrentFolderId();
+ const currentFolderId = rootLevel ? null : urlFolderId;
const libraryId = useResourceManagerStore((s) => s.libraryId);
const listVisibility = useResourceManagerStore((s) => s.listVisibility);
const pushDockFileList = useFileStore((s) => s.pushDockFileList);
diff --git a/src/store/file/slices/resource/action.test.ts b/src/store/file/slices/resource/action.test.ts
index fb403fb731c..e0f18416eb9 100644
--- a/src/store/file/slices/resource/action.test.ts
+++ b/src/store/file/slices/resource/action.test.ts
@@ -2,14 +2,16 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { initialState } from '@/store/file/initialState';
import { useFileStore } from '@/store/file/store';
-import type { ResourceItem } from '@/types/resource';
+import type { CreateDocumentParams, ResourceItem } from '@/types/resource';
-const { mockMoveResource } = vi.hoisted(() => ({
+const { mockCreateResource, mockMoveResource } = vi.hoisted(() => ({
+ mockCreateResource: vi.fn(),
mockMoveResource: vi.fn(),
}));
vi.mock('@/services/resource', () => ({
resourceService: {
+ createResource: mockCreateResource,
moveResource: mockMoveResource,
},
}));
@@ -139,3 +141,68 @@ describe('resource actions', () => {
});
});
});
+
+describe('createResourceAndSync list placement', () => {
+ const createParams = (parentId: string | null | undefined): CreateDocumentParams => ({
+ content: '',
+ fileType: 'custom/document',
+ knowledgeBaseId: 'kb-1',
+ parentId: parentId ?? undefined,
+ sourceType: 'document',
+ title: 'Untitled',
+ });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ useFileStore.setState(initialState);
+ });
+
+ it('keeps a root-level create out of the list while a folder is open', async () => {
+ const folderRow = createResource({ id: 'doc-in-folder', parentId: 'folder-a' });
+ useFileStore.setState({
+ queryParams: { libraryId: 'kb-1', parentId: 'folder-a-slug' },
+ resourceList: [folderRow],
+ resourceMap: new Map([[folderRow.id, folderRow]]),
+ });
+ mockCreateResource.mockResolvedValue(
+ createResource({ id: 'doc-root', knowledgeBaseId: 'kb-1', parentId: null }),
+ );
+
+ const id = await useFileStore.getState().createResourceAndSync(createParams(null));
+
+ expect(id).toBe('doc-root');
+ expect(useFileStore.getState().resourceList.map((item) => item.id)).toEqual(['doc-in-folder']);
+ expect(useFileStore.getState().resourceMap.has('doc-root')).toBe(true);
+ });
+
+ it('keeps a create inside a folder out of the list while the root is open', async () => {
+ const rootRow = createResource({ id: 'doc-root', parentId: null });
+ useFileStore.setState({
+ queryParams: { libraryId: 'kb-1', parentId: null },
+ resourceList: [rootRow],
+ resourceMap: new Map([[rootRow.id, rootRow]]),
+ });
+ mockCreateResource.mockResolvedValue(
+ createResource({ id: 'doc-nested', knowledgeBaseId: 'kb-1', parentId: 'folder-a' }),
+ );
+
+ await useFileStore.getState().createResourceAndSync(createParams('folder-a'));
+
+ expect(useFileStore.getState().resourceList.map((item) => item.id)).toEqual(['doc-root']);
+ });
+
+ it('still lists a create in the open folder when that folder is addressed by slug and not cached', async () => {
+ useFileStore.setState({
+ queryParams: { libraryId: 'kb-1', parentId: 'folder-a-slug' },
+ resourceList: [],
+ resourceMap: new Map(),
+ });
+ mockCreateResource.mockResolvedValue(
+ createResource({ id: 'doc-new', knowledgeBaseId: 'kb-1', parentId: 'folder-a' }),
+ );
+
+ await useFileStore.getState().createResourceAndSync(createParams('folder-a'));
+
+ expect(useFileStore.getState().resourceList.map((item) => item.id)).toEqual(['doc-new']);
+ });
+});
diff --git a/src/store/file/slices/resource/action.ts b/src/store/file/slices/resource/action.ts
index 7ff0700ac76..fd91b8acbac 100644
--- a/src/store/file/slices/resource/action.ts
+++ b/src/store/file/slices/resource/action.ts
@@ -195,6 +195,35 @@ export class ResourceActionImpl {
);
};
+ /**
+ * The definite negative to `#isResourceVisibleInCurrentQuery`: that check
+ * says "no" whenever the open folder is addressed by slug and the parent is
+ * not cached, so a create must not gate on it or a fresh load inside a
+ * folder would never show the row it just created. This only reports rows
+ * that certainly belong elsewhere β€” another library, the root while a folder
+ * is open (or the reverse), or a cached parent whose slug is not the open one.
+ */
+ #isResourceOutsideCurrentQuery = (resource: ResourceItem): boolean => {
+ const { queryParams, resourceMap } = this.#get();
+
+ if (!queryParams) return false;
+
+ if (
+ queryParams.libraryId !== undefined &&
+ (resource.knowledgeBaseId ?? undefined) !== queryParams.libraryId
+ ) {
+ return true;
+ }
+
+ const inFolderView = queryParams.parentId != null;
+ if (!inFolderView) return !!resource.parentId;
+ if (!resource.parentId) return true;
+ if (resource.parentId === queryParams.parentId) return false;
+
+ const parentResource = resourceMap.get(resource.parentId);
+ return !!parentResource && parentResource.slug !== queryParams.parentId;
+ };
+
#isResourceVisibleInCurrentQuery = (resource: ResourceItem): boolean => {
const { queryParams, resourceMap } = this.#get();
@@ -346,9 +375,10 @@ export class ResourceActionImpl {
const optimisticResource = this.#createOptimisticResource(params);
const syncEngine = this.#getSyncEngine();
const tx = syncEngine.createTransaction(`createResource(${optimisticResource.id})`);
+ const showInList = !this.#isResourceOutsideCurrentQuery(optimisticResource);
tx.set((draft) => {
- draft.resourceList.unshift(optimisticResource);
+ if (showInList) draft.resourceList.unshift(optimisticResource);
draft.resourceMap.set(optimisticResource.id, optimisticResource);
draft.syncingIds.add(optimisticResource.id);
});
@@ -373,9 +403,13 @@ export class ResourceActionImpl {
const optimisticResource = this.#createOptimisticResource(params);
const syncEngine = this.#getSyncEngine();
const tx = syncEngine.createTransaction(`createResourceAndSync(${optimisticResource.id})`);
+ // A row created for another folder (sidebar "+" at the root while a folder
+ // is open, a folder row's "+" while the root is open) must not surface in
+ // the list the Explorer is currently showing.
+ const showInList = !this.#isResourceOutsideCurrentQuery(optimisticResource);
tx.set((draft) => {
- draft.resourceList.unshift(optimisticResource);
+ if (showInList) draft.resourceList.unshift(optimisticResource);
draft.resourceMap.set(optimisticResource.id, optimisticResource);
draft.syncingIds.add(optimisticResource.id);
});
diff --git a/src/store/tree/actions.test.ts b/src/store/tree/actions.test.ts
index 06857db99fe..891a22f7e0d 100644
--- a/src/store/tree/actions.test.ts
+++ b/src/store/tree/actions.test.ts
@@ -5,17 +5,21 @@ import { toTreeItem, TreeActionImpl } from './actions';
import type { TreeState } from './types';
const {
+ mockDeleteResources,
mockGetKnowledgeItems,
mockRefreshFileList,
mockResourceMove,
mockStoreMove,
mockSwrMutate,
+ mockUpdateResource,
} = vi.hoisted(() => ({
+ mockDeleteResources: vi.fn(),
mockGetKnowledgeItems: vi.fn(),
mockRefreshFileList: vi.fn(),
mockResourceMove: vi.fn(),
mockStoreMove: vi.fn(),
mockSwrMutate: vi.fn(),
+ mockUpdateResource: vi.fn(),
}));
vi.mock('swr', () => ({ mutate: mockSwrMutate }));
@@ -34,7 +38,9 @@ const fileStoreState = {
vi.mock('@/services/resource', () => ({
resourceService: {
+ deleteResources: mockDeleteResources,
moveResource: mockResourceMove,
+ updateResource: mockUpdateResource,
},
}));
@@ -157,6 +163,59 @@ describe('TreeActionImpl folder key resolution', () => {
expect(state.children['f13650aa']).toBeUndefined();
});
+ it('reconcile resolves the slug to the loaded folder even after a stale slug entry exists', () => {
+ const state = createLoadedState();
+ // The explorer's first list for a deep-linked folder arrives before the
+ // ancestors are loaded and lands under the slug.
+ state.children['f13650aa'] = [doc];
+ const actions = new TreeActionImpl(
+ createSetter(() => state),
+ () => state,
+ );
+
+ const created = toTreeItem({ fileType: 'custom/document', id: 'docs_created', name: 'New' });
+ actions.reconcile('f13650aa', [doc, created]);
+
+ expect(state.children['docs_folder']?.map((item) => item.id)).toEqual([
+ 'docs_created',
+ 'docs_new',
+ ]);
+ // The stale slug entry is left alone; the sidebar never walks it.
+ expect(state.children['f13650aa']?.map((item) => item.id)).toEqual(['docs_new']);
+ });
+
+ it('reconcile drops rows whose parentId points at another folder', () => {
+ const state = createLoadedState();
+ const actions = new TreeActionImpl(
+ createSetter(() => state),
+ () => state,
+ );
+ const own = toTreeItem({
+ fileType: 'custom/document',
+ id: 'docs_own',
+ name: 'Own',
+ parentId: 'docs_folder',
+ });
+ const phantom = toTreeItem({
+ fileType: 'custom/document',
+ id: 'docs_elsewhere',
+ name: 'Created for another folder',
+ parentId: 'docs_other',
+ });
+
+ actions.reconcile('f13650aa', [doc, own, phantom]);
+ expect(state.children['docs_folder']?.map((item) => item.id)).toEqual(['docs_own', 'docs_new']);
+
+ const rootPhantom = toTreeItem({
+ fileType: 'custom/document',
+ id: 'docs_nested',
+ name: 'Nested',
+ parentId: 'docs_folder',
+ });
+ actions.reconcile('', [folder, doc, rootPhantom]);
+ expect(state.children['']?.map((item) => item.id)).toEqual(['docs_folder', 'docs_new']);
+ });
+
it('reconcile keeps the root key and unknown keys untouched', () => {
const state = createLoadedState();
const actions = new TreeActionImpl(
@@ -192,6 +251,64 @@ describe('TreeActionImpl folder key resolution', () => {
expect(matcher('resource:search')).toBe(false);
});
+ it('a revalidate requested during an in-flight root load runs once that load settles', async () => {
+ const state = createState();
+ const actions = new TreeActionImpl(
+ createSetter(() => state),
+ () => state,
+ );
+ // The initial root fetch captured its snapshot before the sidebar "+"
+ // created a row; the refresh must not be dropped on the floor.
+ let resolveInitial!: (value: { items: unknown[] }) => void;
+ const initial = new Promise<{ items: unknown[] }>((resolve) => {
+ resolveInitial = resolve;
+ });
+ const created = { fileType: 'custom/document', id: 'docs_created', name: 'New', slug: null };
+ mockGetKnowledgeItems.mockReturnValueOnce(initial).mockResolvedValue({ items: [created] });
+
+ const load = actions.loadChildren('');
+ expect(state.status['']).toBe('loading');
+
+ await actions.revalidate('');
+ await actions.revalidate('');
+ expect(mockGetKnowledgeItems).toHaveBeenCalledTimes(1);
+
+ resolveInitial({ items: [] });
+ await load;
+ await vi.waitFor(() => {
+ expect(state.children['']?.map((item) => item.id)).toEqual(['docs_created']);
+ });
+ // Both queued requests collapsed into a single follow-up fetch.
+ expect(mockGetKnowledgeItems).toHaveBeenCalledTimes(2);
+ expect(state.status['']).toBe('idle');
+ });
+
+ it('a revalidate requested during an in-flight revalidate follows it instead of racing it', async () => {
+ const state = createState();
+ const actions = new TreeActionImpl(
+ createSetter(() => state),
+ () => state,
+ );
+ let resolveFirst!: (value: { items: unknown[] }) => void;
+ const first = new Promise<{ items: unknown[] }>((resolve) => {
+ resolveFirst = resolve;
+ });
+ const fresh = { fileType: 'custom/document', id: 'docs_fresh', name: 'Fresh', slug: null };
+ mockGetKnowledgeItems.mockReturnValueOnce(first).mockResolvedValue({ items: [fresh] });
+
+ const running = actions.revalidate('folder-a');
+ expect(state.status['folder-a']).toBe('revalidating');
+ await actions.revalidate('folder-a');
+ expect(mockGetKnowledgeItems).toHaveBeenCalledTimes(1);
+
+ resolveFirst({ items: [] });
+ await running;
+ await vi.waitFor(() => {
+ expect(state.children['folder-a']?.map((item) => item.id)).toEqual(['docs_fresh']);
+ });
+ expect(mockGetKnowledgeItems).toHaveBeenCalledTimes(2);
+ });
+
it('revalidate stores the refetched children under the folder id when addressed by slug', async () => {
const state = createLoadedState();
const actions = new TreeActionImpl(
@@ -209,3 +326,178 @@ describe('TreeActionImpl folder key resolution', () => {
expect(state.status['docs_folder']).toBe('idle');
});
});
+
+describe('TreeActionImpl optimistic moves', () => {
+ const folder = toTreeItem({ fileType: CUSTOM_FOLDER_FILE_TYPE, id: 'folder-test', name: 'test' });
+ const docA = toTreeItem({ fileType: 'custom/document', id: 'doc-a', name: 'A' });
+ const docB = toTreeItem({ fileType: 'custom/document', id: 'doc-b', name: 'B' });
+
+ // A move that never settles is the bug: the drop handler's promise hangs, the
+ // sidebar never revalidates, and every later mutation on the same folders
+ // queues behind the stuck one.
+ const withTimeout = <T>(promise: Promise<T>, ms = 200) =>
+ Promise.race([
+ promise,
+ new Promise<never>((_, reject) => {
+ setTimeout(() => reject(new Error(`did not settle within ${ms}ms`)), ms);
+ }),
+ ]);
+
+ const createTree = () => {
+ const state = createState();
+ state.children = { '': [folder, docA, docB], 'folder-test': [] };
+ const actions = new TreeActionImpl(
+ createSetter(() => state),
+ () => state,
+ );
+ return { actions, state };
+ };
+
+ beforeEach(() => {
+ mockRefreshFileList.mockReset();
+ mockResourceMove.mockReset();
+ mockStoreMove.mockReset();
+ fileStoreState.resourceMap = new Map();
+ mockResourceMove.mockResolvedValue({});
+ mockRefreshFileList.mockResolvedValue(undefined);
+ });
+
+ it('moveItem settles, persists, and revalidates both parents when the node is cached', async () => {
+ const { actions, state } = createTree();
+ const revalidateSpy = vi.spyOn(actions, 'revalidate').mockResolvedValue();
+
+ await withTimeout(actions.moveItem('doc-a', '', 'folder-test'));
+
+ expect(mockResourceMove).toHaveBeenCalledWith('doc-a', 'folder-test');
+ expect(state.children['']?.map((i) => i.id)).toEqual(['folder-test', 'doc-b']);
+ expect(state.children['folder-test']?.map((i) => i.id)).toEqual(['doc-a']);
+ expect(revalidateSpy).toHaveBeenCalledWith('');
+ expect(revalidateSpy).toHaveBeenCalledWith('folder-test');
+ });
+
+ it('a second move touching the same folders still reaches the backend', async () => {
+ const { actions, state } = createTree();
+ vi.spyOn(actions, 'revalidate').mockResolvedValue();
+
+ await withTimeout(actions.moveItem('doc-a', '', 'folder-test'));
+ await withTimeout(actions.moveItem('doc-b', '', 'folder-test'));
+
+ expect(mockResourceMove).toHaveBeenCalledTimes(2);
+ expect(mockResourceMove).toHaveBeenLastCalledWith('doc-b', 'folder-test');
+ expect(state.children['']?.map((i) => i.id)).toEqual(['folder-test']);
+ expect(state.children['folder-test']?.map((i) => i.id)).toEqual(['doc-a', 'doc-b']);
+ });
+
+ it('moveItems settles and persists every cached node', async () => {
+ const { actions, state } = createTree();
+ const revalidateSpy = vi.spyOn(actions, 'revalidate').mockResolvedValue();
+
+ await withTimeout(actions.moveItems(['doc-a', 'doc-b'], '', 'folder-test'));
+
+ expect(mockResourceMove).toHaveBeenCalledTimes(2);
+ expect(state.children['']?.map((i) => i.id)).toEqual(['folder-test']);
+ expect(state.children['folder-test']?.map((i) => i.id)).toEqual(['doc-a', 'doc-b']);
+ expect(revalidateSpy).toHaveBeenCalledWith('');
+ expect(revalidateSpy).toHaveBeenCalledWith('folder-test');
+ });
+
+ it('a failed move rolls the node back and rejects', async () => {
+ const { actions, state } = createTree();
+ vi.spyOn(actions, 'revalidate').mockResolvedValue();
+ mockResourceMove.mockRejectedValue(new Error('boom'));
+
+ await expect(withTimeout(actions.moveItem('doc-a', '', 'folder-test'))).rejects.toThrow('boom');
+
+ expect(state.children['']?.map((i) => i.id)).toEqual(['folder-test', 'doc-a', 'doc-b']);
+ expect(state.children['folder-test']).toEqual([]);
+ });
+});
+
+describe('TreeActionImpl optimistic moves (destination and other mutations)', () => {
+ const folder = toTreeItem({ fileType: CUSTOM_FOLDER_FILE_TYPE, id: 'folder-test', name: 'test' });
+ const docA = toTreeItem({ fileType: 'custom/document', id: 'doc-a', name: 'A' });
+
+ const withTimeout = <T>(promise: Promise<T>, ms = 200) =>
+ Promise.race([
+ promise,
+ new Promise<never>((_, reject) => {
+ setTimeout(() => reject(new Error(`did not settle within ${ms}ms`)), ms);
+ }),
+ ]);
+
+ beforeEach(() => {
+ mockRefreshFileList.mockReset();
+ mockResourceMove.mockReset();
+ mockStoreMove.mockReset();
+ fileStoreState.resourceMap = new Map();
+ mockResourceMove.mockResolvedValue({});
+ mockRefreshFileList.mockResolvedValue(undefined);
+ });
+
+ it('leaves an unloaded destination untouched so its first expand still fetches', async () => {
+ const state = createState();
+ state.children = { '': [folder, docA] };
+ const actions = new TreeActionImpl(
+ createSetter(() => state),
+ () => state,
+ );
+ const revalidateSpy = vi.spyOn(actions, 'revalidate').mockResolvedValue();
+
+ await withTimeout(actions.moveItem('doc-a', '', 'folder-test'));
+
+ expect(state.children['']?.map((i) => i.id)).toEqual(['folder-test']);
+ expect(state.children['folder-test']).toBeUndefined();
+ expect(revalidateSpy).toHaveBeenCalledWith('folder-test');
+ });
+
+ it('does not duplicate a row the destination already lists', async () => {
+ const state = createState();
+ state.children = { '': [folder, docA], 'folder-test': [docA] };
+ const actions = new TreeActionImpl(
+ createSetter(() => state),
+ () => state,
+ );
+ vi.spyOn(actions, 'revalidate').mockResolvedValue();
+
+ await withTimeout(actions.moveItem('doc-a', '', 'folder-test'));
+
+ expect(state.children['folder-test']?.map((i) => i.id)).toEqual(['doc-a']);
+ });
+
+ it('renameItem settles and revalidates the parent', async () => {
+ const state = createState();
+ state.children = { '': [folder, docA] };
+ const actions = new TreeActionImpl(
+ createSetter(() => state),
+ () => state,
+ );
+ const revalidateSpy = vi.spyOn(actions, 'revalidate').mockResolvedValue();
+ mockUpdateResource.mockResolvedValue({});
+
+ await withTimeout(actions.renameItem('doc-a', '', 'Renamed'));
+
+ expect(mockUpdateResource).toHaveBeenCalledWith('doc-a', { name: 'Renamed' });
+ expect(state.children['']?.find((i) => i.id === 'doc-a')?.name).toBe('Renamed');
+ expect(revalidateSpy).toHaveBeenCalledWith('');
+ });
+
+ it('removeItems settles, drops the folder caches, and revalidates the parent', async () => {
+ const state = createState();
+ state.children = { '': [folder, docA], 'folder-test': [] };
+ state.expanded = { 'folder-test': true };
+ const actions = new TreeActionImpl(
+ createSetter(() => state),
+ () => state,
+ );
+ const revalidateSpy = vi.spyOn(actions, 'revalidate').mockResolvedValue();
+ mockDeleteResources.mockResolvedValue(undefined);
+
+ await withTimeout(actions.removeItems(['folder-test'], ''));
+
+ expect(mockDeleteResources).toHaveBeenCalledWith(['folder-test']);
+ expect(state.children['']?.map((i) => i.id)).toEqual(['doc-a']);
+ expect(state.children['folder-test']).toBeUndefined();
+ expect(state.expanded['folder-test']).toBeUndefined();
+ expect(revalidateSpy).toHaveBeenCalledWith('');
+ });
+});
diff --git a/src/store/tree/actions.ts b/src/store/tree/actions.ts
index 03e5ba5c75c..5f7b5765f01 100644
--- a/src/store/tree/actions.ts
+++ b/src/store/tree/actions.ts
@@ -39,6 +39,7 @@ export const toTreeItem = (item: {
id: string;
metadata?: Record<string, any> | null;
name: string;
+ parentId?: string | null;
size?: number | null;
slug?: string | null;
sourceType?: string;
@@ -52,6 +53,7 @@ export const toTreeItem = (item: {
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,
@@ -86,17 +88,37 @@ export class TreeActionImpl {
return this.#engine;
};
+ /**
+ * Folders whose refresh was requested while a fetch for them was already in
+ * flight. That fetch captured its snapshot before the change the caller is
+ * revealing (a create from the sidebar "+" during the initial root load, a
+ * move landing while the destination is still loading), so dropping the
+ * request would leave the new row out of the tree until something else
+ * refreshed it. One follow-up runs once the in-flight fetch settles; repeated
+ * requests collapse into that one.
+ */
+ #queuedRevalidate = new Set<string>();
+
+ #runQueuedRevalidate = (folderId: string) => {
+ if (!this.#queuedRevalidate.delete(folderId)) return;
+ void this.revalidate(folderId);
+ };
+
/**
* `children` is keyed by folder id, but the explorer addresses the current
* folder by whatever the URL carries β€” usually the folder slug (see
* `useFileStore.queryParams.parentId`). Writing under the slug leaves the
* sidebar (which walks by id) blind to the update, so map a slug back to the
* id of the already-loaded folder node. Unknown keys pass through unchanged.
+ *
+ * The loaded node wins over an existing `children[key]` entry: the explorer's
+ * first list for a deep-linked folder arrives before its ancestors are
+ * loaded and lands under the slug, and that stale entry must not keep every
+ * later update pinned to the slug once the folder node is known.
*/
#resolveFolderKey = (key: string): string => {
if (!key) return '';
const { children } = this.#get();
- if (children[key]) return key;
for (const items of Object.values(children)) {
const match = items.find((item) => item.isFolder && (item.id === key || item.slug === key));
if (match) return match.id;
@@ -105,6 +127,7 @@ export class TreeActionImpl {
};
init = (knowledgeBaseId: string) => {
+ this.#queuedRevalidate.clear();
this.#set(
{
children: {},
@@ -121,6 +144,7 @@ export class TreeActionImpl {
};
reset = () => {
+ this.#queuedRevalidate.clear();
this.#set(
{
children: {},
@@ -178,6 +202,7 @@ export class TreeActionImpl {
false,
'tree/loadChildren/success',
);
+ this.#runQueuedRevalidate(folderId);
} catch (error) {
if (this.#get().epoch !== epoch) return;
console.error(`Failed to load children for ${folderId}:`, error);
@@ -192,6 +217,7 @@ export class TreeActionImpl {
false,
'tree/loadChildren/error',
);
+ this.#runQueuedRevalidate(folderId);
}
};
@@ -200,7 +226,10 @@ export class TreeActionImpl {
const folderId = this.#resolveFolderKey(folderKey);
const { epoch, knowledgeBaseId, status } = this.#get();
- if (status[folderId] === 'loading') return;
+ if (status[folderId] === 'loading' || status[folderId] === 'revalidating') {
+ this.#queuedRevalidate.add(folderId);
+ return;
+ }
this.#set(
{ status: { ...this.#get().status, [folderId]: 'revalidating' } },
@@ -228,6 +257,7 @@ export class TreeActionImpl {
false,
'tree/revalidate/success',
);
+ this.#runQueuedRevalidate(folderId);
} catch {
if (this.#get().epoch !== epoch) return;
this.#set(
@@ -235,14 +265,22 @@ export class TreeActionImpl {
false,
'tree/revalidate/error',
);
+ this.#runQueuedRevalidate(folderId);
}
};
reconcile = (folderKey: string, items: TreeItem[]) => {
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
+ // open folder's id, but the row's own parentId can. Rows with no parentId
+ // are the server's and are kept as they are.
+ const scoped = items.filter(
+ (item) => item.parentId == null || item.parentId === (folderId || null),
+ );
this.#set(
{
- children: { ...this.#get().children, [folderId]: sortTreeItems(items) },
+ children: { ...this.#get().children, [folderId]: sortTreeItems(scoped) },
status: { ...this.#get().status, [folderId]: 'idle' },
},
false,
@@ -265,6 +303,21 @@ export class TreeActionImpl {
if (this.#get().epoch !== epoch) return;
};
+ /**
+ * Refresh the touched folders from the server once every queued mutation has
+ * settled, so a revalidation never overwrites another move's optimistic rows.
+ *
+ * Must run AFTER `tx.commit()` resolves, never inside `tx.onSuccess`: the
+ * engine only marks a mutation done after its onSuccess returns, so a
+ * `flush()` awaited there waits for itself. The transaction then never
+ * settled, the sidebar never revalidated, and every later mutation touching
+ * the same folders queued behind the stuck one without reaching the server.
+ */
+ #revalidateSettled = async (folderKeys: string[]) => {
+ await this.#getEngine().flush();
+ void Promise.all(folderKeys.map((key) => this.revalidate(key)));
+ };
+
moveItem = async (itemId: string, fromParent: string, toParent: string): Promise<void> => {
const { children } = this.#get();
const item = children[fromParent]?.find((i) => i.id === itemId);
@@ -291,7 +344,13 @@ export class TreeActionImpl {
draft.children[fromParent] = (draft.children[fromParent] ?? []).filter(
(i) => i.id !== itemId,
);
- draft.children[toParent] = sortTreeItems([...(draft.children[toParent] ?? []), item]);
+ // Only a loaded destination gets the row. Seeding an unloaded folder with
+ // just the moved item would make its first expand skip the fetch and show
+ // that lone row as the whole folder; the post-commit revalidate fills it.
+ const target = draft.children[toParent];
+ if (target) {
+ draft.children[toParent] = sortTreeItems([...target.filter((i) => i.id !== itemId), item]);
+ }
});
tx.mutation = async () => {
@@ -308,12 +367,8 @@ export class TreeActionImpl {
}
};
- tx.onSuccess = async () => {
- await engine.flush();
- void Promise.all([this.revalidate(fromParent), this.revalidate(toParent)]);
- };
-
await tx.commit();
+ await this.#revalidateSettled([fromParent, toParent]);
};
moveItems = async (itemIds: string[], fromParent: string, toParent: string): Promise<void> => {
@@ -329,7 +384,13 @@ export class TreeActionImpl {
draft.children[fromParent] = (draft.children[fromParent] ?? []).filter(
(i) => !idsSet.has(i.id),
);
- draft.children[toParent] = sortTreeItems([...(draft.children[toParent] ?? []), ...items]);
+ const target = draft.children[toParent];
+ if (target) {
+ draft.children[toParent] = sortTreeItems([
+ ...target.filter((i) => !idsSet.has(i.id)),
+ ...items,
+ ]);
+ }
});
tx.mutation = async () => {
@@ -359,12 +420,8 @@ export class TreeActionImpl {
}
};
- tx.onSuccess = async () => {
- await engine.flush();
- void Promise.all([this.revalidate(fromParent), this.revalidate(toParent)]);
- };
-
await tx.commit();
+ await this.#revalidateSettled([fromParent, toParent]);
};
renameItem = async (itemId: string, parentId: string, newName: string): Promise<void> => {
@@ -384,12 +441,8 @@ export class TreeActionImpl {
await useFileStore.getState().refreshFileList();
};
- tx.onSuccess = async () => {
- await engine.flush();
- void this.revalidate(parentId);
- };
-
await tx.commit();
+ await this.#revalidateSettled([parentId]);
};
removeItems = async (itemIds: string[], parentId: string): Promise<void> => {
@@ -407,18 +460,15 @@ export class TreeActionImpl {
await useFileStore.getState().refreshFileList();
};
- tx.onSuccess = async () => {
- await engine.flush();
- const expanded = { ...this.#get().expanded };
- const children = { ...this.#get().children };
- for (const id of itemIds) {
- delete expanded[id];
- delete children[id];
- }
- this.#set({ children, expanded }, false, 'tree/removeItems/cleanup');
- void this.revalidate(parentId);
- };
-
await tx.commit();
+
+ const expanded = { ...this.#get().expanded };
+ const children = { ...this.#get().children };
+ for (const id of itemIds) {
+ delete expanded[id];
+ delete children[id];
+ }
+ this.#set({ children, expanded }, false, 'tree/removeItems/cleanup');
+ await this.#revalidateSettled([parentId]);
};
}
diff --git a/src/store/tree/store.ts b/src/store/tree/store.ts
index 80982f8581c..145358b9b19 100644
--- a/src/store/tree/store.ts
+++ b/src/store/tree/store.ts
@@ -43,6 +43,7 @@ useFileStore.subscribe((state) => {
id: item.id,
metadata: item.metadata,
name: item.name,
+ parentId: item.parentId,
size: item.size,
slug: item.slug,
sourceType: item.sourceType,
diff --git a/src/store/tree/types.ts b/src/store/tree/types.ts
index 01c5f456f07..08ff2e3df95 100644
--- a/src/store/tree/types.ts
+++ b/src/store/tree/types.ts
@@ -12,6 +12,12 @@ export interface TreeItem {
isFolder: boolean;
metadata?: Record<string, any>;
name: string;
+ /**
+ * Parent folder id when the source row knows it (optimistic creates, rows the
+ * server returns with a parent). Lets `reconcile` drop a row the Explorer is
+ * holding for another folder; `undefined` means unknown and is kept.
+ */
+ parentId?: string | null;
/** Byte size for file nodes β€” drives the push modal's oversize pre-warning. */
size?: number;
slug?: string | null;