diff --git a/frontend/src/api/knowledge-base/index.ts b/frontend/src/api/knowledge-base/index.ts index a519666f..fd4c878e 100644 --- a/frontend/src/api/knowledge-base/index.ts +++ b/frontend/src/api/knowledge-base/index.ts @@ -264,6 +264,14 @@ export function listKnowledgeFiles( source?: string; start_time?: string; end_time?: string; + /** + * Folder to browse. An empty string means the knowledge base root, so the + * parameter is only sent when it is defined — leaving it out lists every + * folder (the flat view). + */ + folder_path?: string; + /** Include documents stored in sub-folders of folder_path. */ + folder_recursive?: boolean; }, ) { const query = new URLSearchParams(); @@ -276,10 +284,39 @@ export function listKnowledgeFiles( if (params.source) query.append('source', params.source); if (params.start_time) query.append('start_time', params.start_time); if (params.end_time) query.append('end_time', params.end_time); + if (params.folder_path !== undefined) { + query.append('folder_path', params.folder_path); + if (params.folder_recursive) query.append('folder_recursive', 'true'); + } const qs = query.toString(); return get(`/api/v1/knowledge-bases/${kbId}/knowledge?${qs}`); } +/** One node of the knowledge base folder tree. */ +export interface KnowledgeFolderNode { + /** Canonical folder path, e.g. "docs/spec". */ + path: string; + /** Last segment of the path, used as the row label. */ + name: string; + /** Documents stored directly in this folder. */ + document_count: number; + /** Documents in this folder plus every descendant folder. */ + total_count: number; + children?: KnowledgeFolderNode[]; +} + +export interface KnowledgeFolderTree { + /** Documents that are not part of any uploaded folder. */ + root_document_count: number; + /** Documents in the whole knowledge base. */ + total_document_count: number; + folders: KnowledgeFolderNode[]; +} + +export function listKnowledgeFolders(kbId: string) { + return get(`/api/v1/knowledge-bases/${kbId}/knowledge/folders`); +} + export function getKnowledgeDetails(id: string, options?: { agent_id?: string; agent_source_tenant_id?: string }) { const query = new URLSearchParams(); if (options?.agent_id) query.set('agent_id', options.agent_id); diff --git a/frontend/src/hooks/useKnowledgeBase.ts b/frontend/src/hooks/useKnowledgeBase.ts index d863ca0c..e7913094 100644 --- a/frontend/src/hooks/useKnowledgeBase.ts +++ b/frontend/src/hooks/useKnowledgeBase.ts @@ -51,6 +51,8 @@ export default function (knowledgeBaseId?: string) { source?: string; start_time?: string; end_time?: string; + folder_path?: string; + folder_recursive?: boolean; } = { page: 1, page_size: 35 }, kbId?: string, ): Promise => { @@ -76,6 +78,7 @@ export default function (knowledgeBaseId?: string) { original_file_name: item.file_name, display_name: displayName, file_name: displayName, + folder_path: item.folder_path || '', updated_at: formatStringDate(new Date(item.updated_at)), isMore: false, file_type: fileTypeSource ? String(fileTypeSource).toLocaleUpperCase() : '', diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 05f5796e..bbc716c5 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -369,6 +369,17 @@ export default { tagEditSelectedSection: 'Selected', tagEditAvailableSection: 'Available', 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', + collapse: 'Collapse folders', + expand: 'Expand folders', + collapseFolder: 'Collapse this folder', + expandFolder: 'Expand this folder', + }, tagFilterTitle: 'Filter by tag', tagFilterPlaceholder: 'Tags', tagFilterMulti: '{count} tags', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index e7e6414c..6810b8ae 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -5123,6 +5123,17 @@ export default { tagEditSelectedSection: '선택된 태그', tagEditAvailableSection: '선택 가능', tagEditNoSelected: '선택 없음', + folderTree: { + title: '폴더', + allDocuments: '전체 문서', + rootFolder: '루트', + empty: '폴더를 업로드하면 구조가 여기에 표시됩니다.', + includeSubfolders: '하위 폴더의 문서 포함', + collapse: '폴더 접기', + expand: '폴더 펼치기', + collapseFolder: '이 폴더 접기', + expandFolder: '이 폴더 펼치기', + }, tagFilterTitle: '태그로 필터', tagFilterPlaceholder: '태그', tagFilterMulti: '태그 {count}개', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 533caa26..304ca63c 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -5123,6 +5123,17 @@ export default { tagEditSelectedSection: 'Выбранные', tagEditAvailableSection: 'Доступные', tagEditNoSelected: 'Ничего не выбрано', + folderTree: { + title: 'Папки', + allDocuments: 'Все документы', + rootFolder: 'Корень', + empty: 'Загрузите папку — её структура появится здесь.', + includeSubfolders: 'Включать документы во вложенных папках', + collapse: 'Свернуть папки', + expand: 'Развернуть папки', + collapseFolder: 'Свернуть эту папку', + expandFolder: 'Развернуть эту папку', + }, tagFilterTitle: 'Фильтр по тегу', tagFilterPlaceholder: 'Теги', tagFilterMulti: '{count} тегов', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index aab24a9d..d5e993d8 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -5123,6 +5123,17 @@ export default { tagEditSelectedSection: '已选标签', tagEditAvailableSection: '可选标签', tagEditNoSelected: '暂未选择', + folderTree: { + title: '目录', + allDocuments: '全部文档', + rootFolder: '根目录', + empty: '上传文件夹后,目录结构会显示在这里。', + includeSubfolders: '包含子目录中的文档', + collapse: '收起目录', + expand: '展开目录', + collapseFolder: '收起该文件夹', + expandFolder: '展开该文件夹', + }, tagFilterTitle: '按标签筛选', tagFilterPlaceholder: '标签', tagFilterMulti: '{count} 个标签', diff --git a/frontend/src/views/knowledge/KnowledgeBase.vue b/frontend/src/views/knowledge/KnowledgeBase.vue index b6ff33e8..846d8fc8 100644 --- a/frontend/src/views/knowledge/KnowledgeBase.vue +++ b/frontend/src/views/knowledge/KnowledgeBase.vue @@ -35,6 +35,8 @@ import { batchReparseKnowledge, getKnowledgeSpans, getKnowledgeDetails, + listKnowledgeFolders, + type KnowledgeFolderTree, } from "@/api/knowledge-base/index"; import { knowledgeSpansPayloadHasTrace } from '@/utils/knowledgeTrace'; import FAQEntryManager from './components/FAQEntryManager.vue'; @@ -42,6 +44,7 @@ import DocumentListView from './components/DocumentListView.vue'; import DocumentCardView from './components/DocumentCardView.vue'; import DocumentBatchBar from './components/DocumentBatchBar.vue'; import KbUploadSourceDropdown from './components/KbUploadSourceDropdown.vue'; +import KbFolderTree from './components/KbFolderTree.vue'; import TagEditDialog from './components/TagEditDialog.vue'; import BatchTagDialog from './components/BatchTagDialog.vue'; import KbTagManageDrawer from './components/KbTagManageDrawer.vue'; @@ -591,6 +594,52 @@ const sourceOptions = computed(() => [ const updatedTimeRange = ref([]); // Disable any date after today so users cannot filter into the future. 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) => { + try { + return localStorage.getItem(key) === 'true'; + } catch { + return false; + } +}; +const writeStoredFlag = (key: string, value: boolean) => { + try { + localStorage.setItem(key, String(value)); + } catch { + // Private-mode storage failures must not break navigation. + } +}; +const folderTree = ref(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(null); +const folderTreeCollapsed = ref(readStoredFlag(FOLDER_TREE_COLLAPSED_KEY)); +const folderRecursive = ref(readStoredFlag(FOLDER_TREE_RECURSIVE_KEY)); +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)); +// Rows only need their folder shown when the current list can span folders. +const showDocumentFolderPath = computed( + () => hasFolders.value && (selectedFolderPath.value === null || folderRecursive.value), +); +const folderBreadcrumbs = computed(() => { + const path = selectedFolderPath.value; + if (!path) return []; + const segments = path.split('/'); + return segments.map((name, index) => ({ + name, + path: segments.slice(0, index + 1).join('/'), + })); +}); +// 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 || []; return { @@ -601,6 +650,8 @@ 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, + folder_recursive: folderRecursive.value, }; }); const tagMap = computed>(() => { @@ -701,6 +752,54 @@ const loadKnowledgeFiles = (kbIdValue: string): Promise => { const isCurrentKb = (targetKbId: string) => targetKbId === kbId.value; +const loadFolderTree = async (kbIdValue: string) => { + if (!kbIdValue || isFAQ.value) { + folderTree.value = null; + return; + } + folderTreeLoading.value = true; + try { + const res: any = await listKnowledgeFolders(kbIdValue); + 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 && !folderPathExists(path)) { + selectedFolderPath.value = null; + } + } catch (error) { + if (!isCurrentKb(kbIdValue)) return; + console.error('Failed to load knowledge folders', error); + folderTree.value = null; + } finally { + if (isCurrentKb(kbIdValue)) { + folderTreeLoading.value = false; + } + } +}; + +const folderPathExists = (path: string): boolean => { + const walk = (nodes: KnowledgeFolderTree['folders']): boolean => + nodes.some((node) => node.path === path || walk(node.children || [])); + return walk(folderTree.value?.folders || []); +}; + +const handleFolderSelect = (path: string | null) => { + if (selectedFolderPath.value === path) return; + selectedFolderPath.value = path; +}; + +const handleFolderRecursiveChange = (value: boolean) => { + folderRecursive.value = value; + writeStoredFlag(FOLDER_TREE_RECURSIVE_KEY, value); +}; + +const handleFolderTreeCollapsedChange = (value: boolean) => { + folderTreeCollapsed.value = value; + writeStoredFlag(FOLDER_TREE_COLLAPSED_KEY, value); +}; + const loadTags = async (kbIdValue: string, reset = false) => { if (!kbIdValue) { tagList.value = []; @@ -859,9 +958,11 @@ const loadKnowledgeBaseInfo = async (targetKbId: string, force = false) => { uiStore.clearSelectedTagIds(); if (!isFAQ.value) { loadKnowledgeFiles(targetKbId); + void loadFolderTree(targetKbId); } else { cardList.value = []; total.value = 0; + folderTree.value = null; } loadTags(targetKbId, true); } catch (error) { @@ -936,6 +1037,8 @@ watch(() => kbId.value, (newKbId, oldKbId) => { tagSearchQuery.value = ''; tagPage.value = 1; uiStore.clearSelectedTagIds(); + folderTree.value = null; + selectedFolderPath.value = null; } loadKnowledgeBaseInfo(newKbId); }, { immediate: true }); @@ -990,6 +1093,14 @@ watch([selectedParseStatus, selectedSource, updatedTimeRange], () => { } }, { deep: true }); +// 目录树选择与"包含子目录"开关都只改变文档列表的筛选范围,行为与其他筛选一致。 +watch([selectedFolderPath, folderRecursive], () => { + if (!kbId.value || isFAQ.value) return; + clearSelection(); + resetPage(); + loadKnowledgeFiles(kbId.value); +}); + // 监听文件上传事件 const handleFileUploaded = (event: CustomEvent) => { const uploadedKbId = event.detail.kbId; @@ -1000,6 +1111,7 @@ const handleFileUploaded = (event: CustomEvent) => { resetPage(); // Reset page counter when reloading files after upload loadKnowledgeFiles(uploadedKbId); loadTags(uploadedKbId); + void loadFolderTree(uploadedKbId); // 启动几次探测,尽快让面包屑的"索引中"亮起。 scheduleWikiStatusProbes(); } @@ -1248,6 +1360,7 @@ const confirmDeleteKnowledge = (index: number, item: KnowledgeCard) => { await new Promise((r) => setTimeout(r, delayMs)); } loadTags(kbId.value, true); + void loadFolderTree(kbId.value); }); }; @@ -1309,6 +1422,7 @@ const handleMoveConfirm = async () => { moveSubmitting.value = false; resetPage(); // Reset page counter when reloading files after move loadKnowledgeFiles(kbId.value); + void loadFolderTree(kbId.value); } } catch (e: any) { MessagePlugin.error(e?.message || t('knowledgeBase.moveFailed')); @@ -1334,6 +1448,7 @@ const startMovePoll = (taskId: string) => { } resetPage(); // Reset page counter when reloading files after move completion loadKnowledgeFiles(kbId.value); + void loadFolderTree(kbId.value); } else if (data.status === 'failed') { stopMovePoll(); moveSubmitting.value = false; @@ -1356,6 +1471,7 @@ const manualEditorSuccess = ({ kbId: savedKbId }: { kbId: string; knowledgeId: s if (savedKbId === kbId.value && !isFAQ.value) { resetPage(); // Reset page counter when reloading files after manual edit loadKnowledgeFiles(savedKbId); + void loadFolderTree(savedKbId); } }; @@ -1399,13 +1515,31 @@ const AUDIO_EXTENSIONS = ['mp3', 'wav', 'm4a', 'flac', 'ogg']; const uploadConfirmStore = useUploadConfirmStore(); +// A browser only sets webkitRelativePath when the file came from a directory +// picker or a dropped directory, which is exactly what distinguishes a folder +// upload from picking individual files. +const isFolderUpload = (file: File) => + !!(file as File & { webkitRelativePath?: string }).webkitRelativePath; + +/** + * Build the path-qualified `fileName` 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 for folder uploads, whose picked directory becomes the + * top-level tree node. Returns undefined for a plain single-file upload at the + * knowledge base root, which keeps that request byte-identical to before. + */ const getFolderUploadFileName = (file: File) => { - const relativePath = (file as any).webkitRelativePath; - if (!relativePath) return undefined; - const pathParts = relativePath.split('/'); - if (pathParts.length <= 2) return undefined; - const subPath = pathParts.slice(1, -1).join('/'); - return `${subPath}/${file.name}`; + const segments: string[] = []; + if (uploadTargetFolder.value) { + segments.push(uploadTargetFolder.value); + } + const relativePath = (file as File & { webkitRelativePath?: string }).webkitRelativePath; + if (relativePath) { + segments.push(...relativePath.split('/').filter(Boolean).slice(0, -1)); + } + if (segments.length === 0) return undefined; + return `${segments.join('/')}/${file.name}`; }; const showUploadResultMessages = ( @@ -1456,10 +1590,7 @@ const executeUploadBatch = async ( let successCount = 0; let failCount = 0; const totalCount = files.length; - const hasFolderPaths = files.some((file) => { - const relativePath = (file as File & { webkitRelativePath?: string }).webkitRelativePath; - return !!relativePath && relativePath.split('/').length > 2; - }); + const hasFolderPaths = files.some(isFolderUpload); for (const file of files) { try { @@ -1573,10 +1704,7 @@ const handleUploadConfirmResult = async (result: UploadConfirmResult) => { const tagIds = result.tagIds || []; if (files.length > 0) { - const hasFolderPaths = files.some((file) => { - const relativePath = (file as File & { webkitRelativePath?: string }).webkitRelativePath; - return !!relativePath && relativePath.split('/').length > 2; - }); + const hasFolderPaths = files.some(isFolderUpload); if (hasFolderPaths) { MessagePlugin.info(t('knowledgeBase.uploadingFolder', { total: files.length })); } @@ -1906,6 +2034,7 @@ const confirmBatchDelete = async () => { await new Promise((r) => setTimeout(r, delayMs)); } loadTags(kbId.value, true); + void loadFolderTree(kbId.value); } else { MessagePlugin.error(res?.message || t('knowledgeBase.batchDeleteFailed')); } @@ -2149,8 +2278,30 @@ async function createNewSession(value: string): Promise {