Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(knowledge): make the folder tree root a real parent node

lyingbugd6083c6c9883
diff --git a/frontend/src/components/UploadConfirmHost.vue b/frontend/src/components/UploadConfirmHost.vue
index 74f4690e8..b7aa343f9 100644
--- a/frontend/src/components/UploadConfirmHost.vue
+++ b/frontend/src/components/UploadConfirmHost.vue
@@ -25,6 +25,7 @@ const handleCancel = () => {
:reparse-preview="uploadConfirmStore.reparse"
:accept-file-types="uploadConfirmStore.acceptFileTypes"
:supported-file-types="uploadConfirmStore.supportedFileTypes"
+ :target-folder="uploadConfirmStore.targetFolder"
@confirm="handleConfirm"
@cancel="handleCancel"
/>
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index bbc716c53..487b909c7 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -371,10 +371,11 @@ export default {
tagEditNoSelected: 'None selected',
folderTree: {
title: 'Folders',
- allDocuments: 'All documents',
- rootFolder: 'Root',
- empty: 'Upload a folder and its structure shows up here.',
- includeSubfolders: 'Include documents in sub-folders',
+ rootRow: 'All documents',
+ rootRowTip: 'The top level of the knowledge base; every folder sits below it',
+ scopeToggle: 'Change list scope',
+ scopeSubtreeTip: 'Including sub-folders — click to list only this level',
+ scopeDirectTip: 'Listing only this level — click to include sub-folders',
collapse: 'Collapse folders',
expand: 'Expand folders',
collapseFolder: 'Collapse this folder',
@@ -668,6 +669,11 @@ export default {
description: 'Useful for web-print, scanned, or image-heavy PDFs. Every page will be rendered as an image and processed via OCR/VLM. May increase processing time and model costs.'
},
continueAdd: 'Add more',
+ destinationLabel: 'Upload to',
+ destinationRoot: 'Knowledge base top level',
+ destinationRootTip: 'Files go to the top level of the knowledge base, not into any folder',
+ destinationTip: 'Files go into the folder "{folder}"',
+ destinationToRoot: 'Upload to the top level instead',
filesAdded: 'Added {count} file(s)',
filesAllDuplicate: 'Selected files are already in the list',
titleManual: 'Confirm online publish',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index 6810b8ae0..338574555 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -5097,6 +5097,11 @@ export default {
vlmModelSelectRequired: '멀티모달이 활성화되었습니다. VLM 모델을 선택하세요',
asrModelSelectRequired: '음성 인식이 활성화되었습니다. ASR 모델을 선택하세요',
continueAdd: '계속 추가',
+ destinationLabel: '업로드 위치',
+ destinationRoot: '지식 베이스 최상위',
+ destinationRootTip: '파일이 폴더가 아닌 지식 베이스 최상위에 업로드됩니다',
+ destinationTip: '파일이 「{folder}」 폴더에 업로드됩니다',
+ destinationToRoot: '최상위에 업로드하도록 변경',
filesAdded: '{count}개 파일이 추가되었습니다',
filesAllDuplicate: '선택한 파일이 이미 목록에 있습니다',
titleManual: '온라인 편집 게시 확인',
@@ -5125,10 +5130,11 @@ export default {
tagEditNoSelected: '선택 없음',
folderTree: {
title: '폴더',
- allDocuments: '전체 문서',
- rootFolder: '루트',
- empty: '폴더를 업로드하면 구조가 여기에 표시됩니다.',
- includeSubfolders: '하위 폴더의 문서 포함',
+ rootRow: '전체 문서',
+ rootRowTip: '지식 베이스의 최상위이며 모든 폴더가 그 아래에 있습니다',
+ scopeToggle: '목록 범위 변경',
+ scopeSubtreeTip: '하위 폴더 포함 중 — 클릭하면 이 단계만 표시합니다',
+ scopeDirectTip: '이 단계만 표시 중 — 클릭하면 하위 폴더를 포함합니다',
collapse: '폴더 접기',
expand: '폴더 펼치기',
collapseFolder: '이 폴더 접기',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 304ca63cf..4ffee2737 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -5097,6 +5097,11 @@ export default {
vlmModelSelectRequired: 'Мультимодальность включена. Выберите модель VLM.',
asrModelSelectRequired: 'Распознавание речи включено. Выберите модель ASR.',
continueAdd: 'Добавить ещё',
+ destinationLabel: 'Загрузить в',
+ destinationRoot: 'Верхний уровень базы знаний',
+ destinationRootTip: 'Файлы попадут на верхний уровень базы знаний, вне папок',
+ destinationTip: 'Файлы попадут в папку «{folder}»',
+ destinationToRoot: 'Загрузить на верхний уровень',
filesAdded: 'Добавлено файлов: {count}',
filesAllDuplicate: 'Выбранные файлы уже в списке',
titleManual: 'Подтверждение публикации',
@@ -5125,10 +5130,11 @@ export default {
tagEditNoSelected: 'Ничего не выбрано',
folderTree: {
title: 'Папки',
- allDocuments: 'Все документы',
- rootFolder: 'Корень',
- empty: 'Загрузите папку — её структура появится здесь.',
- includeSubfolders: 'Включать документы во вложенных папках',
+ rootRow: 'Все документы',
+ rootRowTip: 'Верхний уровень базы знаний — все папки находятся внутри него',
+ scopeToggle: 'Изменить область списка',
+ scopeSubtreeTip: 'Вложенные папки включены — нажмите, чтобы показать только этот уровень',
+ scopeDirectTip: 'Показан только этот уровень — нажмите, чтобы включить вложенные папки',
collapse: 'Свернуть папки',
expand: 'Развернуть папки',
collapseFolder: 'Свернуть эту папку',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index d5e993d83..8c85bc3c1 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -5097,6 +5097,11 @@ export default {
vlmModelSelectRequired: '已启用多模态,请选择 VLM 模型',
asrModelSelectRequired: '已启用语音识别,请选择 ASR 模型',
continueAdd: '继续添加',
+ destinationLabel: '上传到',
+ destinationRoot: '知识库顶层',
+ destinationRootTip: '文件将上传到知识库顶层,不放入任何文件夹',
+ destinationTip: '文件将上传到文件夹「{folder}」',
+ destinationToRoot: '改为上传到顶层',
filesAdded: '已添加 {count} 个文件',
filesAllDuplicate: '所选文件已在列表中',
titleManual: '在线编辑发布确认',
@@ -5125,10 +5130,11 @@ export default {
tagEditNoSelected: '暂未选择',
folderTree: {
title: '目录',
- allDocuments: '全部文档',
- rootFolder: '根目录',
- empty: '上传文件夹后,目录结构会显示在这里。',
- includeSubfolders: '包含子目录中的文档',
+ rootRow: '全部文档',
+ rootRowTip: '知识库顶层,所有文件夹都在它下面',
+ scopeToggle: '切换列表范围',
+ scopeSubtreeTip: '当前包含子目录,点击改为仅显示本层文档',
+ scopeDirectTip: '当前仅显示本层文档,点击改为包含子目录',
collapse: '收起目录',
expand: '展开目录',
collapseFolder: '收起该文件夹',
diff --git a/frontend/src/stores/uploadConfirm.ts b/frontend/src/stores/uploadConfirm.ts
index 350bd4ddd..7ba3223f5 100644
--- a/frontend/src/stores/uploadConfirm.ts
+++ b/frontend/src/stores/uploadConfirm.ts
@@ -26,6 +26,13 @@ export interface UploadConfirmResult {
urls?: string[]
manual?: UploadConfirmManualSource
reparse?: UploadConfirmReparseSource
+ /**
+ * Folder the batch is uploaded into ('' = knowledge base root). Returned as
+ * part of the result because the dialog lets the user change it, so callers
+ * must use this value rather than whatever folder was open when they opened
+ * the dialog.
+ */
+ targetFolder?: string
}
export interface OpenUploadConfirmOptions {
@@ -38,6 +45,8 @@ export interface OpenUploadConfirmOptions {
reparse?: UploadConfirmReparseSource
acceptFileTypes?: string
supportedFileTypes?: string[]
+ /** Folder pre-selected from the sidebar tree; '' means the root. */
+ targetFolder?: string
}
export const useUploadConfirmStore = defineStore('uploadConfirm', {
@@ -52,6 +61,7 @@ export const useUploadConfirmStore = defineStore('uploadConfirm', {
reparse: null as UploadConfirmReparseSource | null,
acceptFileTypes: '',
supportedFileTypes: [] as string[],
+ targetFolder: '',
pendingResolve: null as ((value: UploadConfirmResult) => void) | null,
pendingReject: null as (() => void) | null,
}),
@@ -71,6 +81,7 @@ export const useUploadConfirmStore = defineStore('uploadConfirm', {
this.reparse = options.reparse || null
this.acceptFileTypes = options.acceptFileTypes || ''
this.supportedFileTypes = options.supportedFileTypes ? [...options.supportedFileTypes] : []
+ this.targetFolder = options.targetFolder || ''
this.pendingResolve = resolve
this.pendingReject = reject
})
@@ -97,6 +108,7 @@ export const useUploadConfirmStore = defineStore('uploadConfirm', {
this.reparse = null
this.acceptFileTypes = ''
this.supportedFileTypes = []
+ this.targetFolder = ''
this.pendingResolve = null
this.pendingReject = null
},
diff --git a/frontend/src/views/knowledge/KnowledgeBase.vue b/frontend/src/views/knowledge/KnowledgeBase.vue
index 8af91b094..acd03a9d9 100644
--- a/frontend/src/views/knowledge/KnowledgeBase.vue
+++ b/frontend/src/views/knowledge/KnowledgeBase.vue
@@ -63,6 +63,7 @@ import {
folderBreadcrumbs as buildFolderBreadcrumbs,
folderPathExists as folderExistsInTree,
isFolderUpload,
+ ROOT_FOLDER_PATH,
} from './folderTree';
import { useI18n } from 'vue-i18n';
import { useMarqueeSelect } from '@/hooks/useMarqueeSelect';
@@ -604,11 +605,12 @@ const disableFutureDate = { after: new Date(new Date().setHours(23, 59, 59, 999)
// ── Folder tree (documents uploaded as a folder keep their relative path) ──
const FOLDER_TREE_COLLAPSED_KEY = 'weknora.kbFolderTreeCollapsed';
const FOLDER_TREE_RECURSIVE_KEY = 'weknora.kbFolderRecursive';
-const readStoredFlag = (key: string) => {
+const readStoredFlag = (key: string, fallback = false) => {
try {
- return localStorage.getItem(key) === 'true';
+ const raw = localStorage.getItem(key);
+ return raw === null ? fallback : raw === 'true';
} catch {
- return false;
+ return fallback;
}
};
const writeStoredFlag = (key: string, value: boolean) => {
@@ -620,23 +622,22 @@ const writeStoredFlag = (key: string, value: boolean) => {
};
const folderTree = ref<KnowledgeFolderTree | null>(null);
const folderTreeLoading = ref(false);
-// `null` browses every folder (the historical flat list), `''` is the knowledge
-// base root, any other value is a folder path.
-const selectedFolderPath = ref<string | null>(null);
+// The selected folder path; ROOT_FOLDER_PATH ('') is the knowledge base root,
+// which is a real node of the tree rather than a separate "all documents" mode.
+// Combined with folderRecursive it covers both "everything" (root + recursive)
+// and "documents not inside any folder" (root + direct only).
+const selectedFolderPath = ref<string>(ROOT_FOLDER_PATH);
const folderTreeCollapsed = ref(readStoredFlag(FOLDER_TREE_COLLAPSED_KEY));
-const folderRecursive = ref(readStoredFlag(FOLDER_TREE_RECURSIVE_KEY));
+// Recursive by default: a freshly opened knowledge base should list everything,
+// and a folder that only holds sub-folders would otherwise look empty.
+const folderRecursive = ref(readStoredFlag(FOLDER_TREE_RECURSIVE_KEY, true));
const hasFolders = computed(() => (folderTree.value?.folders?.length ?? 0) > 0);
// The folder column only earns its space once the knowledge base actually has
// folders, so knowledge bases filled with single-file uploads look unchanged.
-const showFolderTree = computed(() => !isFAQ.value && (hasFolders.value || selectedFolderPath.value !== null));
+const showFolderTree = computed(() => !isFAQ.value && hasFolders.value);
// Rows only need their folder shown when the current list can span folders.
-const showDocumentFolderPath = computed(
- () => hasFolders.value && (selectedFolderPath.value === null || folderRecursive.value),
-);
+const showDocumentFolderPath = computed(() => hasFolders.value && folderRecursive.value);
const folderBreadcrumbs = computed(() => buildFolderBreadcrumbs(selectedFolderPath.value));
-// Uploads land in the folder currently being browsed; "all documents" and the
-// root row both mean "no prefix".
-const uploadTargetFolder = computed(() => selectedFolderPath.value || '');
const filterParams = computed(() => {
const [start, end] = updatedTimeRange.value || [];
@@ -648,7 +649,9 @@ const filterParams = computed(() => {
source: selectedSource.value || undefined,
start_time: start ? `${start} 00:00:00` : undefined,
end_time: end ? `${end} 23:59:59` : undefined,
- folder_path: selectedFolderPath.value === null ? undefined : selectedFolderPath.value,
+ // The root folder with the recursive scope is equivalent to no folder filter
+ // at all, so knowledge bases without folders behave exactly as before.
+ folder_path: selectedFolderPath.value,
folder_recursive: folderRecursive.value,
};
});
@@ -761,10 +764,9 @@ const loadFolderTree = async (kbIdValue: string) => {
if (!isCurrentKb(kbIdValue)) return;
folderTree.value = (res?.data as KnowledgeFolderTree) || null;
// A folder can disappear (its last document was deleted or moved); fall
- // back to the flat list instead of leaving an empty, unreachable view.
- const path = selectedFolderPath.value;
- if (path && !folderExistsInTree(folderTree.value?.folders || [], path)) {
- selectedFolderPath.value = null;
+ // back to the root instead of leaving an empty, unreachable view.
+ if (!folderExistsInTree(folderTree.value?.folders || [], selectedFolderPath.value)) {
+ selectedFolderPath.value = ROOT_FOLDER_PATH;
}
} catch (error) {
if (!isCurrentKb(kbIdValue)) return;
@@ -777,7 +779,7 @@ const loadFolderTree = async (kbIdValue: string) => {
}
};
-const handleFolderSelect = (path: string | null) => {
+const handleFolderSelect = (path: string) => {
if (selectedFolderPath.value === path) return;
selectedFolderPath.value = path;
};
@@ -1030,7 +1032,7 @@ watch(() => kbId.value, (newKbId, oldKbId) => {
tagPage.value = 1;
uiStore.clearSelectedTagIds();
folderTree.value = null;
- selectedFolderPath.value = null;
+ selectedFolderPath.value = ROOT_FOLDER_PATH;
}
loadKnowledgeBaseInfo(newKbId);
}, { immediate: true });
@@ -1507,8 +1509,8 @@ const AUDIO_EXTENSIONS = ['mp3', 'wav', 'm4a', 'flac', 'ogg'];
const uploadConfirmStore = useUploadConfirmStore();
-const getFolderUploadFileName = (file: File) =>
- buildUploadFileName(file, uploadTargetFolder.value);
+const getFolderUploadFileName = (file: File, targetFolder: string) =>
+ buildUploadFileName(file, targetFolder);
const showUploadResultMessages = (
successCount: number,
@@ -1545,7 +1547,12 @@ const showUploadResultMessages = (
const executeUploadBatch = async (
files: File[],
- options: { processConfig?: KnowledgeProcessOverrides; tagIds?: string[] } = {},
+ options: {
+ processConfig?: KnowledgeProcessOverrides;
+ tagIds?: string[];
+ /** Destination folder confirmed in the upload dialog; '' is the root. */
+ targetFolder?: string;
+ } = {},
) => {
const targetKbId = kbId.value;
if (!targetKbId || files.length === 0) {
@@ -1569,7 +1576,7 @@ const executeUploadBatch = async (
process_config?: KnowledgeProcessOverrides
} = { file, tag_ids: tagIdsToUpload };
- const fileName = getFolderUploadFileName(file);
+ const fileName = getFolderUploadFileName(file, options.targetFolder || ROOT_FOLDER_PATH);
if (fileName) uploadData.fileName = fileName;
if (options.processConfig) {
uploadData.process_config = options.processConfig;
@@ -1676,7 +1683,11 @@ const handleUploadConfirmResult = async (result: UploadConfirmResult) => {
if (hasFolderPaths) {
MessagePlugin.info(t('knowledgeBase.uploadingFolder', { total: files.length }));
}
- await executeUploadBatch(files, { processConfig, tagIds });
+ await executeUploadBatch(files, {
+ processConfig,
+ tagIds,
+ targetFolder: result.targetFolder || ROOT_FOLDER_PATH,
+ });
}
for (const url of urls) {
@@ -1696,6 +1707,9 @@ const openUploadConfirmDialog = async (files: File[], urls: string[] = []) => {
urls,
acceptFileTypes: acceptFileTypes.value,
supportedFileTypes: [...supportedFileTypes.value],
+ // Pre-fill the destination with the folder being browsed; the dialog shows
+ // it and lets the user send the batch to the root instead.
+ targetFolder: selectedFolderPath.value,
});
await handleUploadConfirmResult(result);
} catch {
@@ -2252,14 +2266,11 @@ async function createNewSession(value: string): Promise<void> {
@update:recursive="handleFolderRecursiveChange" />
<div class="tag-content">
<div class="doc-card-area">
- <nav v-if="selectedFolderPath !== null" class="doc-folder-path" :aria-label="$t('knowledgeBase.folderTree.title')">
- <button type="button" class="doc-folder-path__crumb" @click="handleFolderSelect(null)">
- {{ $t('knowledgeBase.folderTree.allDocuments') }}
+ <nav v-if="showFolderTree && folderBreadcrumbs.length" class="doc-folder-path"
+ :aria-label="$t('knowledgeBase.folderTree.title')">
+ <button type="button" class="doc-folder-path__crumb" @click="handleFolderSelect('')">
+ {{ $t('knowledgeBase.folderTree.rootRow') }}
</button>
- <template v-if="!folderBreadcrumbs.length">
- <t-icon name="chevron-right" class="doc-folder-path__sep" />
- <span class="doc-folder-path__crumb is-current">{{ $t('knowledgeBase.folderTree.rootFolder') }}</span>
- </template>
<template v-for="(crumb, index) in folderBreadcrumbs" :key="crumb.path">
<t-icon name="chevron-right" class="doc-folder-path__sep" />
<span v-if="index === folderBreadcrumbs.length - 1" class="doc-folder-path__crumb is-current">
diff --git a/frontend/src/views/knowledge/components/KbFolderTree.vue b/frontend/src/views/knowledge/components/KbFolderTree.vue
index 88339e9e0..3744df893 100644
--- a/frontend/src/views/knowledge/components/KbFolderTree.vue
+++ b/frontend/src/views/knowledge/components/KbFolderTree.vue
@@ -4,16 +4,21 @@
<template v-if="!collapsed">
<span class="kb-folder-tree__title">{{ t('knowledgeBase.folderTree.title') }}</span>
<div class="kb-folder-tree__header-actions">
- <t-tooltip :content="t('knowledgeBase.folderTree.includeSubfolders')" placement="top">
+ <t-tooltip
+ :content="recursive
+ ? t('knowledgeBase.folderTree.scopeSubtreeTip')
+ : t('knowledgeBase.folderTree.scopeDirectTip')"
+ placement="top"
+ >
<button
type="button"
class="kb-folder-tree__icon-btn"
:class="{ active: recursive }"
:aria-pressed="recursive"
- :aria-label="t('knowledgeBase.folderTree.includeSubfolders')"
+ :aria-label="t('knowledgeBase.folderTree.scopeToggle')"
@click="emit('update:recursive', !recursive)"
>
- <t-icon name="tree-round-dot-vertical" size="15px" />
+ <t-icon :name="recursive ? 'tree-round-dot-vertical' : 'file-1'" size="15px" />
</button>
</t-tooltip>
<t-tooltip :content="t('knowledgeBase.folderTree.collapse')" placement="top">
@@ -41,70 +46,38 @@
</div>
<div v-if="!collapsed" class="kb-folder-tree__body">
- <template v-if="loading && !rows.length">
+ <template v-if="loading && !tree">
<div v-for="n in 5" :key="'folder-skel-' + n" class="kb-folder-tree__skeleton">
<t-skeleton animation="gradient" :row-col="[{ width: '100%', height: '16px' }]" />
</div>
</template>
<template v-else>
- <button
- type="button"
- class="kb-folder-row kb-folder-row--all"
- :class="{ active: selectedPath === null }"
- @click="emit('select', null)"
- >
- <t-icon name="folder-open" class="kb-folder-row__icon" />
- <span class="kb-folder-row__label">{{ t('knowledgeBase.folderTree.allDocuments') }}</span>
- <span class="kb-folder-row__count">{{ tree?.total_document_count ?? 0 }}</span>
- </button>
-
- <button
- v-if="showRootRow"
- type="button"
- class="kb-folder-row"
- :class="{ active: selectedPath === '' }"
- :style="{ '--kb-folder-depth': 0 }"
- @click="emit('select', '')"
- >
- <span class="kb-folder-row__toggle-placeholder" aria-hidden="true" />
- <t-icon name="folder" class="kb-folder-row__icon" />
- <span class="kb-folder-row__label">{{ t('knowledgeBase.folderTree.rootFolder') }}</span>
- <span class="kb-folder-row__count">{{ tree?.root_document_count ?? 0 }}</span>
- </button>
-
<button
v-for="row in rows"
- :key="row.node.path"
+ :key="row.path || '__root__'"
type="button"
class="kb-folder-row"
- :class="{ active: selectedPath === row.node.path }"
+ :class="{ active: selectedPath === row.path, 'is-root': row.kind === 'root' }"
:style="{ '--kb-folder-depth': row.depth }"
- :title="row.node.path"
- @click="emit('select', row.node.path)"
+ :title="rowTitle(row)"
+ @click="emit('select', row.path)"
>
<span
- v-if="row.node.children?.length"
+ v-if="row.hasChildren"
class="kb-folder-row__toggle"
role="button"
- :aria-label="t(expanded.has(row.node.path)
+ :aria-label="t(isExpanded(row.path)
? 'knowledgeBase.folderTree.collapseFolder'
: 'knowledgeBase.folderTree.expandFolder')"
- @click.stop="toggle(row.node.path)"
+ @click.stop="toggle(row.path)"
>
- <t-icon :name="expanded.has(row.node.path) ? 'chevron-down' : 'chevron-right'" />
+ <t-icon :name="isExpanded(row.path) ? 'chevron-down' : 'chevron-right'" />
</span>
<span v-else class="kb-folder-row__toggle-placeholder" aria-hidden="true" />
- <t-icon
- :name="expanded.has(row.node.path) && row.node.children?.length ? 'folder-open' : 'folder'"
- class="kb-folder-row__icon"
- />
- <span class="kb-folder-row__label">{{ row.node.name }}</span>
- <span class="kb-folder-row__count">{{ recursive ? row.node.total_count : row.node.document_count }}</span>
+ <t-icon :name="rowIcon(row)" class="kb-folder-row__icon" />
+ <span class="kb-folder-row__label">{{ rowLabel(row) }}</span>
+ <span class="kb-folder-row__count">{{ folderRowCount(row, recursive) }}</span>
</button>
-
- <p v-if="!rows.length && !loading" class="kb-folder-tree__empty">
- {{ t('knowledgeBase.folderTree.empty') }}
- </p>
</template>
</div>
</aside>
@@ -114,38 +87,53 @@
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import type { KnowledgeFolderTree } from '@/api/knowledge-base/index'
-import { flattenFolderRows, folderAncestorPaths } from '../folderTree'
+import {
+ buildFolderRows,
+ folderAncestorPaths,
+ folderRowCount,
+ ROOT_FOLDER_PATH,
+ type FolderRow,
+} from '../folderTree'
const props = withDefaults(defineProps<{
tree: KnowledgeFolderTree | null
- /** `null` = every folder, `''` = knowledge base root, otherwise a folder path. */
- selectedPath: string | null
+ /** Selected folder path; the empty string is the knowledge base root. */
+ selectedPath: string
loading?: boolean
collapsed?: boolean
+ /** When true a folder lists its sub-folders' documents too. */
recursive?: boolean
}>(), {
loading: false,
collapsed: false,
- recursive: false,
+ recursive: true,
})
const emit = defineEmits<{
- select: [path: string | null]
+ select: [path: string]
'update:collapsed': [collapsed: boolean]
'update:recursive': [recursive: boolean]
}>()
const { t } = useI18n()
-const expanded = ref(new Set<string>())
+// The root starts expanded so the uploaded structure is visible without a click.
+const expanded = ref(new Set<string>([ROOT_FOLDER_PATH]))
+
+const rows = computed(() => buildFolderRows(props.tree, expanded.value))
+
+const isExpanded = (path: string) => expanded.value.has(path)
-/**
- * The root row only makes sense once folders exist: without it a knowledge base
- * with no folder upload would show a redundant second "all documents" row.
- */
-const showRootRow = computed(() => (props.tree?.folders?.length ?? 0) > 0)
+const rowLabel = (row: FolderRow) =>
+ row.kind === 'root' ? t('knowledgeBase.folderTree.rootRow') : row.name
-const rows = computed(() => flattenFolderRows(props.tree?.folders ?? [], expanded.value))
+const rowIcon = (row: FolderRow) => {
+ if (row.kind === 'root') return 'folder-open'
+ return row.hasChildren && isExpanded(row.path) ? 'folder-open' : 'folder'
+}
+
+const rowTitle = (row: FolderRow) =>
+ row.kind === 'root' ? t('knowledgeBase.folderTree.rootRowTip') : row.path
const toggle = (path: string) => {
const next = new Set(expanded.value)
@@ -154,27 +142,28 @@ const toggle = (path: string) => {
expanded.value = next
}
-// Keep the selected folder reachable: every ancestor of the active path is
-// expanded, both on first load and when the selection changes from elsewhere
-// (e.g. clicking a document's folder chip in the list).
+// Keep the selected folder reachable: expand the root and every folder above
+// the active path, both on first load and when the selection changes from
+// elsewhere (e.g. clicking a document's folder chip in the list).
watch(
() => [props.selectedPath, props.tree] as const,
() => {
- const ancestors = folderAncestorPaths(props.selectedPath)
- if (ancestors.length === 0) return
const next = new Set(expanded.value)
- ancestors.forEach((path) => next.add(path))
+ folderAncestorPaths(props.selectedPath).forEach((path) => next.add(path))
expanded.value = next
},
{ immediate: true },
)
-// First load auto-expands the top level so folders are visible without a click.
+// First load also opens the top-level folders, so a two-level upload is visible
+// in full without any expanding.
watch(
() => props.tree,
(tree) => {
- if (!tree?.folders?.length || expanded.value.size > 0) return
- expanded.value = new Set(tree.folders.map((folder) => folder.path))
+ if (!tree?.folders?.length || expanded.value.size > 1) return
+ const next = new Set(expanded.value)
+ tree.folders.forEach((folder) => next.add(folder.path))
+ expanded.value = next
},
{ immediate: true },
)
@@ -308,10 +297,10 @@ watch(
color: var(--td-brand-color);
}
}
-}
-.kb-folder-row--all {
- margin-bottom: 2px;
+ &.is-root .kb-folder-row__label {
+ font-weight: 500;
+ }
}
.kb-folder-row__toggle,
@@ -359,11 +348,4 @@ watch(
color: var(--td-text-color-placeholder);
font-variant-numeric: tabular-nums;
}
-
-.kb-folder-tree__empty {
- margin: 8px;
- font-size: 12px;
- line-height: 1.6;
- color: var(--td-text-color-placeholder);
-}
</style>
diff --git a/frontend/src/views/knowledge/components/UploadConfirmDialog.test.ts b/frontend/src/views/knowledge/components/UploadConfirmDialog.test.ts
index 5af8342ff..18dcdfc3c 100644
--- a/frontend/src/views/knowledge/components/UploadConfirmDialog.test.ts
+++ b/frontend/src/views/knowledge/components/UploadConfirmDialog.test.ts
@@ -17,7 +17,7 @@ test('selects multiple document tags and returns them with the confirmation resu
test('uses confirmed tags for file and URL imports instead of reading the list filter at upload time', () => {
assert.match(knowledgeBase, /const tagIds = result\.tagIds \|\| \[\]/)
- assert.match(knowledgeBase, /executeUploadBatch\(files, \{ processConfig, tagIds \}\)/)
+ assert.match(knowledgeBase, /executeUploadBatch\(files, \{[\s\S]*?\btagIds,[\s\S]*?\}\)/)
assert.match(knowledgeBase, /executeUrlImport\(url, processConfig, tagIds\)/)
assert.doesNotMatch(
knowledgeBase,
@@ -25,6 +25,18 @@ test('uses confirmed tags for file and URL imports instead of reading the list f
)
})
+// Browsing a folder pre-fills the upload destination, so the dialog must show it
+// and the batch must use the folder the user confirmed there — never the sidebar
+// selection as it stands when the uploads actually start.
+test('takes the upload destination folder from the confirmation result', () => {
+ assert.match(host, /:target-folder="uploadConfirmStore\.targetFolder"/)
+ assert.match(dialog, /class="destination-row"/)
+ assert.match(dialog, /targetFolder: localTargetFolder\.value/)
+ assert.match(dialog, /@click="localTargetFolder = ''"/)
+ assert.match(knowledgeBase, /targetFolder: result\.targetFolder \|\| ROOT_FOLDER_PATH/)
+ assert.match(knowledgeBase, /targetFolder: selectedFolderPath\.value/)
+})
+
test('routes global knowledge file drops through the upload confirmation flow', () => {
assert.match(platform, /weknora:knowledge-file-drop/)
assert.match(knowledgeBase, /handleKnowledgeFileDrop/)
diff --git a/frontend/src/views/knowledge/components/UploadConfirmDialog.vue b/frontend/src/views/knowledge/components/UploadConfirmDialog.vue
index ad22862b4..b12925b88 100644
--- a/frontend/src/views/knowledge/components/UploadConfirmDialog.vue
+++ b/frontend/src/views/knowledge/components/UploadConfirmDialog.vue
@@ -28,6 +28,24 @@
</div>
</div>
+ <!-- Where the batch lands. Shown for every file upload so browsing
+ a folder never silently decides the destination. -->
+ <div v-if="mode === 'file'" class="destination-row">
+ <t-icon :name="localTargetFolder ? 'folder' : 'folder-open'" class="destination-icon" />
+ <span class="destination-label">{{ t('uploadConfirm.destinationLabel') }}</span>
+ <span class="destination-path" :title="destinationTitle">{{ destinationText }}</span>
+ <t-tooltip v-if="localTargetFolder" :content="t('uploadConfirm.destinationToRoot')" placement="top">
+ <button
+ type="button"
+ class="destination-clear"
+ :aria-label="t('uploadConfirm.destinationToRoot')"
+ @click="localTargetFolder = ''"
+ >
+ <t-icon name="close-circle-filled" />
+ </button>
+ </t-tooltip>
+ </div>
+
<div class="files-list-wrap">
<div v-if="mode === 'manual' && manualPreview" class="manual-source-panel">
<p class="manual-source-title" :title="manualPreview.title">{{ manualPreview.title }}</p>
@@ -65,7 +83,12 @@
</span>
<div class="file-meta">
<span class="file-name" :title="file.name">{{ file.name }}</span>
- <span class="file-size">{{ formatFileSize(file.size) }}</span>
+ <span class="file-size">
+ {{ formatFileSize(file.size) }}
+ <template v-if="fileRelativeDir(file)">
+ · <span class="file-relative-dir" :title="fileRelativeDir(file)">{{ fileRelativeDir(file) }}</span>
+ </template>
+ </span>
</div>
<button
type="button"
@@ -583,6 +606,8 @@ const props = withDefaults(defineProps<{
tagId?: string
acceptFileTypes?: string
supportedFileTypes?: string[]
+ /** Folder the batch will be uploaded into; '' means the knowledge base root. */
+ targetFolder?: string
}>(), {
mode: 'file',
files: () => [],
@@ -592,6 +617,7 @@ const props = withDefaults(defineProps<{
reparsePreview: null,
acceptFileTypes: '',
supportedFileTypes: () => [],
+ targetFolder: '',
})
const emit = defineEmits<{
@@ -615,12 +641,36 @@ const tagsLoadFailed = ref(false)
const chunkingMoreOpen = ref(false)
const activeSection = ref<ConfigSectionKey>('tags')
const uiState = ref<UploadUIState>(createDefaultUIState())
+// Destination folder for this batch. Pre-filled from the sidebar tree, but
+// editable here so browsing a folder never silently decides where files land.
+const localTargetFolder = ref('')
const dialogVisible = computed({
get: () => props.visible,
set: (value: boolean) => emit('update:visible', value),
})
+const destinationText = computed(() =>
+ localTargetFolder.value || t('uploadConfirm.destinationRoot'),
+)
+
+const destinationTitle = computed(() =>
+ localTargetFolder.value
+ ? t('uploadConfirm.destinationTip', { folder: localTargetFolder.value })
+ : t('uploadConfirm.destinationRootTip'),
+)
+
+/**
+ * Directory a folder-upload file came from, shown under its name so a batch of
+ * same-named files (README.md in five folders) stays distinguishable and the
+ * resulting structure is visible before confirming.
+ */
+function fileRelativeDir(file: File): string {
+ const relativePath = (file as File & { webkitRelativePath?: string }).webkitRelativePath
+ if (!relativePath) return ''
+ return relativePath.split('/').filter(Boolean).slice(0, -1).join('/')
+}
+
function getModelName(modelId: string): string {
if (!modelId) return t('uploadConfirm.notSet')
const model = allModels.value.find((m: any) => m.id === modelId)
@@ -1189,6 +1239,7 @@ watch(
localFiles.value = props.mode === 'file' ? [...(props.files || [])] : []
localUrls.value = props.mode === 'file' ? [...(props.urls || [])] : []
selectedTagIds.value = props.mode === 'reparse' ? [] : [...(props.tagIds || [])]
+ localTargetFolder.value = props.mode === 'file' ? (props.targetFolder || '') : ''
initFromKbInfo(props.kbInfo)
if (props.mode === 'reparse') {
applyOverridesToState(props.reparsePreview?.processOverrides)
@@ -1330,6 +1381,7 @@ const handleConfirm = () => {
tagIds: [...selectedTagIds.value],
files: [...localFiles.value],
urls: [...localUrls.value],
+ targetFolder: localTargetFolder.value,
})
}
emit('update:visible', false)
@@ -1451,6 +1503,65 @@ const handleConfirm = () => {
color: var(--td-text-color-secondary);
}
+.destination-row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ flex-shrink: 0;
+ margin: 0 8px;
+ padding: 6px 8px;
+ border-radius: 6px;
+ background: var(--td-bg-color-secondarycontainer);
+ font-size: 12px;
+ line-height: 18px;
+}
+
+.destination-icon {
+ flex-shrink: 0;
+ font-size: 14px;
+ color: var(--td-text-color-placeholder);
+}
+
+.destination-label {
+ flex-shrink: 0;
+ color: var(--td-text-color-placeholder);
+}
+
+.destination-path {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ direction: rtl;
+ text-align: left;
+ color: var(--td-text-color-primary);
+}
+
+.destination-clear {
+ display: flex;
+ flex-shrink: 0;
+ align-items: center;
+ justify-content: center;
+ width: 18px;
+ height: 18px;
+ padding: 0;
+ border: 0;
+ border-radius: 50%;
+ background: transparent;
+ color: var(--td-text-color-placeholder);
+ cursor: pointer;
+ transition: color 0.15s ease;
+
+ &:hover {
+ color: var(--td-text-color-secondary);
+ }
+
+ .t-icon {
+ font-size: 14px;
+ }
+}
+
.files-list-wrap {
display: flex;
flex: 1;
@@ -1526,6 +1637,13 @@ const handleConfirm = () => {
font-size: 11px;
line-height: 1.3;
color: var(--td-text-color-placeholder);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.file-relative-dir {
+ color: var(--td-text-color-secondary);
}
.file-remove {
diff --git a/frontend/src/views/knowledge/folderTree.test.ts b/frontend/src/views/knowledge/folderTree.test.ts
index 86f93988b..d49f4c09b 100644
--- a/frontend/src/views/knowledge/folderTree.test.ts
+++ b/frontend/src/views/knowledge/folderTree.test.ts
@@ -2,15 +2,17 @@ import assert from 'node:assert/strict'
import test from 'node:test'
import {
+ buildFolderRows,
buildUploadFileName,
- flattenFolderRows,
folderAncestorPaths,
folderBreadcrumbs,
folderPathExists,
+ folderRowCount,
isFolderUpload,
+ ROOT_FOLDER_PATH,
} from './folderTree.ts'
-const tree = [
+const folders = [
{
path: 'handbook',
name: 'handbook',
@@ -31,30 +33,31 @@ const tree = [
{ path: 'design', name: 'design', document_count: 1, total_count: 1 },
]
-test('a plain single-file upload at the root sends no path-qualified name', () => {
- assert.equal(buildUploadFileName({ name: 'report.pdf' }, null), undefined)
- assert.equal(buildUploadFileName({ name: 'report.pdf' }, ''), undefined)
+const tree = { root_document_count: 2, total_document_count: 7, folders }
+
+test('a plain single-file upload into the root sends no path-qualified name', () => {
+ assert.equal(buildUploadFileName({ name: 'report.pdf' }, ROOT_FOLDER_PATH), undefined)
})
test('a folder upload keeps the picked directory as the top-level folder', () => {
assert.equal(
- buildUploadFileName({ name: 'day-one.md', webkitRelativePath: 'handbook/onboarding/day-one.md' }, null),
+ buildUploadFileName({ name: 'day-one.md', webkitRelativePath: 'handbook/onboarding/day-one.md' }, ''),
'handbook/onboarding/day-one.md',
)
assert.equal(
- buildUploadFileName({ name: 'README.md', webkitRelativePath: 'handbook/README.md' }, null),
+ buildUploadFileName({ name: 'README.md', webkitRelativePath: 'handbook/README.md' }, ''),
'handbook/README.md',
)
})
-test('uploads land in the folder currently open in the sidebar', () => {
+test('files land in the destination folder confirmed for the batch', () => {
assert.equal(
buildUploadFileName({ name: 'report.pdf' }, 'handbook/policies'),
'handbook/policies/report.pdf',
)
})
-test('browsing a folder and uploading a folder nests one inside the other', () => {
+test('a folder upload into a destination folder nests one inside the other', () => {
assert.equal(
buildUploadFileName({ name: 'tokens.md', webkitRelativePath: 'design/tokens.md' }, 'handbook'),
'handbook/design/tokens.md',
@@ -71,50 +74,78 @@ test('breadcrumbs walk from the top level down to the selected folder', () => {
{ name: 'handbook', path: 'handbook' },
{ name: 'onboarding', path: 'handbook/onboarding' },
])
- // "all documents" and the knowledge base root have no folder crumbs.
- assert.deepEqual(folderBreadcrumbs(null), [])
- assert.deepEqual(folderBreadcrumbs(''), [])
+ // The root row needs no crumbs of its own.
+ assert.deepEqual(folderBreadcrumbs(ROOT_FOLDER_PATH), [])
+})
+
+test('ancestor paths always include the root so the tree opens down to the selection', () => {
+ assert.deepEqual(folderAncestorPaths('a/b/c'), ['', 'a', 'a/b', 'a/b/c'])
+ assert.deepEqual(folderAncestorPaths(ROOT_FOLDER_PATH), [''])
})
-test('ancestor paths include the folder itself so the selected row stays visible', () => {
- assert.deepEqual(folderAncestorPaths('a/b/c'), ['a', 'a/b', 'a/b/c'])
- assert.deepEqual(folderAncestorPaths(null), [])
+test('the root always exists, other folders are looked up at any depth', () => {
+ assert.equal(folderPathExists(folders, ROOT_FOLDER_PATH), true)
+ assert.equal(folderPathExists([], ROOT_FOLDER_PATH), true)
+ assert.equal(folderPathExists(folders, 'handbook/onboarding/day-one'), true)
+ assert.equal(folderPathExists(folders, 'handbook/policies'), false)
})
-test('folder lookup searches the whole depth of the tree', () => {
- assert.equal(folderPathExists(tree, 'handbook/onboarding/day-one'), true)
- assert.equal(folderPathExists(tree, 'design'), true)
- assert.equal(folderPathExists(tree, 'handbook/policies'), false)
+test('the root is the only row when it is collapsed', () => {
+ const rows = buildFolderRows(tree, new Set())
+ assert.equal(rows.length, 1)
+ assert.equal(rows[0].kind, 'root')
+ assert.equal(rows[0].path, ROOT_FOLDER_PATH)
+ assert.equal(rows[0].hasChildren, true)
})
-test('collapsed folders hide their subtree', () => {
- const rows = flattenFolderRows(tree, new Set())
+test('top-level folders are children of the root, not its siblings', () => {
+ const rows = buildFolderRows(tree, new Set([ROOT_FOLDER_PATH]))
assert.deepEqual(
- rows.map((row) => [row.node.path, row.depth]),
+ rows.map((row) => [row.path, row.depth]),
[
- ['handbook', 0],
- ['design', 0],
+ ['', 0],
+ ['handbook', 1],
+ ['design', 1],
],
)
})
-test('expanding a folder reveals its children indented one level deeper', () => {
- const rows = flattenFolderRows(tree, new Set(['handbook', 'handbook/onboarding']))
+test('expanding nested folders indents each level one step deeper', () => {
+ const rows = buildFolderRows(tree, new Set([ROOT_FOLDER_PATH, 'handbook', 'handbook/onboarding']))
assert.deepEqual(
- rows.map((row) => [row.node.path, row.depth]),
+ rows.map((row) => [row.path, row.depth]),
[
- ['handbook', 0],
- ['handbook/onboarding', 1],
- ['handbook/onboarding/day-one', 2],
- ['design', 0],
+ ['', 0],
+ ['handbook', 1],
+ ['handbook/onboarding', 2],
+ ['handbook/onboarding/day-one', 3],
+ ['design', 1],
],
)
})
-test('expanding a child without its parent keeps the child hidden', () => {
- const rows = flattenFolderRows(tree, new Set(['handbook/onboarding']))
- assert.deepEqual(
- rows.map((row) => row.node.path),
- ['handbook', 'design'],
- )
+test('expanding a folder whose parent is collapsed keeps it hidden', () => {
+ const rows = buildFolderRows(tree, new Set([ROOT_FOLDER_PATH, 'handbook/onboarding']))
+ assert.deepEqual(rows.map((row) => row.path), ['', 'handbook', 'design'])
+})
+
+test('a knowledge base without folders shows a root row with no toggle', () => {
+ const rows = buildFolderRows({ root_document_count: 3, total_document_count: 3, folders: [] }, new Set([ROOT_FOLDER_PATH]))
+ assert.equal(rows.length, 1)
+ assert.equal(rows[0].hasChildren, false)
+})
+
+test('an unloaded tree still yields a root row so the sidebar never renders empty', () => {
+ const rows = buildFolderRows(null, new Set([ROOT_FOLDER_PATH]))
+ assert.deepEqual(rows.map((row) => [row.kind, row.totalCount]), [['root', 0]])
+})
+
+// The count on a row must match what selecting it puts in the list, otherwise
+// the sidebar and the document list contradict each other.
+test('row counts follow the recursive scope', () => {
+ const [root, handbook] = buildFolderRows(tree, new Set([ROOT_FOLDER_PATH]))
+ assert.equal(folderRowCount(root, true), 7)
+ assert.equal(folderRowCount(root, false), 2)
+ assert.equal(folderRowCount(handbook, true), 4)
+ assert.equal(folderRowCount(handbook, false), 1)
})
diff --git a/frontend/src/views/knowledge/folderTree.ts b/frontend/src/views/knowledge/folderTree.ts
index 4d25b5687..12bf01000 100644
--- a/frontend/src/views/knowledge/folderTree.ts
+++ b/frontend/src/views/knowledge/folderTree.ts
@@ -1,12 +1,14 @@
-import type { KnowledgeFolderNode } from '@/api/knowledge-base/index'
+import type { KnowledgeFolderNode, KnowledgeFolderTree } from '@/api/knowledge-base/index'
/**
- * Pure helpers behind the knowledge base folder sidebar. The document page keeps
- * folder state as a single value with three meanings, so it is worth naming:
- * `null` browses every folder (the historical flat list), `''` is the knowledge
- * base root, and any other string is a folder path such as "docs/spec".
+ * Pure helpers behind the knowledge base folder sidebar.
+ *
+ * A folder selection is just a path, where the empty string is the knowledge
+ * base root. The root is a real node of the tree — every top-level folder is
+ * its child — so there is no separate "all documents" pseudo-row: what the root
+ * row lists is decided by the same recursive switch as any other folder.
*/
-export type FolderSelection = string | null
+export const ROOT_FOLDER_PATH = ''
/** Minimal shape of the browser File objects the upload flow deals with. */
export type UploadFileLike = {
@@ -14,10 +16,20 @@ export type UploadFileLike = {
webkitRelativePath?: string
}
-/** One rendered row of the flattened tree. */
+/**
+ * One rendered row of the flattened tree. The root row carries the knowledge
+ * base totals; the component supplies its label.
+ */
export type FolderRow = {
- node: KnowledgeFolderNode
+ kind: 'root' | 'folder'
+ path: string
+ name: string
depth: number
+ /** Documents stored directly in this folder. */
+ documentCount: number
+ /** Documents in this folder plus every descendant folder. */
+ totalCount: number
+ hasChildren: boolean
}
/**
@@ -31,19 +43,19 @@ export function isFolderUpload(file: UploadFileLike): boolean {
/**
* Build the path-qualified `fileName` form field that the backend splits into
- * folder_path + file_name. Two sources are combined: the folder currently open
- * in the sidebar (so uploads land where the user is looking) and the browser's
- * webkitRelativePath, whose picked directory becomes the top-level tree node.
+ * folder_path + file_name. Two sources are combined: the destination folder
+ * chosen for the batch and the browser's webkitRelativePath, whose picked
+ * directory becomes a folder under that destination.
*
- * Returns undefined for a plain single-file upload at the knowledge base root so
- * that request stays byte-identical to the pre-folder behaviour.
+ * Returns undefined for a plain single-file upload into the root so that request
+ * stays byte-identical to the pre-folder behaviour.
*/
export function buildUploadFileName(
file: UploadFileLike,
- currentFolder: FolderSelection,
+ targetFolder: string,
): string | undefined {
const segments: string[] = []
- if (currentFolder) segments.push(currentFolder)
+ if (targetFolder) segments.push(targetFolder)
if (file.webkitRelativePath) {
segments.push(...file.webkitRelativePath.split('/').filter(Boolean).slice(0, -1))
}
@@ -51,8 +63,11 @@ export function buildUploadFileName(
return `${segments.join('/')}/${file.name}`
}
-/** Breadcrumb entries for a folder path, from the top level down to the leaf. */
-export function folderBreadcrumbs(path: FolderSelection): Array<{ name: string; path: string }> {
+/**
+ * Breadcrumb entries for a folder path, from the top level down to the leaf.
+ * The root has no crumbs of its own — callers render it as the leading item.
+ */
+export function folderBreadcrumbs(path: string): Array<{ name: string; path: string }> {
if (!path) return []
const segments = path.split('/')
return segments.map((name, index) => ({
@@ -62,32 +77,73 @@ export function folderBreadcrumbs(path: FolderSelection): Array<{ name: string;
}
/**
- * The path itself plus every ancestor, used to keep the selected folder
- * reachable by expanding the rows above it.
+ * The root, the path itself and every folder in between, used to keep the
+ * selected folder reachable by expanding the rows above it.
*/
-export function folderAncestorPaths(path: FolderSelection): string[] {
- if (!path) return []
+export function folderAncestorPaths(path: string): string[] {
+ const paths = [ROOT_FOLDER_PATH]
+ if (!path) return paths
const segments = path.split('/')
- return segments.map((_, index) => segments.slice(0, index + 1).join('/'))
+ segments.forEach((_, index) => paths.push(segments.slice(0, index + 1).join('/')))
+ return paths
}
-/** Depth-first search for a folder path in the tree. */
+/** Depth-first search for a folder path in the tree. The root always exists. */
export function folderPathExists(folders: KnowledgeFolderNode[], path: string): boolean {
+ if (path === ROOT_FOLDER_PATH) return true
return folders.some((node) => node.path === path || folderPathExists(node.children || [], path))
}
-/** Flatten the tree into the visible rows, honouring the expanded folder set. */
-export function flattenFolderRows(
+function flattenFolders(
folders: KnowledgeFolderNode[],
expanded: Set<string>,
- depth = 0,
+ depth: number,
): FolderRow[] {
const rows: FolderRow[] = []
folders.forEach((node) => {
- rows.push({ node, depth })
- if (node.children?.length && expanded.has(node.path)) {
- rows.push(...flattenFolderRows(node.children, expanded, depth + 1))
+ const hasChildren = !!node.children?.length
+ rows.push({
+ kind: 'folder',
+ path: node.path,
+ name: node.name,
+ depth,
+ documentCount: node.document_count,
+ totalCount: node.total_count,
+ hasChildren,
+ })
+ if (hasChildren && expanded.has(node.path)) {
+ rows.push(...flattenFolders(node.children!, expanded, depth + 1))
}
})
return rows
}
+
+/**
+ * Flatten the tree into the visible rows: the root first, then the folders
+ * nested beneath it, honouring the expanded set at every level.
+ */
+export function buildFolderRows(
+ tree: KnowledgeFolderTree | null,
+ expanded: Set<string>,
+): FolderRow[] {
+ const folders = tree?.folders ?? []
+ const root: FolderRow = {
+ kind: 'root',
+ path: ROOT_FOLDER_PATH,
+ name: '',
+ depth: 0,
+ documentCount: tree?.root_document_count ?? 0,
+ totalCount: tree?.total_document_count ?? 0,
+ hasChildren: folders.length > 0,
+ }
+ if (!root.hasChildren || !expanded.has(ROOT_FOLDER_PATH)) return [root]
+ return [root, ...flattenFolders(folders, expanded, 1)]
+}
+
+/**
+ * The count a row should display, which must match what selecting it puts in
+ * the document list — otherwise the sidebar and the list disagree.
+ */
+export function folderRowCount(row: FolderRow, recursive: boolean): number {
+ return recursive ? row.totalCount : row.documentCount
+}