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(library): let documents with children expand in the knowledge base tree (#21991)

Arvin Xuc456dd16e790
diff --git a/apps/server/src/routers/lambda/file/knowledgeItems.ts b/apps/server/src/routers/lambda/file/knowledgeItems.ts
index c9b8e8a2b60..36f01c98c07 100644
--- a/apps/server/src/routers/lambda/file/knowledgeItems.ts
+++ b/apps/server/src/routers/lambda/file/knowledgeItems.ts
@@ -152,6 +152,7 @@ export const knowledgeItemsRouter = router({
fileId: item.fileId,
fileType: item.fileType,
finishEmbedding: status.finishEmbedding,
+ hasChildren: item.hasChildren,
id: item.id,
knowledgeBaseIds: item.knowledgeBaseIds,
metadata: item.metadata,
@@ -179,6 +180,7 @@ export const knowledgeItemsRouter = router({
fileId: item.fileId,
fileType: item.fileType,
finishEmbedding: false,
+ hasChildren: item.hasChildren,
id: item.id,
metadata: item.metadata,
name: item.name,
diff --git a/packages/database/src/repositories/knowledge/__tests__/documentChildren.test.ts b/packages/database/src/repositories/knowledge/__tests__/documentChildren.test.ts
new file mode 100644
index 00000000000..55e9d777a0b
--- /dev/null
+++ b/packages/database/src/repositories/knowledge/__tests__/documentChildren.test.ts
@@ -0,0 +1,103 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { documents, files, knowledgeBaseFiles, knowledgeBases } from '../../../schemas/file';
+import { users } from '../../../schemas/user';
+import type { LobeChatDatabase } from '../../../type';
+import { KnowledgeRepo } from '../index';
+
+const userId = 'doc-children-user';
+const otherUserId = 'doc-children-other-user';
+const kbId = 'doc-children-kb';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+let knowledgeRepo: KnowledgeRepo;
+
+const page = (id: string, extra: Partial<typeof documents.$inferInsert> = {}) => ({
+ content: id,
+ fileType: 'custom/document',
+ filename: id,
+ id,
+ knowledgeBaseId: kbId,
+ source: 'document',
+ sourceType: 'api' as const,
+ title: id,
+ totalCharCount: id.length,
+ totalLineCount: 1,
+ userId,
+ ...extra,
+});
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ knowledgeRepo = new KnowledgeRepo(serverDB, userId);
+
+ await serverDB.insert(knowledgeBases).values([{ id: kbId, name: 'KB', userId }]);
+ // Parents first: `parent_id` references `documents.id`.
+ await serverDB
+ .insert(documents)
+ .values([page('parent-doc'), page('leaf-doc'), page('file-parent-doc'), page('trash-parent')]);
+ await serverDB.insert(documents).values([
+ page('child-doc', { parentId: 'parent-doc' }),
+ page('trashed-child', { isDeleted: true, parentId: 'trash-parent' }),
+ // Another user's row can't make the caller's document expandable.
+ page('foreign-child', { knowledgeBaseId: null, parentId: 'leaf-doc', userId: otherUserId }),
+ ]);
+ await serverDB.insert(files).values([
+ {
+ fileType: 'application/pdf',
+ id: 'child-file',
+ name: 'child.pdf',
+ parentId: 'file-parent-doc',
+ size: 100,
+ url: 'child-file-url',
+ userId,
+ },
+ ]);
+ await serverDB
+ .insert(knowledgeBaseFiles)
+ .values([{ fileId: 'child-file', knowledgeBaseId: kbId, userId }]);
+});
+
+describe('KnowledgeRepo.query β€” documents with children', () => {
+ it('reports hasChildren for a document holding a document or a file', async () => {
+ const results = await knowledgeRepo.query({ knowledgeBaseId: kbId, parentId: null });
+ const byId = Object.fromEntries(results.map((item) => [item.id, item]));
+
+ expect(byId['parent-doc'].hasChildren).toBe(true);
+ expect(byId['file-parent-doc'].hasChildren).toBe(true);
+ expect(byId['leaf-doc'].hasChildren).toBe(false);
+ expect(byId['trash-parent'].hasChildren).toBe(false);
+ });
+
+ it('reports hasChildren in the summary listing too', async () => {
+ const results = await knowledgeRepo.query({
+ includeContent: false,
+ knowledgeBaseId: kbId,
+ parentId: null,
+ });
+ const byId = Object.fromEntries(results.map((item) => [item.id, item]));
+
+ expect(byId['parent-doc'].hasChildren).toBe(true);
+ expect(byId['leaf-doc'].hasChildren).toBe(false);
+ });
+
+ it('lists the children of a document inside the knowledge base', async () => {
+ const docChildren = await knowledgeRepo.query({
+ knowledgeBaseId: kbId,
+ parentId: 'parent-doc',
+ });
+ const fileChildren = await knowledgeRepo.query({
+ knowledgeBaseId: kbId,
+ parentId: 'file-parent-doc',
+ });
+
+ expect(docChildren.map((item) => item.id)).toEqual(['child-doc']);
+ expect(docChildren[0].hasChildren).toBe(false);
+ expect(fileChildren.map((item) => item.id)).toEqual(['child-file']);
+ expect(fileChildren[0].hasChildren).toBe(false);
+ });
+});
diff --git a/packages/database/src/repositories/knowledge/index.ts b/packages/database/src/repositories/knowledge/index.ts
index 33dad566d99..6afed8ab622 100644
--- a/packages/database/src/repositories/knowledge/index.ts
+++ b/packages/database/src/repositories/knowledge/index.ts
@@ -20,6 +20,7 @@ import {
asc,
desc,
eq,
+ exists,
ilike,
inArray,
isNull,
@@ -181,6 +182,7 @@ interface KnowledgeRow {
embeddingTaskId: string | null;
fileId: string | null;
fileType: string;
+ hasChildren: boolean;
id: string;
knowledgeBaseIds: string[] | null;
metadata: Record<string, any> | null;
@@ -217,6 +219,12 @@ export interface KnowledgeItem {
embeddingTaskId?: string | null;
fileId?: string | null;
fileType: string;
+ /**
+ * Whether any document or file row names this row as its parent. Folders are
+ * containers either way; this is what lets a document that holds other
+ * documents expand in the tree.
+ */
+ hasChildren?: boolean;
id: string;
/** Knowledge bases the row is filed into (empty when it lives outside every base). */
knowledgeBaseIds?: string[];
@@ -296,6 +304,7 @@ const toKnowledgeItem = (row: KnowledgeRow): KnowledgeItem => ({
embeddingTaskId: row.embeddingTaskId,
fileId: row.fileId,
fileType: row.fileType,
+ hasChildren: Boolean(row.hasChildren),
id: row.id,
knowledgeBaseIds: row.knowledgeBaseIds ?? [],
metadata: toJson(row.metadata),
@@ -355,6 +364,40 @@ export class KnowledgeRepo {
private documentScope = () => buildWorkspaceWhere(this.scope(), d);
+ /**
+ * `has_children` for one arm. It depends on the caller's scope, so it can't
+ * live in the static column literals; both arms append it last, which keeps
+ * the UNION positions aligned. Children always point at a document id, so the
+ * file arm passes its joined page id (NULL when the file backs no page, and
+ * then nothing can be under it).
+ *
+ * The children are scoped like any read (ownership, visibility, trash) but
+ * not by the listing's other filters, so a child the listing itself would
+ * hide (another knowledge base, a hidden source) still counts.
+ */
+ private hasChildrenColumn = (parentDocumentId: AnyPgColumn) =>
+ sql<boolean>`${or(
+ exists(
+ this.db
+ .select({ one: sql`1` })
+ .from(documents)
+ .where(
+ and(
+ eq(documents.parentId, parentDocumentId),
+ buildWorkspaceWhere(this.scope(), documents),
+ ),
+ ),
+ ),
+ exists(
+ this.db
+ .select({ one: sql`1` })
+ .from(files)
+ .where(
+ and(eq(files.parentId, parentDocumentId), buildWorkspaceWhere(this.scope(), files)),
+ ),
+ ),
+ )}`.as('has_children');
+
/**
* Narrow a workspace-scoped list to one Resources mode. Personal rows are
* already owner-scoped and deliberately ignore the mode filter.
@@ -400,7 +443,10 @@ export class KnowledgeRepo {
includeContent: boolean = true,
includeContentPreview: boolean = false,
) => {
- const columns = includeContent ? fileArmColumns : fileArmSummaryColumns(includeContentPreview);
+ const columns = {
+ ...(includeContent ? fileArmColumns : fileArmSummaryColumns(includeContentPreview)),
+ hasChildren: this.hasChildrenColumn(d.id),
+ };
let query = this.db.select(columns).from(f).$dynamic();
if (knowledgeBaseId) {
@@ -441,9 +487,10 @@ export class KnowledgeRepo {
includeAgentArtifacts: boolean = false,
) =>
this.db
- .select(
- includeContent ? documentArmColumns : documentArmSummaryColumns(includeContentPreview),
- )
+ .select({
+ ...(includeContent ? documentArmColumns : documentArmSummaryColumns(includeContentPreview)),
+ hasChildren: this.hasChildrenColumn(d.id),
+ })
.from(d)
.leftJoin(users, eq(users.id, d.userId))
.where(
diff --git a/packages/types/src/files/list.ts b/packages/types/src/files/list.ts
index 071985dbed4..e951b9bc650 100644
--- a/packages/types/src/files/list.ts
+++ b/packages/types/src/files/list.ts
@@ -33,6 +33,8 @@ export interface FileListItem {
fileId?: string | null;
fileType: string;
finishEmbedding: boolean;
+ /** Whether any document or file sits under this row, so a page can expand like a folder. */
+ hasChildren?: boolean;
id: string;
/** Knowledge bases the row is filed into. */
knowledgeBaseIds?: string[];
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx b/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx
index d6ae5391856..1c3a38f8527 100644
--- a/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx
+++ b/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx
@@ -1,21 +1,8 @@
'use client';
import { DERIVED_DOCUMENT_SOURCE_TYPE } from '@lobechat/const';
-import {
- ActionIcon,
- Block,
- Center,
- cx,
- Flexbox,
- Icon,
- Input,
- Spin,
- stopPropagation,
- toast,
- Tooltip,
-} from '@lobehub/ui';
-import { ChevronDownIcon, FileText, FolderIcon, FolderOpenIcon, LockIcon } from 'lucide-react';
-import * as m from 'motion/react-m';
+import { Block, cx, Flexbox, Icon, Input, stopPropagation, toast, Tooltip } from '@lobehub/ui';
+import { FileText, FolderIcon, FolderOpenIcon, LockIcon } from 'lucide-react';
import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -32,12 +19,13 @@ import { libraryFolderPath } from '@/features/ResourceManager/utils/resourcePath
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { showContextMenu } from '@/libs/contextMenu';
import type { TreeItem } from '@/store/tree';
-import { useTreeStore } from '@/store/tree';
+import { isExpandable, useTreeStore } from '@/store/tree';
import { useFileItemClick } from '../Explorer/hooks/useFileItemClick';
import { useFileItemDropdown } from '../Explorer/ItemDropdown/useFileItemDropdown';
import FolderAddButton from './FolderAddButton';
import HierarchyNodeMenuButton from './HierarchyNodeMenuButton';
+import HierarchyNodeToggle from './HierarchyNodeToggle';
import { isHierarchyNodeActive, resolveDeletedFolderRedirect } from './selection';
import { styles } from './styles';
@@ -290,10 +278,6 @@ export const HierarchyNode = memo<HierarchyNodeProps>(
if (item.isFolder) {
const isActive = isHierarchyNodeActive(item, selectedKey);
- const handleToggle = () => {
- onToggle(item.id);
- };
-
return (
<Flexbox gap={2}>
<Block
@@ -328,26 +312,12 @@ export const HierarchyNode = memo<HierarchyNodeProps>(
>
{flat ? (
<div style={{ width: 20 }} />
- ) : isLoading ? (
- <Center flex={'none'} width={20}>
- <Spin size={'small'} />
- </Center>
) : (
- <m.div
- animate={{ rotate: isExpanded ? 0 : -90 }}
- initial={false}
- transition={{ duration: 0.2, ease: 'easeInOut' }}
- >
- <ActionIcon
- icon={ChevronDownIcon}
- size={'small'}
- style={{ width: 20 }}
- onClick={(e) => {
- e.stopPropagation();
- handleToggle();
- }}
- />
- </m.div>
+ <HierarchyNodeToggle
+ isExpanded={isExpanded}
+ isLoading={isLoading}
+ onToggle={() => onToggle(item.id)}
+ />
)}
<Flexbox
horizontal
@@ -399,7 +369,8 @@ export const HierarchyNode = memo<HierarchyNodeProps>(
);
}
- // Render as file
+ // Render as file. A document that holds other documents gets the folder's
+ // caret; the row itself still opens the document.
const isActive = isHierarchyNodeActive(item, selectedKey);
return (
<Flexbox gap={2}>
@@ -426,7 +397,15 @@ export const HierarchyNode = memo<HierarchyNodeProps>(
showContextMenu(menuItems());
}}
>
- <div style={{ width: 20 }} />
+ {!flat && isExpandable(item) ? (
+ <HierarchyNodeToggle
+ isExpanded={isExpanded}
+ isLoading={isLoading}
+ onToggle={() => onToggle(item.id)}
+ />
+ ) : (
+ <div style={{ width: 20 }} />
+ )}
<Flexbox
horizontal
align={'center'}
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNodeToggle.tsx b/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNodeToggle.tsx
new file mode 100644
index 00000000000..b55c9e4ca7f
--- /dev/null
+++ b/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNodeToggle.tsx
@@ -0,0 +1,41 @@
+'use client';
+
+import { ActionIcon, Center, Spin } from '@lobehub/ui';
+import { ChevronDownIcon } from 'lucide-react';
+import * as m from 'motion/react-m';
+
+interface HierarchyNodeToggleProps {
+ isExpanded: boolean;
+ isLoading: boolean;
+ onToggle: () => void;
+}
+
+/**
+ * Expand caret of a tree row, or a spinner while its children load. Shared by
+ * folders and by documents that hold other documents. The click stops here so
+ * it never reaches the row, which navigates or opens the item.
+ */
+const HierarchyNodeToggle = ({ isExpanded, isLoading, onToggle }: HierarchyNodeToggleProps) =>
+ isLoading ? (
+ <Center flex={'none'} width={20}>
+ <Spin size={'small'} />
+ </Center>
+ ) : (
+ <m.div
+ animate={{ rotate: isExpanded ? 0 : -90 }}
+ initial={false}
+ transition={{ duration: 0.2, ease: 'easeInOut' }}
+ >
+ <ActionIcon
+ icon={ChevronDownIcon}
+ size={'small'}
+ style={{ width: 20 }}
+ onClick={(e) => {
+ e.stopPropagation();
+ onToggle();
+ }}
+ />
+ </m.div>
+ );
+
+export default HierarchyNodeToggle;
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/selection.test.ts b/src/features/ResourceManager/components/LibraryHierarchy/selection.test.ts
index 30ec95a2d74..98187207a31 100644
--- a/src/features/ResourceManager/components/LibraryHierarchy/selection.test.ts
+++ b/src/features/ResourceManager/components/LibraryHierarchy/selection.test.ts
@@ -67,6 +67,13 @@ describe('hierarchySubtreeHoldsSelection', () => {
expect(hierarchySubtreeHoldsSelection(folderA, children, 'file_1')).toBe(true);
});
+ it('walks through a document that holds the opened file', () => {
+ const parentPage = { hasChildren: true, id: 'parent_page', isFolder: false };
+ const nested = { '': [folderA], 'folder_a': [parentPage], 'parent_page': [page] } as any;
+
+ expect(hierarchySubtreeHoldsSelection(folderA, nested, 'file_1')).toBe(true);
+ });
+
it('ignores a sibling subtree', () => {
expect(hierarchySubtreeHoldsSelection(folderB, children, 'folder_a')).toBe(false);
});
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/selection.ts b/src/features/ResourceManager/components/LibraryHierarchy/selection.ts
index 0f7abaf731e..16d471bcce9 100644
--- a/src/features/ResourceManager/components/LibraryHierarchy/selection.ts
+++ b/src/features/ResourceManager/components/LibraryHierarchy/selection.ts
@@ -1,5 +1,5 @@
import { libraryFolderPath } from '@/features/ResourceManager/utils/resourcePath';
-import type { TreeItem } from '@/store/tree';
+import { isExpandable, type TreeItem } from '@/store/tree';
interface SelectionSource {
currentFolderId?: string | null;
@@ -44,7 +44,7 @@ export const hierarchySubtreeHoldsSelection = (
for (const row of children[id] ?? []) {
if (isHierarchyNodeActive(row, selectedKey)) return true;
- if (row.isFolder) pending.push(row.id);
+ if (isExpandable(row)) pending.push(row.id);
}
}
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/visibleNodes.test.ts b/src/features/ResourceManager/components/LibraryHierarchy/visibleNodes.test.ts
index e26dd56fef5..8d42bd3aec4 100644
--- a/src/features/ResourceManager/components/LibraryHierarchy/visibleNodes.test.ts
+++ b/src/features/ResourceManager/components/LibraryHierarchy/visibleNodes.test.ts
@@ -31,6 +31,27 @@ describe('buildVisibleNodes', () => {
expect(nodes.map((n) => n.key)).toEqual(['folder']);
});
+ it('walks into an expanded document that holds other documents', () => {
+ // Regression: only folders were walked, so a page nested under another page
+ // never showed up in the library tree.
+ const parentDoc = toTreeItem({
+ fileType: 'custom/document',
+ hasChildren: true,
+ id: 'parent-doc',
+ name: 'Parent',
+ });
+ const nodes = buildVisibleNodes(
+ { '': [parentDoc, docB], 'parent-doc': [docA] },
+ { 'parent-doc': true },
+ );
+
+ expect(nodes.map((n) => [n.key, n.level, n.parentKey])).toEqual([
+ ['parent-doc', 0, ''],
+ ['doc-a', 1, 'parent-doc'],
+ ['doc-b', 0, ''],
+ ]);
+ });
+
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.
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/visibleNodes.ts b/src/features/ResourceManager/components/LibraryHierarchy/visibleNodes.ts
index a86e687c04f..f5976bfecab 100644
--- a/src/features/ResourceManager/components/LibraryHierarchy/visibleNodes.ts
+++ b/src/features/ResourceManager/components/LibraryHierarchy/visibleNodes.ts
@@ -1,4 +1,4 @@
-import type { TreeItem } from '@/store/tree';
+import { isExpandable, type TreeItem } from '@/store/tree';
export interface VisibleNode {
item: TreeItem;
@@ -31,7 +31,7 @@ export const buildVisibleNodes = (
seen.add(node.id);
result.push({ item: node, key: node.id, level, parentKey });
- if (node.isFolder && expanded[node.id]) {
+ if (isExpandable(node) && expanded[node.id]) {
walk(node.id, level + 1);
}
}
diff --git a/src/services/resource/index.ts b/src/services/resource/index.ts
index 6a7276abfb2..ae6624e594a 100644
--- a/src/services/resource/index.ts
+++ b/src/services/resource/index.ts
@@ -41,6 +41,8 @@ const mapToResourceItem = (item: FileListItem): ResourceItem => {
finishEmbedding: item.finishEmbedding,
+ hasChildren: item.hasChildren,
+
id: item.id,
knowledgeBaseIds: item.knowledgeBaseIds,
diff --git a/src/store/tree/actions.test.ts b/src/store/tree/actions.test.ts
index ea4d33485ad..457ed562625 100644
--- a/src/store/tree/actions.test.ts
+++ b/src/store/tree/actions.test.ts
@@ -5,7 +5,13 @@ import { hierarchySearchResource } from '@/features/ResourceManager/store/projec
import type * as ReplicaModule from '@/libs/replica';
import { createReplicaState } from '@/libs/replica';
-import { sortTreeItems, toTreeItem, toTreeItemFromResource, TreeActionImpl } from './actions';
+import {
+ isExpandable,
+ sortTreeItems,
+ toTreeItem,
+ toTreeItemFromResource,
+ TreeActionImpl,
+} from './actions';
import type { TreeState } from './types';
const {
@@ -772,4 +778,28 @@ describe('toTreeItemFromResource', () => {
it('produces the same row as the tree fetch does for the same input', () => {
expect(toTreeItemFromResource(row)).toEqual(toTreeItem(row));
});
+
+ it('keeps a document with children expandable', () => {
+ // Dropping `hasChildren` here would take the caret off a parent page on
+ // every explorer refresh.
+ const parent = toTreeItemFromResource({ ...row, hasChildren: true });
+
+ expect(parent).toMatchObject({ hasChildren: true, isFolder: false });
+ expect(isExpandable(parent)).toBe(true);
+ });
+});
+
+describe('toTreeItem hasChildren', () => {
+ const doc = { fileType: 'custom/document', id: 'docs_1', name: 'Page' };
+
+ it('carries hasChildren from the server row', () => {
+ expect(toTreeItem({ ...doc, hasChildren: true }).hasChildren).toBe(true);
+ expect(toTreeItem({ ...doc, hasChildren: false }).hasChildren).toBe(false);
+ });
+
+ it('treats folders and documents with children as expandable, leaves as not', () => {
+ expect(isExpandable(toTreeItem({ ...doc, hasChildren: true }))).toBe(true);
+ expect(isExpandable(toTreeItem(doc))).toBe(false);
+ expect(isExpandable(toTreeItem({ ...doc, fileType: CUSTOM_FOLDER_FILE_TYPE }))).toBe(true);
+ });
});
diff --git a/src/store/tree/actions.ts b/src/store/tree/actions.ts
index 059e6f5a0f0..c44529853e3 100644
--- a/src/store/tree/actions.ts
+++ b/src/store/tree/actions.ts
@@ -6,7 +6,7 @@ import { resourceService } from '@/services/resource';
import type { StoreSetter } from '@/store/types';
import { OptimisticEngine } from '@/store/utils/optimisticEngine';
-import { revalidateHierarchySearch, sortTreeItems, toTreeItem } from './items';
+import { isExpandable, revalidateHierarchySearch, sortTreeItems, toTreeItem } from './items';
import {
buildLibraryTreeSnapshot,
libraryTreeResource,
@@ -16,6 +16,7 @@ import {
import type { TreeDataState, TreeItem, TreeState, TreeStoreHandle } from './types';
export {
+ isExpandable,
revalidateHierarchySearch,
sortTreeItems,
toTreeItem,
@@ -302,7 +303,7 @@ export class TreeActionImpl {
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);
+ for (const item of items) if (isExpandable(item) && expanded[item.id]) queue.push(item.id);
}
return result;
};
@@ -597,7 +598,7 @@ export class TreeActionImpl {
while (pending.length > 0) {
const id = pending.pop()!;
const descendants = children[id];
- if (descendants) pending.push(...descendants.filter((i) => i.isFolder).map((i) => i.id));
+ if (descendants) pending.push(...descendants.filter(isExpandable).map((i) => i.id));
delete children[id];
delete expanded[id];
delete status[id];
diff --git a/src/store/tree/index.ts b/src/store/tree/index.ts
index d9284743b9d..876a83b63db 100644
--- a/src/store/tree/index.ts
+++ b/src/store/tree/index.ts
@@ -1,3 +1,3 @@
-export { toTreeItem } from './actions';
+export { isExpandable, toTreeItem } from './actions';
export { useTreeStore } from './store';
export type { TreeItem, TreeState } from './types';
diff --git a/src/store/tree/items.ts b/src/store/tree/items.ts
index c6b19e7ff58..28662c841e4 100644
--- a/src/store/tree/items.ts
+++ b/src/store/tree/items.ts
@@ -55,10 +55,19 @@ export const sortTreeItems = <T extends TreeItem>(items: T[]): T[] => {
});
};
+/**
+ * Whether a row has children to walk: every folder, plus a document the server
+ * reports something under. Only for walking and expanding β€” folder navigation,
+ * drop targets and folder-only actions keep checking `isFolder`.
+ */
+export const isExpandable = (item: Pick<TreeItem, 'hasChildren' | 'isFolder'>): boolean =>
+ item.isFolder || !!item.hasChildren;
+
export const toTreeItem = (item: {
createdAt?: Date | string | null;
fileId?: string | null;
fileType: string;
+ hasChildren?: boolean;
id: string;
metadata?: Record<string, any> | null;
name: string;
@@ -73,6 +82,7 @@ export const toTreeItem = (item: {
createdAt: item.createdAt ?? undefined,
fileId: item.fileId,
fileType: item.fileType,
+ hasChildren: item.hasChildren,
id: item.id,
isFolder: item.fileType === CUSTOM_FOLDER_FILE_TYPE,
metadata: item.metadata ?? undefined,
@@ -100,6 +110,7 @@ export const toTreeItemFromResource = (item: {
createdAt?: Date | string | null;
fileId?: string | null;
fileType: string;
+ hasChildren?: boolean;
id: string;
metadata?: Record<string, any> | null;
name: string;
diff --git a/src/store/tree/projection.ts b/src/store/tree/projection.ts
index 1714c4daf5b..990e4056a66 100644
--- a/src/store/tree/projection.ts
+++ b/src/store/tree/projection.ts
@@ -1,5 +1,6 @@
import { defineReplica } from '@/libs/replica';
+import { isExpandable } from './items';
import type { TreeItem } from './types';
/**
@@ -27,6 +28,7 @@ const compactItem = (item: TreeItem): TreeItem => {
createdAt: item.createdAt,
fileId: item.fileId,
fileType: item.fileType,
+ hasChildren: item.hasChildren,
id: item.id,
isFolder: item.isFolder,
metadata: emoji ? { emoji } : undefined,
@@ -66,7 +68,7 @@ export const buildLibraryTreeSnapshot = (
folders += 1;
for (const item of kept) {
- if (item.isFolder && expanded[item.id] && children[item.id]) queue.push(item.id);
+ if (isExpandable(item) && expanded[item.id] && children[item.id]) queue.push(item.id);
}
}
diff --git a/src/store/tree/types.ts b/src/store/tree/types.ts
index 32921f3ec82..64e9d7746a2 100644
--- a/src/store/tree/types.ts
+++ b/src/store/tree/types.ts
@@ -17,6 +17,11 @@ export interface TreeItem {
*/
fileId?: string | null;
fileType: string;
+ /**
+ * Something sits under this row. Folders are expandable regardless; this is
+ * what lets a document that holds other documents expand too.
+ */
+ hasChildren?: boolean;
id: string;
isFolder: boolean;
metadata?: Record<string, any>;
diff --git a/src/types/resource.ts b/src/types/resource.ts
index 21886ab2432..07f52582855 100644
--- a/src/types/resource.ts
+++ b/src/types/resource.ts
@@ -38,6 +38,8 @@ export interface ResourceItem {
fileId?: string | null;
fileType: string;
finishEmbedding?: boolean;
+ /** Whether any document or file sits under this row, so a page can expand like a folder. */
+ hasChildren?: boolean;
// Identity
id: string;
knowledgeBaseId?: string;