diff --git a/frontend/src/api/knowledge-base/index.ts b/frontend/src/api/knowledge-base/index.ts index fd4c878e..7eecec51 100644 --- a/frontend/src/api/knowledge-base/index.ts +++ b/frontend/src/api/knowledge-base/index.ts @@ -317,6 +317,24 @@ export function listKnowledgeFolders(kbId: string) { return get(`/api/v1/knowledge-bases/${kbId}/knowledge/folders`); } +/** + * Re-file documents under `folderPath` ('' = knowledge base top level). Folders + * are derived from the stored paths, so a path that does not exist yet is + * created by this call. Only the grouping changes; documents are not re-parsed. + */ +export function moveKnowledgeToFolder(kbId: string, ids: string[], folderPath: string) { + return post('/api/v1/knowledge/folder', { + kb_id: kbId, + knowledge_ids: ids, + folder_path: folderPath, + }); +} + +/** Rename or move a folder together with everything below it. */ +export function renameKnowledgeFolder(kbId: string, from: string, to: string) { + return put(`/api/v1/knowledge-bases/${kbId}/knowledge/folders`, { from, to }); +} + 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/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index a61da332..0aaa47b9 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -373,17 +373,31 @@ export default { title: 'Folders', rootRow: 'All documents', rootRowTip: 'The top level of the knowledge base; every folder sits below it', - rootRowDirect: 'Unfiled documents', - rootRowDirectTip: 'Documents uploaded on their own, not inside any folder', - scopeToggle: 'Change list scope', - scopeSubtree: 'With sub-folders', - scopeDirect: 'This level', - scopeSubtreeTip: 'List every document in the selected folder and its sub-folders', - scopeDirectTip: 'List only the selected folder\'s own documents; on the top level these are the unfiled ones', + folderCardCount: '{count} documents', + searchingSubtree: '(including sub-folders)', + emptyFolder: 'This folder has no documents yet', + emptySearch: 'No matching documents', collapse: 'Collapse folders', expand: 'Expand folders', collapseFolder: 'Collapse this folder', expandFolder: 'Expand this folder', + rename: 'Rename', + renamePlaceholder: 'Folder name', + renameSuccess: 'Folder renamed', + renameFailed: 'Could not rename the folder', + renameInvalid: 'A folder cannot be moved inside itself', + }, + moveToFolder: { + action: 'Move to folder', + title: 'Move {count} documents', + hint: 'Pick a destination. Folders are derived from document paths, so this only changes grouping — nothing is re-parsed.', + confirm: 'Move', + newFolder: 'New sub-folder', + newFolderPlaceholder: 'New folder name', + newFolderPreview: 'Will create and move to "{path}"', + newFolderUnderRoot: 'Enter a folder name', + success: 'Moved {count} documents', + failed: 'Could not move the documents', }, tagFilterTitle: 'Filter by tag', tagFilterPlaceholder: 'Tags', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 041d08be..acc86cbc 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -5132,17 +5132,31 @@ export default { title: '폴더', rootRow: '전체 문서', rootRowTip: '지식 베이스의 최상위이며 모든 폴더가 그 아래에 있습니다', - rootRowDirect: '미분류 문서', - rootRowDirectTip: '단독으로 업로드되어 어떤 폴더에도 속하지 않은 문서', - scopeToggle: '목록 범위 변경', - scopeSubtree: '하위 포함', - scopeDirect: '현재 단계', - scopeSubtreeTip: '선택한 폴더와 하위 폴더의 모든 문서를 표시합니다', - scopeDirectTip: '선택한 폴더 자체의 문서만 표시합니다. 최상위에서는 미분류 문서입니다', + folderCardCount: '문서 {count}개', + searchingSubtree: '(하위 폴더 포함)', + emptyFolder: '이 폴더에는 아직 문서가 없습니다', + emptySearch: '일치하는 문서가 없습니다', collapse: '폴더 접기', expand: '폴더 펼치기', collapseFolder: '이 폴더 접기', expandFolder: '이 폴더 펼치기', + rename: '이름 변경', + renamePlaceholder: '폴더 이름', + renameSuccess: '폴더 이름을 변경했습니다', + renameFailed: '폴더 이름을 변경할 수 없습니다', + renameInvalid: '폴더를 자기 하위로 이동할 수 없습니다', + }, + moveToFolder: { + action: '폴더로 이동', + title: '문서 {count}개 이동', + hint: '대상 폴더를 선택하세요. 폴더는 문서 경로에서 파생되므로 분류만 바뀌고 다시 처리되지 않습니다.', + confirm: '이동', + newFolder: '새 하위 폴더', + newFolderPlaceholder: '새 폴더 이름', + newFolderPreview: '「{path}」을(를) 만들어 이동합니다', + newFolderUnderRoot: '폴더 이름을 입력하세요', + success: '문서 {count}개를 이동했습니다', + failed: '문서를 이동할 수 없습니다', }, tagFilterTitle: '태그로 필터', tagFilterPlaceholder: '태그', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index b84a1842..7cdc12e7 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -5132,17 +5132,31 @@ export default { title: 'Папки', rootRow: 'Все документы', rootRowTip: 'Верхний уровень базы знаний — все папки находятся внутри него', - rootRowDirect: 'Документы вне папок', - rootRowDirectTip: 'Документы, загруженные по отдельности и не находящиеся ни в одной папке', - scopeToggle: 'Изменить область списка', - scopeSubtree: 'С вложенными', - scopeDirect: 'Этот уровень', - scopeSubtreeTip: 'Показать все документы выбранной папки и её вложенных папок', - scopeDirectTip: 'Показать только документы самой выбранной папки; на верхнем уровне это документы вне папок', + folderCardCount: 'Документов: {count}', + searchingSubtree: '(с вложенными папками)', + emptyFolder: 'В этой папке пока нет документов', + emptySearch: 'Подходящих документов нет', collapse: 'Свернуть папки', expand: 'Развернуть папки', collapseFolder: 'Свернуть эту папку', expandFolder: 'Развернуть эту папку', + rename: 'Переименовать', + renamePlaceholder: 'Название папки', + renameSuccess: 'Папка переименована', + renameFailed: 'Не удалось переименовать папку', + renameInvalid: 'Папку нельзя переместить внутрь себя', + }, + moveToFolder: { + action: 'Переместить в папку', + title: 'Переместить документов: {count}', + hint: 'Выберите папку. Папки выводятся из путей документов, поэтому меняется только группировка — повторная обработка не выполняется.', + confirm: 'Переместить', + newFolder: 'Новая вложенная папка', + newFolderPlaceholder: 'Название новой папки', + newFolderPreview: 'Будет создана папка «{path}»', + newFolderUnderRoot: 'Введите название папки', + success: 'Перемещено документов: {count}', + failed: 'Не удалось переместить документы', }, tagFilterTitle: 'Фильтр по тегу', tagFilterPlaceholder: 'Теги', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 4704c98c..721c6729 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -5132,17 +5132,31 @@ export default { title: '目录', rootRow: '全部文档', rootRowTip: '知识库顶层,所有文件夹都在它下面', - rootRowDirect: '未归类文档', - rootRowDirectTip: '直接上传、不在任何文件夹里的文档', - scopeToggle: '切换列表范围', - scopeSubtree: '含子目录', - scopeDirect: '仅本层', - scopeSubtreeTip: '列出所选目录及其子目录里的全部文档', - scopeDirectTip: '只列出所选目录本层的文档;选中顶层即为未归类文档', + folderCardCount: '{count} 个文档', + searchingSubtree: '(含子目录)', + emptyFolder: '这个文件夹里还没有文档', + emptySearch: '没有匹配的文档', collapse: '收起目录', expand: '展开目录', collapseFolder: '收起该文件夹', expandFolder: '展开该文件夹', + rename: '重命名', + renamePlaceholder: '输入文件夹名称', + renameSuccess: '文件夹已重命名', + renameFailed: '文件夹重命名失败', + renameInvalid: '不能把文件夹移动到它自己的子目录下', + }, + moveToFolder: { + action: '移动到目录', + title: '移动 {count} 个文档', + hint: '选择目标目录。目录由文档路径推导而来,只调整归类,不会重新解析文档。', + confirm: '移动', + newFolder: '新建子目录', + newFolderPlaceholder: '输入新目录名称', + newFolderPreview: '将创建并移动到「{path}」', + newFolderUnderRoot: '请输入目录名称', + success: '已移动 {count} 个文档', + failed: '移动失败', }, tagFilterTitle: '按标签筛选', tagFilterPlaceholder: '标签', diff --git a/frontend/src/views/knowledge/KnowledgeBase.vue b/frontend/src/views/knowledge/KnowledgeBase.vue index 7d5cf719..71e23b2c 100644 --- a/frontend/src/views/knowledge/KnowledgeBase.vue +++ b/frontend/src/views/knowledge/KnowledgeBase.vue @@ -36,6 +36,8 @@ import { getKnowledgeSpans, getKnowledgeDetails, listKnowledgeFolders, + moveKnowledgeToFolder, + renameKnowledgeFolder, type KnowledgeFolderTree, } from "@/api/knowledge-base/index"; import { knowledgeSpansPayloadHasTrace } from '@/utils/knowledgeTrace'; @@ -45,6 +47,7 @@ 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 MoveToFolderDialog from './components/MoveToFolderDialog.vue'; import TagEditDialog from './components/TagEditDialog.vue'; import BatchTagDialog from './components/BatchTagDialog.vue'; import KbTagManageDrawer from './components/KbTagManageDrawer.vue'; @@ -60,10 +63,12 @@ import { import { listMoveTargets, moveKnowledge, getKnowledgeMoveProgress } from '@/api/knowledge-base'; import { buildUploadFileName, + canMoveFolderTo, + childFolders, folderBreadcrumbs as buildFolderBreadcrumbs, folderPathExists as folderExistsInTree, + isFilteringDocuments, isFolderUpload, - rootRowLabelKey, ROOT_FOLDER_PATH, } from './folderTree'; import { useI18n } from 'vue-i18n'; @@ -605,7 +610,6 @@ 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, fallback = false) => { try { const raw = localStorage.getItem(key); @@ -623,24 +627,34 @@ const writeStoredFlag = (key: string, value: boolean) => { }; const folderTree = ref(null); const folderTreeLoading = ref(false); -// 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). +// The folder being browsed; ROOT_FOLDER_PATH ('') is the knowledge base top +// level, a real node of the tree rather than a separate mode. const selectedFolderPath = ref(ROOT_FOLDER_PATH); const folderTreeCollapsed = ref(readStoredFlag(FOLDER_TREE_COLLAPSED_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); -// Rows only need their folder shown when the current list can span folders. -const showDocumentFolderPath = computed(() => hasFolders.value && folderRecursive.value); +// Browsing lists one folder's own contents; filtering searches its whole +// subtree. There is no mode switch: the list follows what the user is doing. +const isFiltering = computed(() => + isFilteringDocuments({ + keyword: docSearchKeyword.value, + tagIds: selectedTagIds.value, + fileType: selectedFileType.value, + parseStatus: selectedParseStatus.value, + source: selectedSource.value, + timeRange: updatedTimeRange.value, + }), +); +// Sub-folder entries shown at the top of the list while browsing. Search results +// are flat, so they are dropped as soon as a filter is active. +const currentChildFolders = computed(() => + isFiltering.value ? [] : childFolders(folderTree.value, selectedFolderPath.value), +); +// A row's folder is worth showing only when the list can span folders. +const showDocumentFolderPath = computed(() => hasFolders.value && isFiltering.value); const folderBreadcrumbs = computed(() => buildFolderBreadcrumbs(selectedFolderPath.value)); -// Leading crumb mirrors the sidebar's root row, whose label depends on the scope. -const folderRootLabel = computed(() => t(rootRowLabelKey(folderRecursive.value))); const filterParams = computed(() => { const [start, end] = updatedTimeRange.value || []; @@ -652,10 +666,10 @@ const filterParams = computed(() => { source: selectedSource.value || undefined, start_time: start ? `${start} 00:00:00` : undefined, end_time: end ? `${end} 23:59:59` : undefined, - // 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, + // Searching descends into sub-folders; browsing shows one level, with the + // sub-folders themselves rendered as entries in the list. + folder_recursive: isFiltering.value, }; }); const tagMap = computed>(() => { @@ -787,9 +801,60 @@ const handleFolderSelect = (path: string) => { selectedFolderPath.value = path; }; -const handleFolderRecursiveChange = (value: boolean) => { - folderRecursive.value = value; - writeStoredFlag(FOLDER_TREE_RECURSIVE_KEY, value); +// ── Re-filing documents and renaming folders ── +// folder_path is display-only, so both operations are a plain column update: +// nothing is re-parsed, re-chunked or re-embedded. +const moveFolderDialogVisible = ref(false); +const moveFolderSubmitting = ref(false); +const moveFolderTargets = ref([]); + +const openMoveToFolderDialog = (ids: string[]) => { + if (!ids.length) return; + moveFolderTargets.value = [...ids]; + moveFolderDialogVisible.value = true; +}; + +const handleMoveToFolderConfirm = async (folderPath: string) => { + const ids = moveFolderTargets.value; + if (!kbId.value || ids.length === 0) return; + moveFolderSubmitting.value = true; + try { + await moveKnowledgeToFolder(kbId.value, ids, folderPath); + moveFolderDialogVisible.value = false; + MessagePlugin.success(t('knowledgeBase.moveToFolder.success', { count: ids.length })); + clearSelection(); + batchMode.value = false; + resetPage(); + await loadKnowledgeFiles(kbId.value); + await loadFolderTree(kbId.value); + } catch (error: any) { + MessagePlugin.error(error?.message || t('knowledgeBase.moveToFolder.failed')); + } finally { + moveFolderSubmitting.value = false; + } +}; + +const handleFolderRename = async ({ from, to }: { from: string; to: string }) => { + if (!kbId.value || !to || from === to) return; + if (!canMoveFolderTo(from, to)) { + MessagePlugin.warning(t('knowledgeBase.folderTree.renameInvalid')); + return; + } + try { + await renameKnowledgeFolder(kbId.value, from, to); + MessagePlugin.success(t('knowledgeBase.folderTree.renameSuccess')); + // Follow the folder to its new path so the user stays where they were. + if (selectedFolderPath.value === from) { + selectedFolderPath.value = to; + } else if (selectedFolderPath.value.startsWith(`${from}/`)) { + selectedFolderPath.value = to + selectedFolderPath.value.slice(from.length); + } + resetPage(); + await loadKnowledgeFiles(kbId.value); + await loadFolderTree(kbId.value); + } catch (error: any) { + MessagePlugin.error(error?.message || t('knowledgeBase.folderTree.renameFailed')); + } }; const handleFolderTreeCollapsedChange = (value: boolean) => { @@ -1090,8 +1155,9 @@ watch([selectedParseStatus, selectedSource, updatedTimeRange], () => { } }, { deep: true }); -// 目录树选择与"包含子目录"开关都只改变文档列表的筛选范围,行为与其他筛选一致。 -watch([selectedFolderPath, folderRecursive], () => { +// 切换目录只改变列表范围,行为与其他筛选一致。浏览态与筛选态之间的切换由各筛选项 +// 自身的 watcher 触发刷新,这里不重复请求。 +watch(selectedFolderPath, () => { if (!kbId.value || isFAQ.value) return; clearSelection(); resetPage(); @@ -2072,7 +2138,7 @@ const confirmCancelParseKnowledge = async (item: KnowledgeCard) => { // Bridge card-view actions back to existing per-card handlers. const handleCardAction = ( - action: 'edit' | 'reparse' | 'cancel-parse' | 'move' | 'delete' | 'view-trace' | 'batch-manage', + action: 'edit' | 'reparse' | 'cancel-parse' | 'move' | 'move-folder' | 'delete' | 'view-trace' | 'batch-manage', item: KnowledgeCard, ) => { const idx = (cardList.value || []).findIndex((i: KnowledgeCard) => i.id === item.id); @@ -2083,6 +2149,7 @@ const handleCardAction = ( } if (action === 'cancel-parse') return confirmCancelParseKnowledge(item); if (action === 'move') return handleMoveKnowledge(item); + if (action === 'move-folder') return openMoveToFolderDialog([item.id]); if (action === 'delete') return confirmDeleteKnowledge(idx, item); if (action === 'view-trace') return handleViewTrace(idx, item); if (action === 'batch-manage') return handleEnterBatchFromCard(item); @@ -2090,7 +2157,7 @@ const handleCardAction = ( // Bridge list-view actions back to existing per-card handlers. const handleListAction = ( - action: 'edit' | 'reparse' | 'cancel-parse' | 'move' | 'delete' | 'view-trace' | 'batch-manage', + action: 'edit' | 'reparse' | 'cancel-parse' | 'move' | 'move-folder' | 'delete' | 'view-trace' | 'batch-manage', item: KnowledgeCard, ) => { const idx = (cardList.value || []).findIndex((i: KnowledgeCard) => i.id === item.id); @@ -2098,6 +2165,7 @@ const handleListAction = ( if (action === 'reparse') return confirmRebuildKnowledge(idx, item); if (action === 'cancel-parse') return confirmCancelParseKnowledge(item); if (action === 'move') return handleMoveKnowledge(item); + if (action === 'move-folder') return openMoveToFolderDialog([item.id]); if (action === 'delete') return confirmDeleteKnowledge(idx, item); if (action === 'view-trace') return handleViewTrace(idx, item); if (action === 'batch-manage') return handleEnterBatchFromCard(item); @@ -2264,15 +2332,16 @@ async function createNewSession(value: string): Promise {