Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

fix(web): surface dataset navigation tree load failures (closes #17301) (#17668)

Souravrajvi0004b3c48454e
diff --git a/test/unit_test/api/apps/services/test_dataset_api_service_nav.py b/test/unit_test/api/apps/services/test_dataset_api_service_nav.py
new file mode 100644
index 0000000000..12f4a74f5b
--- /dev/null
+++ b/test/unit_test/api/apps/services/test_dataset_api_service_nav.py
@@ -0,0 +1,236 @@
+#
+# Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Regression tests for dataset navigation tree service helpers (#17301)."""
+
+import importlib.util
+import json
+import sys
+from enum import IntEnum
+from pathlib import Path
+from types import ModuleType, SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+
+pytestmark = pytest.mark.p2
+
+
+class _StubModelTypeBinary(IntEnum):
+ CHAT = 1
+ EMBEDDING = 2
+
+
+def _stub(monkeypatch, name, **attrs):
+ mod = ModuleType(name)
+ for key, value in attrs.items():
+ setattr(mod, key, value)
+ monkeypatch.setitem(sys.modules, name, mod)
+ if "." in name:
+ parent_name, _, child_name = name.rpartition(".")
+ parent_mod = sys.modules.get(parent_name)
+ if parent_mod is not None:
+ monkeypatch.setattr(parent_mod, child_name, mod, raising=False)
+ return mod
+
+
+def _load_nav_module(monkeypatch, *, accessible=True, index_pack=("idx-1", None), total=0, field_map=None):
+ doc_store = MagicMock()
+ doc_store.search = MagicMock(return_value={})
+ doc_store.get_fields = MagicMock(return_value=field_map or {})
+ doc_store.get_total = MagicMock(return_value=total)
+ doc_store.delete = MagicMock(return_value=0)
+
+ kb = SimpleNamespace(tenant_id="tenant-1", id="kb-1")
+ knowledgebase_service = SimpleNamespace(
+ accessible=MagicMock(return_value=accessible),
+ get_by_id=MagicMock(return_value=(True, kb)),
+ )
+
+ _stub(
+ monkeypatch,
+ "api.db.joint_services.tenant_model_service",
+ get_composite_model_name_by_ids=MagicMock(),
+ resolve_model_config=MagicMock(),
+ resolve_model_id=MagicMock(),
+ )
+ _stub(
+ monkeypatch,
+ "common.constants",
+ PAGERANK_FLD="pagerank",
+ LLMType=SimpleNamespace(),
+ FileSource=SimpleNamespace(KNOWLEDGEBASE="knowledgebase"),
+ RetCode=SimpleNamespace(),
+ StatusEnum=SimpleNamespace(),
+ TaskStatus=SimpleNamespace(),
+ ModelTypeBinary=_StubModelTypeBinary,
+ )
+ _stub(monkeypatch, "common.settings", docStoreConn=doc_store, DOC_ENGINE="infinity")
+ _stub(
+ monkeypatch,
+ "api.db.db_models",
+ Connector2Kb=SimpleNamespace(),
+ Document=SimpleNamespace(),
+ File=SimpleNamespace(),
+ SyncLogs=SimpleNamespace(),
+ )
+ _stub(
+ monkeypatch,
+ "api.db.services.document_service",
+ DocumentService=SimpleNamespace(get_parsing_status_by_kb_ids=MagicMock()),
+ queue_raptor_o_graphrag_tasks=MagicMock(),
+ )
+ _stub(monkeypatch, "api.db.services.file2document_service", File2DocumentService=SimpleNamespace())
+ _stub(monkeypatch, "api.db.services.file_service", FileService=SimpleNamespace())
+ _stub(
+ monkeypatch,
+ "api.db.services.knowledgebase_service",
+ KnowledgebaseService=knowledgebase_service,
+ validate_dataset_embedding_models=lambda kbs: None,
+ )
+ _stub(
+ monkeypatch,
+ "api.db.services.connector_service",
+ Connector2KbService=SimpleNamespace(),
+ SyncLogsService=SimpleNamespace(),
+ )
+ _stub(
+ monkeypatch,
+ "api.db.services.task_service",
+ GRAPH_RAPTOR_FAKE_DOC_ID="fake-doc",
+ TaskService=SimpleNamespace(),
+ )
+ _stub(monkeypatch, "api.db.services.tenant_model_service", TenantModelService=SimpleNamespace())
+ _stub(
+ monkeypatch,
+ "api.db.services.user_service",
+ TenantService=SimpleNamespace(get_joined_tenants_by_user_id=lambda user_id: [{"tenant_id": "tenant-1"}]),
+ UserService=SimpleNamespace(get_by_ids=lambda ids: []),
+ UserTenantService=SimpleNamespace(),
+ )
+ _stub(
+ monkeypatch,
+ "api.utils.api_utils",
+ deep_merge=MagicMock(),
+ get_parser_config=MagicMock(),
+ remap_dictionary_keys=lambda source_data, key_aliases=None: dict(source_data),
+ verify_embedding_availability=MagicMock(),
+ )
+ _stub(
+ monkeypatch,
+ "common.misc_utils",
+ thread_pool_exec=AsyncMock(side_effect=lambda fn, *args, **kwargs: fn(*args, **kwargs)),
+ thread_pool_exec_long_time=AsyncMock(side_effect=lambda fn, *args, **kwargs: fn(*args, **kwargs)),
+ )
+ _stub(monkeypatch, "rag.advanced_rag.knowlege_compile.wiki", WIKI_PAGE_COMPILE_KWD="wiki")
+ _stub(monkeypatch, "common.doc_store.doc_store_base", OrderByExpr=MagicMock)
+
+ repo_root = Path(__file__).resolve().parents[5]
+ module_path = repo_root / "api" / "apps" / "services" / "dataset_api_service.py"
+ spec = importlib.util.spec_from_file_location("test_dataset_api_service_nav_module", module_path)
+ module = importlib.util.module_from_spec(spec)
+ monkeypatch.setitem(sys.modules, "test_dataset_api_service_nav_module", module)
+ spec.loader.exec_module(module)
+ monkeypatch.setattr(module, "_compiled_index_or_none", lambda _tenant_id, _kb_id: index_pack)
+ return module, knowledgebase_service, doc_store
+
+
+def test_nav_item_shapes_cluster_row(monkeypatch):
+ module, _, _ = _load_nav_module(monkeypatch)
+ row = {
+ "name": "cluster-a",
+ "type_kwd": "nav_cluster",
+ "content_with_weight": json.dumps({"description": "Top cluster"}),
+ "doc_count_int": 3,
+ }
+ item = module._nav_item(row)
+ assert item == {
+ "name": "cluster-a",
+ "description": "Top cluster",
+ "keywords": [],
+ "entities": [],
+ "graph_content": "",
+ "doc_count": 3,
+ "type": "cluster",
+ "doc_id": None,
+ "has_children": True,
+ }
+
+
+def test_nav_item_shapes_doc_leaf_row(monkeypatch):
+ module, _, _ = _load_nav_module(monkeypatch)
+ row = {
+ "name": "doc-leaf",
+ "type_kwd": "nav_doc",
+ "content_with_weight": "{}",
+ "doc_id": "doc-123",
+ }
+ item = module._nav_item(row)
+ assert item["type"] == "doc"
+ assert item["doc_id"] == "doc-123"
+ assert item["doc_count"] == 1
+ assert item["has_children"] is False
+
+
+async def test_list_nav_clusters_returns_empty_when_index_missing(monkeypatch):
+ module, _, _ = _load_nav_module(monkeypatch, index_pack=None)
+ ok, payload = await module.list_nav_clusters("kb-1", "tenant-1")
+ assert ok is True
+ assert payload == {"total": 0, "items": []}
+
+
+async def test_list_nav_clusters_denies_inaccessible_dataset(monkeypatch):
+ module, knowledgebase_service, doc_store = _load_nav_module(monkeypatch, accessible=False)
+ ok, payload = await module.list_nav_clusters("kb-1", "tenant-1")
+ assert ok is False
+ assert payload == "no authorization"
+ doc_store.search.assert_not_called()
+ knowledgebase_service.get_by_id.assert_not_called()
+
+
+async def test_list_nav_children_uses_parent_name_filter(monkeypatch):
+ module, _, doc_store = _load_nav_module(
+ monkeypatch,
+ total=1,
+ field_map={
+ "row-1": {
+ "name": "child-a",
+ "type_kwd": "nav_doc",
+ "content_with_weight": "{}",
+ "doc_id": "doc-1",
+ }
+ },
+ )
+
+ ok, payload = await module.list_nav_children("kb-1", "tenant-1", "cluster-a")
+ assert ok is True
+ assert payload["total"] == 1
+ assert payload["items"][0]["name"] == "child-a"
+ call_kwargs = doc_store.search.call_args.kwargs
+ condition = call_kwargs.get("condition") or doc_store.search.call_args.args[2]
+ assert condition["parent_kwd"] == ["cluster-a"]
+
+
+async def test_delete_nav_returns_zero_when_index_missing(monkeypatch):
+ module, _, doc_store = _load_nav_module(monkeypatch, index_pack=None)
+ ok, payload = await module.delete_nav("kb-1", "tenant-1")
+ assert ok is True
+ assert payload == {"deleted": 0}
+ doc_store.delete.assert_not_called()
diff --git a/web/src/hooks/use-dataset-nav-request.ts b/web/src/hooks/use-dataset-nav-request.ts
index 578be4a553..ce3a58a25f 100644
--- a/web/src/hooks/use-dataset-nav-request.ts
+++ b/web/src/hooks/use-dataset-nav-request.ts
@@ -31,46 +31,86 @@ export const DatasetNavKeys = {
['dataset_nav', kbId, 'children', name] as const,
};
+type DatasetNavResponse<T> = {
+ code?: number;
+ data?: T;
+ message?: string;
+};
+
+function isDatasetNavList(payload: unknown): payload is DatasetNavList {
+ if (!payload || typeof payload !== 'object') {
+ return false;
+ }
+ const candidate = payload as DatasetNavList;
+ return typeof candidate.total === 'number' && Array.isArray(candidate.items);
+}
+
+function unwrapDatasetNavResponse(
+ response: DatasetNavResponse<DatasetNavList> | undefined,
+): DatasetNavList {
+ if (response?.code !== 0 || !isDatasetNavList(response.data)) {
+ const errorMessage =
+ (typeof response?.message === 'string' && response.message) ||
+ i18n.t('knowledgeCompilation.navLoadFailed');
+ throw new Error(errorMessage);
+ }
+ return response.data;
+}
+
export function useFetchDatasetNav(keywords = '') {
const kbId = useKnowledgeBaseId();
const trimmedKeywords = trim(keywords);
- const { data, isFetching: loading } = useQuery<DatasetNavList | null>({
+ const {
+ data,
+ isFetching: loading,
+ isError,
+ error,
+ refetch,
+ } = useQuery<DatasetNavList | null>({
queryKey: DatasetNavKeys.list(kbId, trimmedKeywords),
initialData: null,
enabled: !!kbId,
gcTime: 0,
+ retry: false,
queryFn: async () => {
const { data } = await datasetNavService.getNav({
datasetId: kbId,
keywords: trimmedKeywords,
});
- return data?.data ?? null;
+ return unwrapDatasetNavResponse(data);
},
});
- return { data, loading };
+ return { data, loading, isError, error, refetch };
}
export function useFetchDatasetNavChildren(parentName: string | null) {
const kbId = useKnowledgeBaseId();
const enabled = !!kbId && !!parentName;
- const { data, isFetching: loading } = useQuery<DatasetNavList | null>({
+ const {
+ data,
+ isFetching: loading,
+ isError,
+ error,
+ refetch,
+ } = useQuery<DatasetNavList | null>({
queryKey: DatasetNavKeys.children(kbId, parentName ?? ''),
initialData: null,
enabled,
gcTime: 0,
+ retry: false,
queryFn: async () => {
const { data } = await datasetNavService.getNavChildren({
datasetId: kbId,
name: parentName!,
});
- return data?.data ?? null;
+ return unwrapDatasetNavResponse(data);
},
});
- return { data, loading };
+ return { data, loading, isError, error, refetch };
}
export function useDeleteDatasetNav() {
diff --git a/web/src/locales/en.ts b/web/src/locales/en.ts
index 2c80a790f6..479f581fbf 100644
--- a/web/src/locales/en.ts
+++ b/web/src/locales/en.ts
@@ -2385,6 +2385,8 @@ Example: Virtual Hosted Style`,
skillDeleteDescription: 'Are you sure you want to delete this skill?',
navTitle: 'Navigation tree',
navEmpty: 'No navigation nodes',
+ navLoadFailed: 'Failed to load the navigation tree',
+ navChildLoadFailed: 'Failed to load child nodes',
navLoading: 'Loading...',
navSelectNode: 'Select a child node to view details',
navNoDescription: 'No description',
diff --git a/web/src/locales/zh.ts b/web/src/locales/zh.ts
index 42e527da96..f45ea94c8f 100644
--- a/web/src/locales/zh.ts
+++ b/web/src/locales/zh.ts
@@ -2030,6 +2030,8 @@ NER:使用 spaCy NER 和基于规则的关键词提取来抽取 Entities 和 R
skillDeleteDescription: '确定要删除该 Skill 吗?',
navTitle: 'PageIndex',
navEmpty: '暂无导航节点',
+ navLoadFailed: '加载目录树失败',
+ navChildLoadFailed: '加载子节点失败',
navLoading: '加载中...',
navSelectNode: '选择子节点以查看详情',
navNoDescription: '暂无描述',
diff --git a/web/src/pages/dataset/compilation/hooks/use-compilation-nav.ts b/web/src/pages/dataset/compilation/hooks/use-compilation-nav.ts
index c499f8b436..69060ba29e 100644
--- a/web/src/pages/dataset/compilation/hooks/use-compilation-nav.ts
+++ b/web/src/pages/dataset/compilation/hooks/use-compilation-nav.ts
@@ -26,8 +26,11 @@ export function useCompilationNav() {
const kbId = useKnowledgeBaseId();
const [keywords, setKeywords] = useState('');
const debouncedKeywords = useDebounce(keywords, { wait: 500 });
- const { data: navList, loading: navLoading } =
- useFetchDatasetNav(debouncedKeywords);
+ const {
+ data: navList,
+ loading: navLoading,
+ isError: navError,
+ } = useFetchDatasetNav(debouncedKeywords);
const { deleteNav, loading: deleteNavLoading } = useDeleteDatasetNav();
const { deleteNavNode, loading: deleteNodeLoading } =
useDeleteDatasetNavNode();
@@ -36,6 +39,9 @@ export function useCompilationNav() {
const [childrenMap, setChildrenMap] = useState<
Record<string, DatasetNavNode[]>
>({});
+ const [childrenErrorParents, setChildrenErrorParents] = useState<
+ Record<string, boolean>
+ >({});
const [loadingDocId, setLoadingDocId] = useState<string | null>(null);
const [structureMap, setStructureMap] = useState<
Record<string, IStructureGraphTemplate[]>
@@ -44,19 +50,51 @@ export function useCompilationNav() {
null,
);
- const { data: childrenData } = useFetchDatasetNavChildren(loadingParent);
+ const { data: childrenData, isError: childrenError } =
+ useFetchDatasetNavChildren(loadingParent);
const { data: structureData, isPlaceholderData: structurePlaceholder } =
useFetchDocumentStructureGraphById(kbId, loadingDocId ?? '');
useEffect(() => {
- if (loadingParent && childrenData) {
- setChildrenMap((prev) => ({
- ...prev,
- [loadingParent]: childrenData.items,
- }));
+ if (!loadingParent || !childrenData) {
+ return;
}
+ const parent = loadingParent;
+ setChildrenMap((prev) => ({
+ ...prev,
+ [parent]: childrenData.items,
+ }));
+ setChildrenErrorParents((prev) => {
+ if (!prev[parent]) {
+ return prev;
+ }
+ const next = { ...prev };
+ delete next[parent];
+ return next;
+ });
+ setLoadingParent(null);
}, [loadingParent, childrenData]);
+ useEffect(() => {
+ if (!loadingParent || !childrenError) {
+ return;
+ }
+ const parent = loadingParent;
+ setChildrenMap((prev) => {
+ if (!(parent in prev)) {
+ return prev;
+ }
+ const next = { ...prev };
+ delete next[parent];
+ return next;
+ });
+ setChildrenErrorParents((prev) => ({
+ ...prev,
+ [parent]: true,
+ }));
+ setLoadingParent(null);
+ }, [loadingParent, childrenError]);
+
useEffect(() => {
// keepPreviousData serves the previous document's graph while the new one
// loads; only store the response once it belongs to loadingDocId.
@@ -70,11 +108,19 @@ export function useCompilationNav() {
const loadChildren = useCallback(
(name: string) => {
- if (!(name in childrenMap)) {
+ setChildrenErrorParents((prev) => {
+ if (!prev[name]) {
+ return prev;
+ }
+ const next = { ...prev };
+ delete next[name];
+ return next;
+ });
+ if (!(name in childrenMap) && loadingParent !== name) {
setLoadingParent(name);
}
},
- [childrenMap],
+ [childrenMap, loadingParent],
);
const loadStructure = useCallback(
@@ -108,6 +154,14 @@ export function useCompilationNav() {
delete next[name];
return next;
});
+ setChildrenErrorParents((prev) => {
+ if (!(name in prev)) {
+ return prev;
+ }
+ const next = { ...prev };
+ delete next[name];
+ return next;
+ });
}, []);
const dropStructure = useCallback((docId: string) => {
@@ -124,6 +178,7 @@ export function useCompilationNav() {
const resetNav = useCallback(() => {
setSelectedNode(null);
setChildrenMap({});
+ setChildrenErrorParents({});
setLoadingParent(null);
setStructureMap({});
setLoadingDocId(null);
@@ -223,8 +278,10 @@ export function useCompilationNav() {
return {
navList,
navLoading,
+ navError,
keywords,
childrenMap,
+ childrenErrorParents,
structureMap,
selectedNode,
deleteNavLoading,
diff --git a/web/src/pages/dataset/compilation/nav-tree-left-panel.test.tsx b/web/src/pages/dataset/compilation/nav-tree-left-panel.test.tsx
new file mode 100644
index 0000000000..fefc45d662
--- /dev/null
+++ b/web/src/pages/dataset/compilation/nav-tree-left-panel.test.tsx
@@ -0,0 +1,94 @@
+import { render, screen } from '@testing-library/react';
+
+import { NavTreeLeftPanel } from './nav-tree-left-panel';
+
+jest.mock('@/components/structure-graph/adapters', () => ({
+ adaptPageIndexToTreeData: jest.fn(() => []),
+ adaptTreeToTreeData: jest.fn(() => []),
+ getEntityDisplayName: jest.fn((entity) => entity.name ?? ''),
+}));
+
+jest.mock('@/components/ui/tree-view', () => ({
+ TreeView: ({ data }: { data: { name: string }[] }) => (
+ <div data-testid="nav-tree">{data.map((node) => node.name).join(',')}</div>
+ ),
+}));
+
+jest.mock('@/components/confirm-delete-dialog', () => ({
+ ConfirmDeleteDialog: ({ children }: { children: React.ReactNode }) => (
+ <>{children}</>
+ ),
+}));
+
+jest.mock('@/components/ui/input', () => ({
+ SearchInput: () => <input data-testid="nav-search" />,
+}));
+
+jest.mock('@/components/ui/spin', () => ({
+ Spin: () => <div data-testid="nav-spin" />,
+}));
+
+jest.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+const NavItem = {
+ name: 'cluster-a',
+ description: '',
+ doc_count: 1,
+ type: 'cluster',
+ has_children: true,
+};
+
+const PanelHandlers = {
+ onKeywordsChange: jest.fn(),
+ onNodeClick: jest.fn(),
+ onNodeExpand: jest.fn(),
+ onEntityClick: jest.fn(),
+ onDeleteAll: jest.fn(),
+ onDeleteNode: jest.fn(),
+};
+
+describe('NavTreeLeftPanel', () => {
+ it('keeps cached nodes visible when a later nav load fails', () => {
+ render(
+ <NavTreeLeftPanel
+ navList={{ total: 1, items: [NavItem] }}
+ navLoading={false}
+ navError
+ keywords=""
+ childrenMap={{}}
+ structureMap={{}}
+ deleteNavLoading={false}
+ deleteNodeLoading={false}
+ {...PanelHandlers}
+ />,
+ );
+
+ expect(
+ screen.getByText('knowledgeCompilation.navLoadFailed'),
+ ).toBeInTheDocument();
+ expect(screen.getByTestId('nav-tree')).toHaveTextContent('cluster-a');
+ });
+
+ it('shows only the error placeholder when the tree is empty', () => {
+ render(
+ <NavTreeLeftPanel
+ navList={{ total: 0, items: [] }}
+ navLoading={false}
+ navError
+ keywords=""
+ childrenMap={{}}
+ structureMap={{}}
+ deleteNavLoading={false}
+ deleteNodeLoading={false}
+ {...PanelHandlers}
+ />,
+ );
+
+ expect(
+ screen.getByText('knowledgeCompilation.navLoadFailed'),
+ ).toBeInTheDocument();
+ expect(screen.queryByTestId('nav-tree')).not.toBeInTheDocument();
+ });
+});
diff --git a/web/src/pages/dataset/compilation/nav-tree-left-panel.tsx b/web/src/pages/dataset/compilation/nav-tree-left-panel.tsx
index d149735818..804c235d26 100644
--- a/web/src/pages/dataset/compilation/nav-tree-left-panel.tsx
+++ b/web/src/pages/dataset/compilation/nav-tree-left-panel.tsx
@@ -66,8 +66,10 @@ function NavNodeDeleteAction({
type NavTreeLeftPanelProps = {
navList: DatasetNavList | null;
navLoading: boolean;
+ navError?: boolean;
keywords: string;
childrenMap: Record<string, DatasetNavNode[]>;
+ childrenErrorParents?: Record<string, boolean>;
structureMap: Record<string, IStructureGraphTemplate[]>;
deleteNavLoading: boolean;
deleteNodeLoading: boolean;
@@ -82,8 +84,10 @@ type NavTreeLeftPanelProps = {
export function NavTreeLeftPanel({
navList,
navLoading,
+ navError = false,
keywords,
childrenMap,
+ childrenErrorParents = {},
structureMap,
deleteNavLoading,
deleteNodeLoading,
@@ -112,16 +116,19 @@ export function NavTreeLeftPanel({
() =>
buildNavTreeData(navList?.items, {
childrenMap,
+ childrenErrorParents,
structureMap,
getActions: renderNavActions,
onNodeClick,
onNodeExpand,
onEntityClick,
loadingPlaceholder: t('knowledgeCompilation.navLoading'),
+ errorPlaceholder: t('knowledgeCompilation.navChildLoadFailed'),
}),
[
navList?.items,
childrenMap,
+ childrenErrorParents,
structureMap,
renderNavActions,
onNodeClick,
@@ -140,7 +147,9 @@ export function NavTreeLeftPanel({
{treeData.length > 0 && (
<ConfirmDeleteDialog
title={t('knowledgeCompilation.navDeleteAllTitle')}
- content={{ title: t('knowledgeCompilation.navDeleteAllDescription') }}
+ content={{
+ title: t('knowledgeCompilation.navDeleteAllDescription'),
+ }}
onOk={onDeleteAll}
>
<Button
@@ -166,15 +175,26 @@ export function NavTreeLeftPanel({
</div>
) : treeData.length === 0 ? (
<div className="py-8 text-center text-sm text-text-secondary">
- {t('knowledgeCompilation.navEmpty')}
+ {t(
+ navError
+ ? 'knowledgeCompilation.navLoadFailed'
+ : 'knowledgeCompilation.navEmpty',
+ )}
</div>
) : (
- <TreeView
- data={treeData}
- expandOnRowClick={false}
- defaultNodeIcon={Folder}
- defaultLeafIcon={FileText}
- />
+ <>
+ {navError ? (
+ <div className="px-2 pb-2 text-center text-sm text-text-secondary">
+ {t('knowledgeCompilation.navLoadFailed')}
+ </div>
+ ) : null}
+ <TreeView
+ data={treeData}
+ expandOnRowClick={false}
+ defaultNodeIcon={Folder}
+ defaultLeafIcon={FileText}
+ />
+ </>
)}
</div>
</aside>
diff --git a/web/src/pages/dataset/compilation/nav-tree-view.tsx b/web/src/pages/dataset/compilation/nav-tree-view.tsx
index d278a63068..b0e4e1b9f5 100644
--- a/web/src/pages/dataset/compilation/nav-tree-view.tsx
+++ b/web/src/pages/dataset/compilation/nav-tree-view.tsx
@@ -14,8 +14,10 @@ export function NavTreeView() {
const {
navList,
navLoading,
+ navError,
keywords,
childrenMap,
+ childrenErrorParents,
structureMap,
selectedNode,
deleteNavLoading,
@@ -35,8 +37,10 @@ export function NavTreeView() {
<NavTreeLeftPanel
navList={navList}
navLoading={navLoading}
+ navError={navError}
keywords={keywords}
childrenMap={childrenMap}
+ childrenErrorParents={childrenErrorParents}
structureMap={structureMap}
deleteNavLoading={deleteNavLoading}
deleteNodeLoading={deleteNodeLoading}
@@ -70,7 +74,8 @@ export function NavTreeView() {
{t('knowledgeCompilation.description')}
</h4>
<p className="whitespace-pre-wrap">
- {selectedNode.description || t('knowledgeCompilation.navNoDescription')}
+ {selectedNode.description ||
+ t('knowledgeCompilation.navNoDescription')}
</p>
</div>
{selectedNode.keywords && selectedNode.keywords.length > 0 && (
diff --git a/web/src/pages/dataset/compilation/utils/nav-tree.test.ts b/web/src/pages/dataset/compilation/utils/nav-tree.test.ts
new file mode 100644
index 0000000000..7ff388f7aa
--- /dev/null
+++ b/web/src/pages/dataset/compilation/utils/nav-tree.test.ts
@@ -0,0 +1,48 @@
+import { buildNavTreeData } from './nav-tree';
+
+jest.mock('@/components/structure-graph/adapters', () => ({
+ adaptPageIndexToTreeData: jest.fn(() => []),
+ adaptTreeToTreeData: jest.fn(() => []),
+ getEntityDisplayName: jest.fn((entity) => entity.name ?? ''),
+}));
+
+function cluster(name: string) {
+ return {
+ name,
+ description: '',
+ doc_count: 1,
+ type: 'cluster',
+ has_children: true,
+ };
+}
+
+const TreeOptions = {
+ structureMap: {},
+ onNodeClick: jest.fn(),
+ onNodeExpand: jest.fn(),
+ loadingPlaceholder: 'Loading...',
+ errorPlaceholder: 'Failed to load child nodes',
+};
+
+describe('buildNavTreeData', () => {
+ it('renders an error placeholder when a child load failed', () => {
+ const data = buildNavTreeData([cluster('cluster-a')], {
+ ...TreeOptions,
+ childrenMap: {},
+ childrenErrorParents: { 'cluster-a': true },
+ });
+
+ expect(data[0].children).toEqual([
+ { id: 'cluster-a/__error__', name: 'Failed to load child nodes' },
+ ]);
+ });
+
+ it('does not keep the loading placeholder after an empty child list is cached', () => {
+ const data = buildNavTreeData([cluster('cluster-a')], {
+ ...TreeOptions,
+ childrenMap: { 'cluster-a': [] },
+ });
+
+ expect(data[0].children).toBeUndefined();
+ });
+});
diff --git a/web/src/pages/dataset/compilation/utils/nav-tree.ts b/web/src/pages/dataset/compilation/utils/nav-tree.ts
index ecd1815ada..923d79ca39 100644
--- a/web/src/pages/dataset/compilation/utils/nav-tree.ts
+++ b/web/src/pages/dataset/compilation/utils/nav-tree.ts
@@ -26,12 +26,14 @@ export type NavEntityClickHandler = (
type BuildNavTreeDataOptions = {
childrenMap: Record<string, DatasetNavNode[]>;
+ childrenErrorParents?: Record<string, boolean>;
structureMap: Record<string, IStructureGraphTemplate[]>;
getActions?: NavTreeActionsFactory;
onNodeClick: (node: DatasetNavNode, parentName: string | null) => void;
onNodeExpand: (node: DatasetNavNode) => void;
onEntityClick?: NavEntityClickHandler;
loadingPlaceholder: string;
+ errorPlaceholder: string;
};
function getEntityDescription(entity: IStructureGraphEntity): string {
@@ -123,12 +125,14 @@ export function buildNavTreeData(
): TreeDataItem[] {
const {
childrenMap,
+ childrenErrorParents,
structureMap,
getActions,
onNodeClick,
onNodeExpand,
onEntityClick,
loadingPlaceholder,
+ errorPlaceholder,
} = options;
return items.map((node) => {
@@ -144,7 +148,9 @@ export function buildNavTreeData(
if (node.has_children) {
item.hasChildren = true;
const children = childrenMap[node.name];
- if (children?.length) {
+ if (childrenErrorParents?.[node.name]) {
+ item.children = [{ id: `${id}/__error__`, name: errorPlaceholder }];
+ } else if (children?.length) {
item.children = buildNavTreeData(children, options, node.name, id);
} else if (!children) {
// Children not fetched yet: a placeholder keeps the node rendered as