feat(knowledge): browse folders like a file manager and allow re-filing

The scope switch is gone. It existed because "select a folder" was ambiguous
in a list that could not show folders, and turning that ambiguity into a
control just moved the problem onto the user.

The list now shows what a folder contains: its sub-folders as entries first,
then the documents directly inside it. So the mode follows what the user is
already doing instead of a switch - browsing shows one level, and any active
filter searches the whole subtree flat, with a breadcrumb note saying so. A
document uploaded on its own needs no special row either: it sits at the top
level next to the folders, exactly where it is.

Folders can also be adjusted now, which they could not before - a mis-filed
upload previously had to be deleted and re-uploaded. Documents move via the
row menu or the batch bar into an existing or newly typed folder, and a
folder can be renamed in place, carrying its subtree. Both are plain
folder_path updates: nothing is re-parsed, re-chunked or re-embedded.
main
lyingbug 2026-08-04 10:15:23 +00:00 committed by lyingbug
parent b3e31a24d9
commit 5fea7a1695
21 changed files with 1494 additions and 213 deletions

View File

@ -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);

View File

@ -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',

View File

@ -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: '태그',

View File

@ -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: 'Теги',

View File

@ -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: '标签',

View File

@ -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<KnowledgeFolderTree | null>(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<string>(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<Record<string, any>>(() => {
@ -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<string[]>([]);
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<void> {
<template v-if="activeKbTab === 'documents' || !isWiki">
<div class="knowledge-main">
<KbFolderTree v-if="showFolderTree" :tree="folderTree" :selected-path="selectedFolderPath"
:loading="folderTreeLoading" :collapsed="folderTreeCollapsed" :recursive="folderRecursive"
:loading="folderTreeLoading" :collapsed="folderTreeCollapsed" :can-edit="canEdit"
@select="handleFolderSelect" @update:collapsed="handleFolderTreeCollapsedChange"
@update:recursive="handleFolderRecursiveChange" />
@rename="handleFolderRename" />
<div class="tag-content">
<div class="doc-card-area">
<nav v-if="showFolderTree && folderBreadcrumbs.length" class="doc-folder-path"
<nav v-if="showFolderTree && (folderBreadcrumbs.length || isFiltering)" class="doc-folder-path"
:aria-label="$t('knowledgeBase.folderTree.title')">
<button type="button" class="doc-folder-path__crumb" @click="handleFolderSelect('')">
{{ folderRootLabel }}
<button type="button" class="doc-folder-path__crumb" :class="{ 'is-current': !folderBreadcrumbs.length }"
@click="handleFolderSelect('')">
{{ $t('knowledgeBase.folderTree.rootRow') }}
</button>
<template v-for="(crumb, index) in folderBreadcrumbs" :key="crumb.path">
<t-icon name="chevron-right" class="doc-folder-path__sep" />
@ -2283,6 +2352,10 @@ async function createNewSession(value: string): Promise<void> {
{{ crumb.name }}
</button>
</template>
<!-- Filtering silently widens the scope to sub-folders, so say so. -->
<span v-if="isFiltering" class="doc-folder-path__scope">
{{ $t('knowledgeBase.folderTree.searchingSubtree') }}
</span>
</nav>
<div class="doc-filter-bar">
<t-input v-model.trim="docSearchKeyword" :placeholder="$t('knowledgeBase.docSearchPlaceholder')"
@ -2469,9 +2542,10 @@ async function createNewSession(value: string): Promise<void> {
</div>
</div>
</div>
<template v-else-if="cardList.length && viewMode === 'grid'">
<template v-else-if="(cardList.length || currentChildFolders.length) && viewMode === 'grid'">
<DocumentCardView
:items="cardList"
:folders="currentChildFolders"
:selected-ids="selectedIds"
:batch-mode="batchMode"
:can-edit="canEdit"
@ -2497,8 +2571,8 @@ async function createNewSession(value: string): Promise<void> {
@update:move-mode="(mode: any) => moveMode = mode"
/>
</template>
<template v-else-if="cardList.length && viewMode === 'list'">
<DocumentListView :items="cardList" :selected-ids="selectedIds" :tag-list="tagList"
<template v-else-if="(cardList.length || currentChildFolders.length) && viewMode === 'list'">
<DocumentListView :items="cardList" :folders="currentChildFolders" :selected-ids="selectedIds" :tag-list="tagList"
:can-edit="canEdit" :can-mutate-knowledge="canMutateKnowledge"
:trace-visible-ids="traceAvailableById"
:move-menu-mode="moveMenuMode"
@ -2521,15 +2595,22 @@ async function createNewSession(value: string): Promise<void> {
</template>
<template v-else-if="!docListLoading">
<div class="doc-empty-state">
<EmptyKnowledge />
<p v-if="selectedFolderPath || isFiltering" class="doc-empty-folder">
{{ isFiltering
? $t('knowledgeBase.folderTree.emptySearch')
: $t('knowledgeBase.folderTree.emptyFolder') }}
</p>
<EmptyKnowledge v-else />
</div>
</template>
</div>
<div class="doc-batch-bar-anchor" v-show="batchMode || selectedIds.size > 0">
<DocumentBatchBar :count="selectedIds.size" :delete-loading="batchDeleting"
:reparse-loading="batchReparsing" :tag-loading="batchTagging" :visible="batchMode || selectedIds.size > 0"
:show-move-to-folder="canEdit"
@cancel="handleBatchCancel" @delete="confirmBatchDelete" @reparse="confirmBatchReparse"
@batch-tag="handleBatchTag" />
@batch-tag="handleBatchTag"
@move-to-folder="openMoveToFolderDialog(Array.from(selectedIds))" />
</div>
</div>
</div>
@ -2571,6 +2652,15 @@ async function createNewSession(value: string): Promise<void> {
@update:visible="batchTagDialogVisible = $event" @confirm="onBatchTagConfirm"
@tag-created="loadTags(kbId, true)" @open-manage="openTagManageFromBatchDialog" />
<MoveToFolderDialog
v-model:visible="moveFolderDialogVisible"
:tree="folderTree"
:count="moveFolderTargets.length"
:submitting="moveFolderSubmitting"
:current-path="selectedFolderPath"
@confirm="handleMoveToFolderConfirm"
/>
<KbTagManageDrawer
v-if="!isFAQ"
v-model:visible="tagManageDrawerVisible"

View File

@ -14,6 +14,8 @@ const props = defineProps<{
item: KnowledgeItem;
canMutateKnowledge: boolean;
traceVisible: boolean;
/** Whether the knowledge base has a folder structure to file documents into. */
foldersAvailable?: boolean;
}>();
const emit = defineEmits<{
@ -22,6 +24,7 @@ const emit = defineEmits<{
(e: 'reparse'): void;
(e: 'cancel-parse'): void;
(e: 'move'): void;
(e: 'move-folder'): void;
(e: 'batch-manage'): void;
(e: 'delete'): void;
}>();
@ -80,7 +83,13 @@ const fileName = computed(() => props.item.file_name || props.item.title || prop
</div>
</t-popconfirm>
<!-- 移动到... -->
<!-- 移动到目录 -->
<div v-if="canMutateKnowledge" class="doc-action-menu-item" @click.stop="emit('move-folder')">
<t-icon class="icon" name="folder" />
<span>{{ $t('knowledgeBase.moveToFolder.action') }}</span>
</div>
<!-- 移动到其他知识库 -->
<div v-if="canMutateKnowledge" class="doc-action-menu-item" @click.stop="emit('move')">
<t-icon class="icon" name="swap" />
<span>{{ $t('knowledgeBase.moveDocument') }}</span>

View File

@ -9,6 +9,8 @@ defineProps<{
// When true the bar stays visible even with 0 selections, so users can exit
// batch mode from here without selecting anything first.
visible?: boolean;
/** Hidden when the knowledge base has no folder structure to file into. */
showMoveToFolder?: boolean;
}>();
const emit = defineEmits<{
@ -16,6 +18,7 @@ const emit = defineEmits<{
(e: 'delete'): void;
(e: 'reparse'): void;
(e: 'batchTag'): void;
(e: 'moveToFolder'): void;
}>();
const { t } = useI18n();
@ -50,6 +53,13 @@ const { t } = useI18n();
{{ t('knowledgeBase.batchTag') }}
</t-button>
<t-button v-if="showMoveToFolder" theme="default" variant="outline" size="small"
:disabled="count === 0 || deleteLoading || reparseLoading || tagLoading"
@click="emit('moveToFolder')">
<template #icon><t-icon name="folder" size="14px" /></template>
{{ t('knowledgeBase.moveToFolder.action') }}
</t-button>
<t-popconfirm theme="warning" :content="t('knowledgeBase.confirmBatchDeleteDocument', { count })"
:confirm-btn="{ content: t('knowledgeBase.confirmDelete'), theme: 'danger' }"
:cancel-btn="{ content: t('common.cancel') }" placement="top" @confirm="emit('delete')">

View File

@ -44,9 +44,11 @@ const props = defineProps<{
canMutateKnowledge: boolean;
traceAvailableById: Record<string, boolean>;
tagList: Tag[];
/** Sub-folders of the folder currently being browsed. */
folders?: Array<{ path: string; name: string; total_count: number }>;
/**
* Replace the updated-at line with the card's folder. Only meaningful when
* the grid spans several folders (all documents / recursive browse).
* the grid spans several folders, i.e. while filtering.
*/
showFolderPath?: boolean;
// Move sub-flow state
@ -62,7 +64,7 @@ const emit = defineEmits<{
(e: 'open', item: KnowledgeCard): void;
(e: 'toggle-checkbox', id: string, checked: boolean, ctx?: { e?: Event }): void;
(e: 'menu-visible-change', visible: boolean, item: KnowledgeCard): void;
(e: 'action', action: 'edit' | 'view-trace' | 'reparse' | 'cancel-parse' | 'move' | 'batch-manage' | 'delete', item: KnowledgeCard): void;
(e: 'action', action: 'edit' | 'view-trace' | 'reparse' | 'cancel-parse' | 'move' | 'move-folder' | 'batch-manage' | 'delete', item: KnowledgeCard): void;
(e: 'tag-edit', item: KnowledgeCard): void;
(e: 'open-folder', path: string): void;
// Move sub-flow emits
@ -257,7 +259,7 @@ const onCardMouseLeave = () => {
};
// --- Action handlers ---
const handleAction = (action: 'edit' | 'view-trace' | 'reparse' | 'cancel-parse' | 'move' | 'batch-manage' | 'delete', item: KnowledgeCard) => {
const handleAction = (action: 'edit' | 'view-trace' | 'reparse' | 'cancel-parse' | 'move' | 'move-folder' | 'batch-manage' | 'delete', item: KnowledgeCard) => {
// Don't close menu for move — it triggers the sub-flow
if (action !== 'move') {
if (item.isMore !== undefined) item.isMore = false;
@ -269,6 +271,26 @@ const handleAction = (action: 'edit' | 'view-trace' | 'reparse' | 'cancel-parse'
<template>
<div class="doc-card-list doc-card-list-animated">
<!-- Sub-folders of the folder being browsed, listed first the way a file
manager does, so navigating down does not require the sidebar. -->
<div
v-for="folder in folders"
:key="'folder-' + folder.path"
class="folder-card"
:title="folder.path"
role="button"
tabindex="0"
@click="emit('open-folder', folder.path)"
@keydown.enter="emit('open-folder', folder.path)"
>
<t-icon name="folder" class="folder-card__icon" />
<div class="folder-card__text">
<span class="folder-card__name">{{ folder.name }}</span>
<span class="folder-card__meta">{{ t('knowledgeBase.folderTree.folderCardCount', { count: folder.total_count }) }}</span>
</div>
<t-icon name="chevron-right" class="folder-card__chevron" />
</div>
<div
class="knowledge-card"
:class="{ 'is-selected': selectedIds.has(item.id), 'batch-mode': batchMode }"
@ -320,6 +342,7 @@ const handleAction = (action: 'edit' | 'view-trace' | 'reparse' | 'cancel-parse'
@reparse="handleAction('reparse', item)"
@cancel-parse="handleAction('cancel-parse', item)"
@move="handleAction('move', item)"
@move-folder="handleAction('move-folder', item)"
@batch-manage="handleAction('batch-manage', item)"
@delete="handleAction('delete', item)"
/>
@ -623,6 +646,72 @@ const handleAction = (action: 'edit' | 'view-trace' | 'reparse' | 'cancel-parse'
}
}
// Folder entries share the grid with the document cards but are deliberately
// shorter: they are navigation, not content.
.folder-card {
min-width: 240px;
height: 56px;
box-sizing: border-box;
display: flex;
align-items: center;
gap: 10px;
padding: 0 12px;
border: 1px solid var(--td-component-border);
border-radius: 6px;
background: var(--td-bg-color-container);
cursor: pointer;
transition: border-color 0.15s ease, background 0.15s ease;
&:hover {
border-color: var(--td-brand-color);
background: var(--td-bg-color-container-hover);
.folder-card__chevron {
color: var(--td-brand-color);
}
}
&:focus-visible {
outline: none;
box-shadow: 0 0 0 2px color-mix(in srgb, var(--td-brand-color) 30%, transparent);
}
}
.folder-card__icon {
flex: 0 0 auto;
font-size: 20px;
color: var(--td-brand-color);
}
.folder-card__text {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 2px;
}
.folder-card__name {
font-size: 14px;
font-weight: 500;
color: var(--td-text-color-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.folder-card__meta {
font-size: 12px;
color: var(--td-text-color-placeholder);
}
.folder-card__chevron {
flex: 0 0 auto;
font-size: 16px;
color: var(--td-text-color-placeholder);
transition: color 0.15s ease;
}
.knowledge-card {
min-width: 240px;
display: flex;

View File

@ -36,10 +36,12 @@ const props = defineProps<{
traceVisibleIds: Record<string, boolean>;
tagList: Tag[];
loading?: boolean;
/** Sub-folders of the folder currently being browsed. */
folders?: Array<{ path: string; name: string; total_count: number }>;
/**
* Show each row's folder under its name. Only useful when the list spans
* several folders (the "all documents" view or a recursive folder browse);
* inside a single folder the path would be the same on every row.
* several folders, i.e. while filtering; inside one folder the path would be
* identical on every row.
*/
showFolderPath?: boolean;
// Move sub-flow state
@ -55,7 +57,7 @@ const emit = defineEmits<{
(e: 'open', item: KnowledgeItem): void;
(e: 'toggle-row', id: string, checked: boolean, shiftKey: boolean): void;
(e: 'toggle-all', checked: boolean): void;
(e: 'action', action: 'edit' | 'reparse' | 'cancel-parse' | 'move' | 'delete' | 'view-trace' | 'batch-manage', item: KnowledgeItem): void;
(e: 'action', action: 'edit' | 'reparse' | 'cancel-parse' | 'move' | 'move-folder' | 'delete' | 'view-trace' | 'batch-manage', item: KnowledgeItem): void;
(e: 'probe-trace', item: KnowledgeItem): void;
(e: 'tag-edit', item: KnowledgeItem): void;
(e: 'open-folder', path: string): void;
@ -212,7 +214,7 @@ onBeforeUnmount(() => {
stickyObserver = null;
});
const handleAction = (action: 'edit' | 'reparse' | 'cancel-parse' | 'move' | 'delete' | 'view-trace' | 'batch-manage', item: KnowledgeItem) => {
const handleAction = (action: 'edit' | 'reparse' | 'cancel-parse' | 'move' | 'move-folder' | 'delete' | 'view-trace' | 'batch-manage', item: KnowledgeItem) => {
// Don't close popup for move — it triggers the move sub-flow
if (action !== 'move') {
moreOpen.value = null;
@ -241,6 +243,33 @@ const handleAction = (action: 'edit' | 'reparse' | 'cancel-parse' | 'move' | 'de
</div>
<div class="doc-list-body">
<!-- Sub-folders of the folder being browsed, listed above the documents
the way a file manager does. -->
<div v-for="folder in folders" :key="'folder-' + folder.path" class="doc-list-row doc-list-row--folder"
:title="folder.path" role="row" @click="emit('open-folder', folder.path)">
<div class="cell cell-check" aria-hidden="true"></div>
<div class="cell cell-name">
<span class="row-file-icon-wrap">
<t-icon name="folder" class="row-folder-icon" />
</span>
<div class="row-file-text">
<span class="row-file-name">{{ folder.name }}</span>
</div>
</div>
<div class="cell cell-tag"></div>
<div class="cell cell-source">
<span class="row-folder-meta">
{{ t('knowledgeBase.folderTree.folderCardCount', { count: folder.total_count }) }}
</span>
</div>
<div class="cell cell-size"></div>
<div class="cell cell-status"></div>
<div class="cell cell-time"></div>
<div v-if="canEdit" class="cell cell-actions">
<t-icon name="chevron-right" class="row-folder-chevron" />
</div>
</div>
<div v-for="item in items" :key="item.id" class="doc-list-row"
:class="{ selected: selectedIds.has(item.id), 'menu-open': moreOpen === item.id }" :data-select-id="item.id"
role="row" @click="emit('open', item)">
@ -337,6 +366,7 @@ const handleAction = (action: 'edit' | 'reparse' | 'cancel-parse' | 'move' | 'de
@reparse="handleAction('reparse', item)"
@cancel-parse="handleAction('cancel-parse', item)"
@move="handleAction('move', item)"
@move-folder="handleAction('move-folder', item)"
@batch-manage="handleAction('batch-manage', item)"
@delete="handleAction('delete', item)"
/>
@ -612,6 +642,25 @@ const handleAction = (action: 'edit' | 'reparse' | 'cancel-parse' | 'move' | 'de
color: var(--td-text-color-placeholder);
}
.doc-list-row--folder {
cursor: pointer;
&:hover .row-folder-chevron {
color: var(--td-brand-color);
}
}
.row-folder-icon {
color: var(--td-brand-color);
}
.row-folder-meta,
.row-folder-chevron {
font-size: 12px;
color: var(--td-text-color-placeholder);
transition: color 0.15s ease;
}
.row-file-folder {
display: inline-flex;
align-items: center;

View File

@ -26,25 +26,6 @@
</t-tooltip>
</div>
<!-- Labeled rather than an icon toggle: this switch is what makes the
documents outside every folder reachable, so it must be readable at a
glance instead of hiding behind a tooltip. -->
<div v-if="!collapsed" class="kb-folder-scope" role="group"
:aria-label="t('knowledgeBase.folderTree.scopeToggle')">
<t-tooltip :content="t('knowledgeBase.folderTree.scopeSubtreeTip')" placement="bottom">
<button type="button" class="kb-folder-scope__btn" :class="{ active: recursive }"
:aria-pressed="recursive" @click="emit('update:recursive', true)">
{{ t('knowledgeBase.folderTree.scopeSubtree') }}
</button>
</t-tooltip>
<t-tooltip :content="t('knowledgeBase.folderTree.scopeDirectTip')" placement="bottom">
<button type="button" class="kb-folder-scope__btn" :class="{ active: !recursive }"
:aria-pressed="!recursive" @click="emit('update:recursive', false)">
{{ t('knowledgeBase.folderTree.scopeDirect') }}
</button>
</t-tooltip>
</div>
<div v-if="!collapsed" class="kb-folder-tree__body">
<template v-if="loading && !tree">
<div v-for="n in 5" :key="'folder-skel-' + n" class="kb-folder-tree__skeleton">
@ -52,15 +33,17 @@
</div>
</template>
<template v-else>
<button
<div
v-for="row in rows"
:key="row.path || '__root__'"
type="button"
class="kb-folder-row"
:class="{ active: selectedPath === row.path, 'is-root': row.kind === 'root' }"
:style="{ '--kb-folder-depth': row.depth }"
:title="rowTitle(row)"
:title="row.kind === 'root' ? t('knowledgeBase.folderTree.rootRowTip') : row.path"
role="button"
tabindex="0"
@click="emit('select', row.path)"
@keydown.enter="emit('select', row.path)"
>
<span
v-if="row.hasChildren"
@ -74,71 +57,85 @@
<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="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>
<t-icon
:name="row.kind === 'root' || (row.hasChildren && isExpanded(row.path)) ? 'folder-open' : 'folder'"
class="kb-folder-row__icon"
/>
<input
v-if="renamingPath === row.path"
ref="renameInputRef"
v-model="renameValue"
class="kb-folder-row__rename"
:placeholder="t('knowledgeBase.folderTree.renamePlaceholder')"
@click.stop
@keydown.enter="commitRename(row)"
@keydown.esc="cancelRename"
@blur="commitRename(row)"
/>
<template v-else>
<span class="kb-folder-row__label">
{{ row.kind === 'root' ? t('knowledgeBase.folderTree.rootRow') : row.name }}
</span>
<t-tooltip v-if="canEdit && row.kind === 'folder'"
:content="t('knowledgeBase.folderTree.rename')" placement="top">
<button type="button" class="kb-folder-row__action"
:aria-label="t('knowledgeBase.folderTree.rename')" @click.stop="startRename(row)">
<t-icon name="edit" />
</button>
</t-tooltip>
<span class="kb-folder-row__count">{{ row.totalCount }}</span>
</template>
</div>
</template>
</div>
</aside>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { computed, nextTick, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import type { KnowledgeFolderTree } from '@/api/knowledge-base/index'
import {
buildFolderRows,
folderAncestorPaths,
folderRowCount,
rootRowLabelKey,
rootRowTitleKey,
joinFolderPath,
ROOT_FOLDER_PATH,
type FolderRow,
} from '../folderTree'
const props = withDefaults(defineProps<{
tree: KnowledgeFolderTree | null
/** Selected folder path; the empty string is the knowledge base root. */
/** Selected folder path; the empty string is the knowledge base top level. */
selectedPath: string
loading?: boolean
collapsed?: boolean
/** When true a folder lists its sub-folders' documents too. */
recursive?: boolean
canEdit?: boolean
}>(), {
loading: false,
collapsed: false,
recursive: true,
canEdit: false,
})
const emit = defineEmits<{
select: [path: string]
'update:collapsed': [collapsed: boolean]
'update:recursive': [recursive: boolean]
rename: [payload: { from: string; to: string }]
}>()
const { t } = useI18n()
// The root starts expanded so the uploaded structure is visible without a click.
const expanded = ref(new Set<string>([ROOT_FOLDER_PATH]))
const renamingPath = ref('')
const renameValue = ref('')
const renameInputRef = ref<HTMLInputElement | HTMLInputElement[] | null>(null)
const rows = computed(() => buildFolderRows(props.tree, expanded.value))
const isExpanded = (path: string) => expanded.value.has(path)
const rowLabel = (row: FolderRow) =>
row.kind === 'root' ? t(rootRowLabelKey(props.recursive)) : row.name
const rowIcon = (row: FolderRow) => {
// Direct scope on the root lists the loose documents rather than the whole
// base, so the icon drops the "folder" metaphor it no longer stands for.
if (row.kind === 'root') return props.recursive ? 'folder-open' : 'file-1'
return row.hasChildren && isExpanded(row.path) ? 'folder-open' : 'folder'
}
const rowTitle = (row: FolderRow) =>
row.kind === 'root' ? t(rootRowTitleKey(props.recursive)) : row.path
const toggle = (path: string) => {
const next = new Set(expanded.value)
if (next.has(path)) next.delete(path)
@ -146,9 +143,33 @@ const toggle = (path: string) => {
expanded.value = next
}
const startRename = async (row: FolderRow) => {
renamingPath.value = row.path
renameValue.value = row.name
await nextTick()
const input = Array.isArray(renameInputRef.value) ? renameInputRef.value[0] : renameInputRef.value
input?.focus()
input?.select()
}
const cancelRename = () => {
renamingPath.value = ''
renameValue.value = ''
}
const commitRename = (row: FolderRow) => {
if (renamingPath.value !== row.path) return
const name = renameValue.value.trim()
cancelRename()
// Only the last segment is edited here; the folder keeps its place in the tree.
if (!name || name === row.name) return
const parent = row.path.slice(0, Math.max(0, row.path.length - row.name.length - 1))
emit('rename', { from: row.path, to: joinFolderPath(parent, name) })
}
// 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).
// elsewhere (e.g. opening a folder from the document list).
watch(
() => [props.selectedPath, props.tree] as const,
() => {
@ -211,45 +232,6 @@ watch(
text-overflow: ellipsis;
}
.kb-folder-scope {
display: flex;
flex-shrink: 0;
gap: 2px;
margin-top: 2px;
padding: 2px;
border-radius: 6px;
background: var(--td-bg-color-secondarycontainer);
}
.kb-folder-scope__btn {
flex: 1;
min-width: 0;
height: 22px;
padding: 0 6px;
border: 0;
border-radius: 4px;
background: transparent;
color: var(--td-text-color-secondary);
font-family: var(--app-font-family);
font-size: 12px;
line-height: 22px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
cursor: pointer;
transition: background-color 0.15s ease, color 0.15s ease;
&:hover:not(.active) {
color: var(--td-text-color-primary);
}
&.active {
color: var(--td-brand-color);
background: var(--td-bg-color-container);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
}
}
.kb-folder-tree__icon-btn {
width: 24px;
height: 24px;
@ -268,11 +250,6 @@ watch(
color: var(--td-brand-color);
background: var(--td-bg-color-container-hover);
}
&.active {
color: var(--td-brand-color);
background: color-mix(in srgb, var(--td-brand-color) 8%, transparent);
}
}
.kb-folder-tree__body {
@ -305,7 +282,6 @@ watch(
width: 100%;
height: 30px;
padding: 0 8px 0 calc(var(--kb-folder-depth, 0) * var(--kb-folder-indent) + 8px);
border: 0;
border-radius: 6px;
background: transparent;
color: var(--td-text-color-primary);
@ -318,6 +294,10 @@ watch(
&:hover {
background: var(--td-bg-color-container-hover);
.kb-folder-row__action {
opacity: 1;
}
}
&:focus-visible {
@ -378,6 +358,46 @@ watch(
white-space: nowrap;
}
.kb-folder-row__action {
flex: 0 0 auto;
width: 20px;
height: 20px;
padding: 0;
border: 0;
border-radius: 4px;
background: transparent;
color: var(--td-text-color-placeholder);
display: inline-flex;
align-items: center;
justify-content: center;
cursor: pointer;
opacity: 0;
transition: opacity 0.15s ease, color 0.15s ease, background-color 0.15s ease;
&:hover {
color: var(--td-brand-color);
background: var(--td-bg-color-secondarycontainer);
}
.t-icon {
font-size: 13px;
}
}
.kb-folder-row__rename {
flex: 1;
min-width: 0;
height: 22px;
padding: 0 6px;
border: 1px solid var(--td-brand-color);
border-radius: 4px;
background: var(--td-bg-color-container);
color: var(--td-text-color-primary);
font-family: var(--app-font-family);
font-size: 13px;
outline: none;
}
.kb-folder-row__count {
flex: 0 0 auto;
font-size: 11px;

View File

@ -0,0 +1,256 @@
<template>
<t-dialog
:visible="visible"
:header="t('knowledgeBase.moveToFolder.title', { count })"
:confirm-btn="{ content: t('knowledgeBase.moveToFolder.confirm'), theme: 'primary', loading: submitting, disabled: !canSubmit }"
:cancel-btn="{ content: t('common.cancel') }"
width="480px"
@confirm="handleConfirm"
@close="close"
@cancel="close"
>
<div class="move-folder-body">
<p class="move-folder-hint">{{ t('knowledgeBase.moveToFolder.hint') }}</p>
<div class="move-folder-list">
<button
type="button"
class="move-folder-option"
:class="{ active: selected === '' && !creating }"
@click="pick('')"
>
<t-icon name="folder-open" class="move-folder-option__icon" />
<span class="move-folder-option__label">{{ t('knowledgeBase.folderTree.rootRow') }}</span>
<t-icon v-if="selected === '' && !creating" name="check" class="move-folder-option__check" />
</button>
<button
v-for="option in options"
:key="option.path"
type="button"
class="move-folder-option"
:class="{ active: selected === option.path && !creating }"
:style="{ '--move-folder-depth': option.depth }"
:title="option.path"
@click="pick(option.path)"
>
<t-icon name="folder" class="move-folder-option__icon" />
<span class="move-folder-option__label">{{ option.name }}</span>
<t-icon v-if="selected === option.path && !creating" name="check" class="move-folder-option__check" />
</button>
</div>
<div class="move-folder-create">
<button v-if="!creating" type="button" class="move-folder-create__trigger" @click="startCreating">
<t-icon name="folder-add" />
<span>{{ t('knowledgeBase.moveToFolder.newFolder') }}</span>
</button>
<template v-else>
<t-input
v-model.trim="newFolderName"
:placeholder="t('knowledgeBase.moveToFolder.newFolderPlaceholder')"
autofocus
clearable
@enter="handleConfirm"
/>
<p class="move-folder-create__preview">
{{ newFolderPath
? t('knowledgeBase.moveToFolder.newFolderPreview', { path: newFolderPath })
: t('knowledgeBase.moveToFolder.newFolderUnderRoot') }}
</p>
</template>
</div>
</div>
</t-dialog>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import type { KnowledgeFolderNode, KnowledgeFolderTree } from '@/api/knowledge-base/index'
import { joinFolderPath } from '../folderTree'
const props = withDefaults(defineProps<{
visible: boolean
tree: KnowledgeFolderTree | null
count: number
submitting?: boolean
/** Folder the documents are currently in, pre-selected as the starting point. */
currentPath?: string
}>(), {
submitting: false,
currentPath: '',
})
const emit = defineEmits<{
'update:visible': [value: boolean]
confirm: [folderPath: string]
}>()
const { t } = useI18n()
const selected = ref('')
const creating = ref(false)
const newFolderName = ref('')
type FolderOption = { path: string; name: string; depth: number }
const options = computed<FolderOption[]>(() => {
const result: FolderOption[] = []
const walk = (nodes: KnowledgeFolderNode[], depth: number) => {
nodes.forEach((node) => {
result.push({ path: node.path, name: node.name, depth })
walk(node.children || [], depth + 1)
})
}
walk(props.tree?.folders ?? [], 0)
return result
})
// A new folder is created under whichever folder is currently highlighted, so
// the picker doubles as "where to put it".
const newFolderPath = computed(() => joinFolderPath(selected.value, newFolderName.value))
const canSubmit = computed(() => (creating.value ? !!newFolderPath.value : true))
const pick = (path: string) => {
selected.value = path
creating.value = false
newFolderName.value = ''
}
const startCreating = () => {
creating.value = true
newFolderName.value = ''
}
const close = () => {
emit('update:visible', false)
}
const handleConfirm = () => {
if (!canSubmit.value) return
emit('confirm', creating.value ? newFolderPath.value : selected.value)
}
watch(
() => props.visible,
(visible) => {
if (!visible) return
selected.value = props.currentPath || ''
creating.value = false
newFolderName.value = ''
},
{ immediate: true },
)
</script>
<style scoped lang="less">
.move-folder-body {
display: flex;
flex-direction: column;
gap: 10px;
}
.move-folder-hint {
margin: 0;
font-size: 12px;
line-height: 1.6;
color: var(--td-text-color-placeholder);
}
.move-folder-list {
--move-folder-indent: 16px;
max-height: 260px;
overflow-y: auto;
padding: 4px;
border: 1px solid var(--td-component-stroke);
border-radius: 6px;
scrollbar-width: thin;
&::-webkit-scrollbar {
width: 4px;
}
&::-webkit-scrollbar-thumb {
border-radius: 2px;
background: var(--td-scrollbar-color);
}
}
.move-folder-option {
display: flex;
align-items: center;
gap: 6px;
box-sizing: border-box;
width: 100%;
height: 30px;
padding: 0 8px 0 calc(var(--move-folder-depth, 0) * var(--move-folder-indent) + 8px);
border: 0;
border-radius: 4px;
background: transparent;
color: var(--td-text-color-primary);
font-family: var(--app-font-family);
font-size: 13px;
text-align: left;
cursor: pointer;
transition: background 0.15s ease, color 0.15s ease;
&:hover {
background: var(--td-bg-color-container-hover);
}
&.active {
background: color-mix(in srgb, var(--td-brand-color) 8%, transparent);
color: var(--td-brand-color);
.move-folder-option__icon {
color: var(--td-brand-color);
}
}
}
.move-folder-option__icon {
flex: 0 0 auto;
font-size: 15px;
color: var(--td-text-color-placeholder);
}
.move-folder-option__label {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.move-folder-option__check {
flex: 0 0 auto;
font-size: 14px;
}
.move-folder-create__trigger {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 0;
border: 0;
background: transparent;
color: var(--td-brand-color);
font-family: var(--app-font-family);
font-size: 13px;
cursor: pointer;
.t-icon {
font-size: 15px;
}
}
.move-folder-create__preview {
margin: 6px 0 0;
font-size: 12px;
line-height: 1.6;
color: var(--td-text-color-placeholder);
word-break: break-all;
}
</style>

View File

@ -4,14 +4,16 @@ import test from 'node:test'
import {
buildFolderRows,
buildUploadFileName,
canMoveFolderTo,
childFolders,
folderAncestorPaths,
folderBreadcrumbs,
folderPathExists,
folderRowCount,
isFilteringDocuments,
isFolderUpload,
joinFolderPath,
normalizeFolderPath,
ROOT_FOLDER_PATH,
rootRowLabelKey,
rootRowTitleKey,
} from './folderTree.ts'
const folders = [
@ -142,21 +144,63 @@ test('an unloaded tree still yields a root row so the sidebar never renders empt
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', () => {
test('tree rows carry the recursive total, which is how much a folder contains', () => {
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)
assert.equal(root.totalCount, 7)
assert.equal(handbook.totalCount, 4)
assert.equal(handbook.documentCount, 1)
})
// Single-file uploads sit outside every folder, so a folder-only tree can give
// them no node of their own. The root row is named after what it actually lists
// so they are still findable, without inventing a second pseudo-folder row.
test('the root row is named after what the current scope makes it list', () => {
assert.equal(rootRowLabelKey(true), 'knowledgeBase.folderTree.rootRow')
assert.equal(rootRowLabelKey(false), 'knowledgeBase.folderTree.rootRowDirect')
assert.notEqual(rootRowTitleKey(true), rootRowTitleKey(false))
// Browsing a folder shows its own sub-folders as list entries, which is what
// lets a document uploaded on its own simply sit at the top level next to the
// folders instead of needing a mode switch to be found.
test('the list shows the direct sub-folders of the browsed folder', () => {
assert.deepEqual(
childFolders(tree, ROOT_FOLDER_PATH).map((node) => node.path),
['handbook', 'design'],
)
assert.deepEqual(
childFolders(tree, 'handbook').map((node) => node.path),
['handbook/onboarding'],
)
// A leaf folder and an unknown path both have nothing to descend into.
assert.deepEqual(childFolders(tree, 'design'), [])
assert.deepEqual(childFolders(tree, 'nope'), [])
assert.deepEqual(childFolders(null, ROOT_FOLDER_PATH), [])
})
// The browse/search distinction replaces the scope switch: it is derived from
// what the user is already doing rather than from a control they must interpret.
test('any active filter turns browsing into a subtree search', () => {
assert.equal(isFilteringDocuments({}), false)
assert.equal(isFilteringDocuments({ keyword: ' ' }), false, 'whitespace is not a search')
assert.equal(isFilteringDocuments({ timeRange: [] }), false)
assert.equal(isFilteringDocuments({ timeRange: ['', ''] }), false)
assert.equal(isFilteringDocuments({ keyword: 'spec' }), true)
assert.equal(isFilteringDocuments({ tagIds: ['t1'] }), true)
assert.equal(isFilteringDocuments({ fileType: 'pdf' }), true)
assert.equal(isFilteringDocuments({ parseStatus: 'failed' }), true)
assert.equal(isFilteringDocuments({ source: 'web' }), true)
assert.equal(isFilteringDocuments({ timeRange: ['2026-01-01', ''] }), true)
})
test('folder paths typed by the user are canonicalized like the server does', () => {
assert.equal(normalizeFolderPath(' docs / spec '), 'docs/spec')
assert.equal(normalizeFolderPath('docs//spec/'), 'docs/spec')
assert.equal(normalizeFolderPath('../../docs'), 'docs')
assert.equal(normalizeFolderPath('docs\\spec'), 'docs/spec')
assert.equal(normalizeFolderPath('///'), '')
assert.equal(joinFolderPath('handbook', 'policies '), 'handbook/policies')
assert.equal(joinFolderPath('', 'handbook'), 'handbook')
})
// Moving a folder into its own subtree would make that subtree unreachable.
test('a folder cannot be moved inside itself', () => {
assert.equal(canMoveFolderTo('docs', 'handbook'), true)
assert.equal(canMoveFolderTo('docs', 'docsets'), true, 'a shared prefix is not containment')
assert.equal(canMoveFolderTo('docs', 'docs/spec'), false)
assert.equal(canMoveFolderTo('docs', 'docs'), false)
assert.equal(canMoveFolderTo('docs', ''), false)
assert.equal(canMoveFolderTo('', 'docs'), false)
})

View File

@ -141,30 +141,85 @@ export function buildFolderRows(
}
/**
* The count a row should display, which must match what selecting it puts in
* the document list — otherwise the sidebar and the list disagree.
* Direct sub-folders of a folder, i.e. what the document list shows as folder
* entries while browsing it. The root's children are the top-level folders.
*/
export function folderRowCount(row: FolderRow, recursive: boolean): number {
return recursive ? row.totalCount : row.documentCount
export function childFolders(
tree: KnowledgeFolderTree | null,
path: string,
): KnowledgeFolderNode[] {
const folders = tree?.folders ?? []
if (path === ROOT_FOLDER_PATH) return folders
const find = (nodes: KnowledgeFolderNode[]): KnowledgeFolderNode | undefined => {
for (const node of nodes) {
if (node.path === path) return node
const found = find(node.children || [])
if (found) return found
}
return undefined
}
return find(folders)?.children ?? []
}
/**
* i18n key for the root row's label. The root is the only row whose contents
* change meaning with the scope: recursively it is the whole knowledge base,
* directly it is exactly the documents that are not inside any folder — which
* single-file uploads are, and which would otherwise have no visible home in a
* tree that can only show folders. Naming the row after what it currently lists
* keeps one mechanism instead of adding a second pseudo-folder for them.
* Whether the document list is filtering rather than browsing.
*
* This is the single input that decides how a folder selection is read, and it
* comes from what the user is already doing instead of from a mode switch they
* have to understand:
*
* - Browsing (no filter active) lists the selected folder's own contents — its
* sub-folders as entries plus the documents directly inside it, the way a file
* manager does. A document uploaded on its own therefore sits at the top level
* next to the folders, which is exactly where it belongs.
* - Filtering searches the selected folder and everything below it, returning a
* flat result set, because a search that stopped at one level would hide
* matches for no good reason.
*/
export function rootRowLabelKey(recursive: boolean): string {
return recursive
? 'knowledgeBase.folderTree.rootRow'
: 'knowledgeBase.folderTree.rootRowDirect'
export function isFilteringDocuments(filters: {
keyword?: string
tagIds?: string[]
fileType?: string
parseStatus?: string
source?: string
timeRange?: string[]
}): boolean {
return !!(
filters.keyword?.trim() ||
filters.tagIds?.length ||
filters.fileType ||
filters.parseStatus ||
filters.source ||
filters.timeRange?.filter(Boolean).length
)
}
/** i18n key for the root row's tooltip, following the same rule as its label. */
export function rootRowTitleKey(recursive: boolean): string {
return recursive
? 'knowledgeBase.folderTree.rootRowTip'
: 'knowledgeBase.folderTree.rootRowDirectTip'
/**
* Canonicalize a user-typed folder path the same way the server does, so the
* move dialog can preview and compare the destination it is about to send.
*/
export function normalizeFolderPath(path: string): string {
return path
.replace(/\\/g, '/')
.split('/')
.map((segment) => segment.trim().replace(/[. ]+$/, ''))
.filter((segment) => segment && segment !== '.' && segment !== '..')
.join('/')
}
/** Destination path for a new sub-folder of `parent`. */
export function joinFolderPath(parent: string, name: string): string {
return normalizeFolderPath(parent ? `${parent}/${name}` : name)
}
/**
* Whether a folder can be renamed/moved to `to`: a folder cannot land inside its
* own subtree, which would make that subtree unreachable.
*/
export function canMoveFolderTo(from: string, to: string): boolean {
const source = normalizeFolderPath(from)
const target = normalizeFolderPath(to)
if (!source || !target) return false
if (target === source) return false
return !target.startsWith(`${source}/`)
}

View File

@ -221,6 +221,85 @@ func (r *knowledgeRepository) ListKnowledgeFolderCounts(
return counts, nil
}
// UpdateKnowledgeFolderPath files the given knowledge entries under folderPath.
// Only the display/navigation column is touched: chunks, embeddings and the
// stored file are unaffected, which is why re-filing needs no re-processing.
// Returns the number of affected rows.
func (r *knowledgeRepository) UpdateKnowledgeFolderPath(
ctx context.Context,
tenantID uint64,
kbID string,
ids []string,
folderPath string,
) (int64, error) {
if len(ids) == 0 {
return 0, nil
}
result := r.db.WithContext(ctx).
Model(&types.Knowledge{}).
Where("tenant_id = ? AND knowledge_base_id = ? AND id IN (?)", tenantID, kbID, ids).
Updates(map[string]interface{}{"folder_path": folderPath, "updated_at": time.Now()})
if result.Error != nil {
return 0, result.Error
}
return result.RowsAffected, nil
}
// RenameKnowledgeFolderPath rewrites folder_path for a folder and every folder
// below it, which is how a folder rename or move is applied. Renaming onto an
// existing path merges the two folders. Returns the number of affected rows.
func (r *knowledgeRepository) RenameKnowledgeFolderPath(
ctx context.Context,
tenantID uint64,
kbID string,
from string,
to string,
) (int64, error) {
if from == "" {
return 0, errors.New("source folder path is required")
}
// The rewrite is done row by row rather than with SQL string functions so it
// behaves identically on PostgreSQL and SQLite.
var rows []*types.Knowledge
if err := r.db.WithContext(ctx).
Select("id", "folder_path").
Where("tenant_id = ? AND knowledge_base_id = ? AND (folder_path = ? OR folder_path LIKE ?)",
tenantID, kbID, from, escapeLikeKeyword(from)+"/%").
Find(&rows).Error; err != nil {
return 0, err
}
if len(rows) == 0 {
return 0, nil
}
// Group by destination so each distinct rewrite is a single UPDATE.
byTarget := map[string][]string{}
for _, row := range rows {
suffix := strings.TrimPrefix(row.FolderPath, from)
byTarget[types.NormalizeKnowledgeFolderPath(to+suffix)] = append(
byTarget[types.NormalizeKnowledgeFolderPath(to+suffix)], row.ID)
}
var affected int64
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
for target, targetIDs := range byTarget {
result := tx.Model(&types.Knowledge{}).
Where("tenant_id = ? AND knowledge_base_id = ? AND id IN (?)", tenantID, kbID, targetIDs).
Updates(map[string]interface{}{"folder_path": target, "updated_at": time.Now()})
if result.Error != nil {
return result.Error
}
affected += result.RowsAffected
}
return nil
})
if err != nil {
return 0, err
}
return affected, nil
}
// UpdateKnowledge updates knowledge
func (r *knowledgeRepository) UpdateKnowledge(ctx context.Context, knowledge *types.Knowledge) error {
omit := omitFieldsOnUpdate

View File

@ -0,0 +1,97 @@
package repository
import (
"context"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
)
// folderPathOf reads a row's stored folder_path directly so the assertions do
// not depend on the list filters.
func folderPathOf(t *testing.T, db *gorm.DB, id string) string {
t.Helper()
var path string
require.NoError(t, db.Raw(`SELECT folder_path FROM knowledges WHERE id = ?`, id).Scan(&path).Error)
return path
}
func TestUpdateKnowledgeFolderPath(t *testing.T) {
db := setupKnowledgeTestDB(t)
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
ctx := context.Background()
const tenantID = uint64(1)
kbID := uuid.New().String()
otherKBID := uuid.New().String()
loose := insertKnowledgeInFolder(t, db, tenantID, kbID, "", "readme.md")
filed := insertKnowledgeInFolder(t, db, tenantID, kbID, "docs", "intro.md")
foreign := insertKnowledgeInFolder(t, db, tenantID, otherKBID, "docs", "other.md")
affected, err := repo.UpdateKnowledgeFolderPath(ctx, tenantID, kbID, []string{loose, filed}, "archive/2026")
require.NoError(t, err)
assert.Equal(t, int64(2), affected)
assert.Equal(t, "archive/2026", folderPathOf(t, db, loose))
assert.Equal(t, "archive/2026", folderPathOf(t, db, filed))
// Moving back out of every folder is expressed as the empty path.
affected, err = repo.UpdateKnowledgeFolderPath(ctx, tenantID, kbID, []string{filed}, "")
require.NoError(t, err)
assert.Equal(t, int64(1), affected)
assert.Equal(t, "", folderPathOf(t, db, filed))
// A row in another knowledge base is never touched, even when its ID is passed.
affected, err = repo.UpdateKnowledgeFolderPath(ctx, tenantID, kbID, []string{foreign}, "leaked")
require.NoError(t, err)
assert.Equal(t, int64(0), affected)
assert.Equal(t, "docs", folderPathOf(t, db, foreign))
affected, err = repo.UpdateKnowledgeFolderPath(ctx, tenantID, kbID, nil, "archive")
require.NoError(t, err)
assert.Equal(t, int64(0), affected)
}
func TestRenameKnowledgeFolderPath(t *testing.T) {
db := setupKnowledgeTestDB(t)
repo := NewKnowledgeRepository(db).(*knowledgeRepository)
ctx := context.Background()
const tenantID = uint64(1)
kbID := uuid.New().String()
root := insertKnowledgeInFolder(t, db, tenantID, kbID, "", "readme.md")
docs := insertKnowledgeInFolder(t, db, tenantID, kbID, "docs", "intro.md")
spec := insertKnowledgeInFolder(t, db, tenantID, kbID, "docs/spec", "design.md")
deep := insertKnowledgeInFolder(t, db, tenantID, kbID, "docs/spec/v2", "draft.md")
sibling := insertKnowledgeInFolder(t, db, tenantID, kbID, "docsets", "unrelated.md")
// The folder and its whole subtree move; siblings whose name merely shares a
// prefix ("docsets") must not be dragged along.
affected, err := repo.RenameKnowledgeFolderPath(ctx, tenantID, kbID, "docs", "handbook")
require.NoError(t, err)
assert.Equal(t, int64(3), affected)
assert.Equal(t, "handbook", folderPathOf(t, db, docs))
assert.Equal(t, "handbook/spec", folderPathOf(t, db, spec))
assert.Equal(t, "handbook/spec/v2", folderPathOf(t, db, deep))
assert.Equal(t, "docsets", folderPathOf(t, db, sibling))
assert.Equal(t, "", folderPathOf(t, db, root))
// Renaming a nested folder onto an existing one merges them.
_, err = repo.RenameKnowledgeFolderPath(ctx, tenantID, kbID, "handbook/spec", "docsets")
require.NoError(t, err)
assert.Equal(t, "docsets", folderPathOf(t, db, spec))
assert.Equal(t, "docsets/v2", folderPathOf(t, db, deep))
assert.Equal(t, "docsets", folderPathOf(t, db, sibling))
// An unknown folder is a no-op rather than an error.
affected, err = repo.RenameKnowledgeFolderPath(ctx, tenantID, kbID, "missing", "whatever")
require.NoError(t, err)
assert.Equal(t, int64(0), affected)
_, err = repo.RenameKnowledgeFolderPath(ctx, tenantID, kbID, "", "whatever")
assert.Error(t, err, "renaming the root itself is meaningless and must be rejected")
}

View File

@ -19,6 +19,7 @@ import (
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
secutils "github.com/Tencent/WeKnora/internal/utils"
"github.com/redis/go-redis/v9"
)
@ -578,6 +579,81 @@ func (s *knowledgeService) ListKnowledgeFolderTree(ctx context.Context,
return types.BuildKnowledgeFolderTree(counts), nil
}
// MoveKnowledgeToFolder re-files knowledge entries under folderPath. Since
// folders are derived from the stored paths, a folder that does not exist yet is
// created by this call; a folder whose last entry moves away disappears.
func (s *knowledgeService) MoveKnowledgeToFolder(ctx context.Context,
kbID string, ids []string, folderPath string,
) (int64, error) {
if len(ids) == 0 {
return 0, werrors.NewBadRequestError("knowledge_ids cannot be empty")
}
normalized, err := normalizeTargetFolderPath(ctx, folderPath)
if err != nil {
return 0, err
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
affected, err := s.repo.UpdateKnowledgeFolderPath(ctx, tenantID, kbID, ids, normalized)
if err != nil {
logger.Errorf(ctx, "Failed to move knowledge to folder %q: %v", normalized, err)
return 0, err
}
logger.Infof(ctx, "Moved %d knowledge entries to folder %q in kb %s", affected, normalized, kbID)
return affected, nil
}
// RenameKnowledgeFolder moves a folder and its whole subtree to a new path.
// Renaming onto an existing folder merges them, which is the same outcome the
// user would get by moving the documents one by one.
func (s *knowledgeService) RenameKnowledgeFolder(ctx context.Context,
kbID string, from string, to string,
) (int64, error) {
source := types.NormalizeKnowledgeFolderPath(from)
if source == "" {
return 0, werrors.NewBadRequestError("源文件夹路径不能为空")
}
target, err := normalizeTargetFolderPath(ctx, to)
if err != nil {
return 0, err
}
if target == "" {
return 0, werrors.NewBadRequestError("目标文件夹路径不能为空")
}
if target == source {
return 0, nil
}
// Moving a folder inside itself would make its own subtree unreachable.
if strings.HasPrefix(target, source+"/") {
return 0, werrors.NewBadRequestError("不能将文件夹移动到它自己的子目录下")
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
affected, err := s.repo.RenameKnowledgeFolderPath(ctx, tenantID, kbID, source, target)
if err != nil {
logger.Errorf(ctx, "Failed to rename folder %q to %q: %v", source, target, err)
return 0, err
}
logger.Infof(ctx, "Renamed folder %q to %q in kb %s, %d entries affected",
source, target, kbID, affected)
return affected, nil
}
// normalizeTargetFolderPath canonicalizes a caller-supplied destination folder
// and applies the same input validation as the upload path, since the value ends
// up rendered as sidebar tree labels.
func normalizeTargetFolderPath(ctx context.Context, folderPath string) (string, error) {
trimmed := strings.TrimSpace(folderPath)
if trimmed == "" {
return "", nil
}
safe, valid := secutils.ValidateInput(trimmed)
if !valid {
logger.Errorf(ctx, "Invalid folder path: %s", secutils.SanitizeForLog(trimmed))
return "", werrors.NewValidationError("文件夹路径包含非法字符")
}
return types.NormalizeKnowledgeFolderPath(safe), nil
}
// GetKnowledgeFile retrieves the physical file associated with a knowledge entry
func (s *knowledgeService) GetKnowledgeFile(ctx context.Context, id string) (io.ReadCloser, string, error) {
// Get knowledge record

View File

@ -0,0 +1,114 @@
package service
import (
"context"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type folderMoveRepoStub struct {
interfaces.KnowledgeRepository
movedIDs []string
movedTo string
moveCalls int
renameFrom string
renameTo string
renameCalls int
}
func (r *folderMoveRepoStub) UpdateKnowledgeFolderPath(
_ context.Context, _ uint64, _ string, ids []string, folderPath string,
) (int64, error) {
r.moveCalls++
r.movedIDs = ids
r.movedTo = folderPath
return int64(len(ids)), nil
}
func (r *folderMoveRepoStub) RenameKnowledgeFolderPath(
_ context.Context, _ uint64, _ string, from string, to string,
) (int64, error) {
r.renameCalls++
r.renameFrom = from
r.renameTo = to
return 1, nil
}
func folderMoveContext() context.Context {
return context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
}
func TestMoveKnowledgeToFolderNormalizesDestination(t *testing.T) {
repo := &folderMoveRepoStub{}
svc := &knowledgeService{repo: repo}
affected, err := svc.MoveKnowledgeToFolder(folderMoveContext(), "kb-1", []string{"k1", "k2"}, "/docs//spec/")
require.NoError(t, err)
assert.Equal(t, int64(2), affected)
assert.Equal(t, "docs/spec", repo.movedTo)
assert.Equal(t, []string{"k1", "k2"}, repo.movedIDs)
}
func TestMoveKnowledgeToFolderAcceptsRootAndRejectsEmptyBatch(t *testing.T) {
repo := &folderMoveRepoStub{}
svc := &knowledgeService{repo: repo}
// The empty destination is meaningful: it files documents back at the top level.
_, err := svc.MoveKnowledgeToFolder(folderMoveContext(), "kb-1", []string{"k1"}, "")
require.NoError(t, err)
assert.Equal(t, "", repo.movedTo)
_, err = svc.MoveKnowledgeToFolder(folderMoveContext(), "kb-1", nil, "docs")
assert.Error(t, err)
assert.Equal(t, 1, repo.moveCalls, "an empty batch must not reach the repository")
}
func TestMoveKnowledgeToFolderRejectsTraversalAndUnsafeInput(t *testing.T) {
repo := &folderMoveRepoStub{}
svc := &knowledgeService{repo: repo}
_, err := svc.MoveKnowledgeToFolder(folderMoveContext(), "kb-1", []string{"k1"}, "../../etc/docs")
require.NoError(t, err)
assert.Equal(t, "etc/docs", repo.movedTo, "traversal must not escape the knowledge base")
_, err = svc.MoveKnowledgeToFolder(folderMoveContext(), "kb-1", []string{"k1"}, "<script>alert(1)</script>")
assert.Error(t, err, "folder names are rendered as tree labels, so unsafe input is rejected")
}
func TestRenameKnowledgeFolderValidatesPaths(t *testing.T) {
repo := &folderMoveRepoStub{}
svc := &knowledgeService{repo: repo}
ctx := folderMoveContext()
affected, err := svc.RenameKnowledgeFolder(ctx, "kb-1", "docs", "handbook")
require.NoError(t, err)
assert.Equal(t, int64(1), affected)
assert.Equal(t, "docs", repo.renameFrom)
assert.Equal(t, "handbook", repo.renameTo)
// Renaming a folder into its own subtree would orphan that subtree.
_, err = svc.RenameKnowledgeFolder(ctx, "kb-1", "docs", "docs/spec")
assert.Error(t, err)
// A sibling that merely shares the prefix is a legitimate destination.
_, err = svc.RenameKnowledgeFolder(ctx, "kb-1", "docs", "docsets")
require.NoError(t, err)
_, err = svc.RenameKnowledgeFolder(ctx, "kb-1", "", "handbook")
assert.Error(t, err)
_, err = svc.RenameKnowledgeFolder(ctx, "kb-1", "docs", "")
assert.Error(t, err)
// Renaming to the same path is a no-op rather than a pointless write.
before := repo.renameCalls
affected, err = svc.RenameKnowledgeFolder(ctx, "kb-1", "docs", "/docs/")
require.NoError(t, err)
assert.Equal(t, int64(0), affected)
assert.Equal(t, before, repo.renameCalls)
}

View File

@ -1069,6 +1069,208 @@ func (h *KnowledgeHandler) ListKnowledgeFolders(c *gin.Context) {
})
}
// MoveKnowledgeToFolderRequest is the body schema for POST /knowledge/folder.
type MoveKnowledgeToFolderRequest struct {
KBID string `json:"kb_id" binding:"required"`
IDs []string `json:"knowledge_ids" binding:"required"`
// FolderPath is the destination folder; the empty string is the knowledge
// base top level. It is deliberately not `binding:"required"` so documents
// can be moved back out of every folder.
FolderPath string `json:"folder_path"`
}
// MoveKnowledgeToFolder godoc
// @Summary 移动知识到文件夹
// @Description 批量修改知识条目所属文件夹。文件夹由路径推导而来,因此目标路径不存在时会自动创建;空路径表示知识库顶层。仅调整归类,不会重新解析文档
// @Tags 知识管理
// @Accept json
// @Produce json
// @Param request body MoveKnowledgeToFolderRequest true "移动请求"
// @Success 200 {object} map[string]interface{} "移动成功"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 403 {object} errors.AppError "权限不足"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge/folder [post]
func (h *KnowledgeHandler) MoveKnowledgeToFolder(c *gin.Context) {
ctx := c.Request.Context()
var req MoveKnowledgeToFolderRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(errors.NewBadRequestError("Invalid request parameters: " + err.Error()))
return
}
ids := dedupeKnowledgeIDs(req.IDs)
if len(ids) == 0 {
c.Error(errors.NewBadRequestError("knowledge_ids cannot be empty"))
return
}
const maxBatch = 200
if len(ids) > maxBatch {
c.Error(errors.NewBadRequestError(fmt.Sprintf("too many ids (max %d per batch)", maxBatch)))
return
}
kbID, effectiveTenantID, err := h.requireKnowledgeWriteAccess(c, req.KBID)
if err != nil {
c.Error(err)
return
}
ctx = context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID)
// Guard against cross-KB moves: the service layer scopes by tenant, so the
// handler must confirm every entry belongs to the requested knowledge base.
if err := h.requireKnowledgeInKB(ctx, effectiveTenantID, kbID, ids); err != nil {
c.Error(err)
return
}
affected, err := h.kgService.MoveKnowledgeToFolder(ctx, kbID, ids, req.FolderPath)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
return
}
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"moved_count": affected,
"folder_path": types.NormalizeKnowledgeFolderPath(req.FolderPath),
},
})
}
// RenameKnowledgeFolderRequest is the body schema for
// PUT /knowledge-bases/:id/knowledge/folders.
type RenameKnowledgeFolderRequest struct {
From string `json:"from" binding:"required"`
To string `json:"to" binding:"required"`
}
// RenameKnowledgeFolder godoc
// @Summary 重命名或移动文件夹
// @Description 把一个文件夹及其所有子目录改到新路径。目标路径已存在时两个文件夹合并;不能移动到自身子目录下
// @Tags 知识管理
// @Accept json
// @Produce json
// @Param id path string true "知识库ID"
// @Param request body RenameKnowledgeFolderRequest true "重命名请求"
// @Success 200 {object} map[string]interface{} "重命名成功"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 403 {object} errors.AppError "权限不足"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge-bases/{id}/knowledge/folders [put]
func (h *KnowledgeHandler) RenameKnowledgeFolder(c *gin.Context) {
ctx := c.Request.Context()
var req RenameKnowledgeFolderRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(errors.NewBadRequestError("Invalid request parameters: " + err.Error()))
return
}
_, kbID, effectiveTenantID, permission, err := h.validateKnowledgeBaseAccess(c)
if err != nil {
c.Error(err)
return
}
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
c.Error(errors.NewForbiddenError("No permission to modify knowledge"))
return
}
ctx = context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID)
affected, err := h.kgService.RenameKnowledgeFolder(ctx, kbID, req.From, req.To)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
return
}
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"moved_count": affected,
"folder_path": types.NormalizeKnowledgeFolderPath(req.To),
},
})
}
// dedupeKnowledgeIDs trims, drops empty and de-duplicates a batch of IDs while
// preserving the caller's order.
func dedupeKnowledgeIDs(raw []string) []string {
seen := make(map[string]struct{}, len(raw))
ids := make([]string, 0, len(raw))
for _, item := range raw {
id := strings.TrimSpace(item)
if id == "" {
continue
}
if _, ok := seen[id]; ok {
continue
}
seen[id] = struct{}{}
ids = append(ids, id)
}
return ids
}
// requireKnowledgeWriteAccess resolves a knowledge base from a request body and
// enforces the editor-or-admin plus ownership gate shared by the batch routes.
func (h *KnowledgeHandler) requireKnowledgeWriteAccess(
c *gin.Context,
requestedKBID string,
) (string, uint64, error) {
_, kbID, effectiveTenantID, permission, err := h.validateKnowledgeBaseAccessWithKBID(c, requestedKBID)
if err != nil {
return "", 0, err
}
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
return "", 0, errors.NewForbiddenError("No permission to modify knowledge")
}
if err := h.requireKBOwnershipOrAdmin(c, kbID); err != nil {
return "", 0, err
}
return kbID, effectiveTenantID, nil
}
// requireKnowledgeInKB verifies every ID exists and belongs to the given
// knowledge base, so a batch operation cannot reach across knowledge bases.
func (h *KnowledgeHandler) requireKnowledgeInKB(
ctx context.Context,
tenantID uint64,
kbID string,
ids []string,
) error {
knowledgeList, err := h.kgService.GetKnowledgeBatch(ctx, tenantID, ids)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
return errors.NewInternalServerError(err.Error())
}
if len(knowledgeList) != len(ids) {
return errors.NewBadRequestError("One or more knowledge entries not found")
}
for _, k := range knowledgeList {
if k.KnowledgeBaseID != kbID {
return errors.NewBadRequestError(
fmt.Sprintf("Knowledge %s does not belong to knowledge base %s",
secutils.SanitizeForLog(k.ID), secutils.SanitizeForLog(kbID)))
}
}
return nil
}
// DeleteKnowledge godoc
// @Summary 删除知识
// @Description 根据ID异步删除知识条目。请求会被入队到与批量删除相同的异步管道(asynq);
@ -1156,20 +1358,7 @@ func (h *KnowledgeHandler) BatchDeleteKnowledge(c *gin.Context) {
return
}
// Deduplicate and drop empty IDs.
seen := make(map[string]struct{}, len(req.IDs))
ids := make([]string, 0, len(req.IDs))
for _, raw := range req.IDs {
id := strings.TrimSpace(raw)
if id == "" {
continue
}
if _, ok := seen[id]; ok {
continue
}
seen[id] = struct{}{}
ids = append(ids, id)
}
ids := dedupeKnowledgeIDs(req.IDs)
if len(ids) == 0 {
c.Error(errors.NewBadRequestError("ids cannot be empty"))
return

View File

@ -75,6 +75,7 @@ func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandl
kb.POST("/manual", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.CreateManualKnowledge)
kbRead.GET("", g.Viewer(), g.KBAccessRead("id"), handler.ListKnowledge)
kbRead.GET("/folders", g.Viewer(), g.KBAccessRead("id"), handler.ListKnowledgeFolders)
kb.PUT("/folders", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.RenameKnowledgeFolder)
// Clearing all contents under a KB is a destructive op; gate
// behind Admin instead of Contributor.
kb.With(apiKeyFullAccess()).DELETE("", g.Admin(), g.KBAccessWrite("id"), handler.ClearKnowledgeBaseContents)
@ -127,6 +128,7 @@ func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandl
k.PUT("/tags", g.Contributor(), handler.UpdateKnowledgeTagBatch)
k.POST("/batch-reparse", g.Contributor(), handler.BatchReparseKnowledge)
k.POST("/batch-delete", g.Contributor(), handler.BatchDeleteKnowledge)
k.POST("/folder", g.Contributor(), handler.MoveKnowledgeToFolder)
k.POST("/move", g.Contributor(), handler.MoveKnowledge)
}
}

View File

@ -88,6 +88,17 @@ type KnowledgeService interface {
// folder_path of every knowledge entry in a knowledge base, with per-folder
// document counts. It powers the document sidebar tree.
ListKnowledgeFolderTree(ctx context.Context, kbID string) (*types.KnowledgeFolderTree, error)
// MoveKnowledgeToFolder re-files knowledge entries under the given folder
// path (empty means the knowledge base top level). Folders are derived from
// the stored paths, so a path that does not exist yet is created implicitly.
MoveKnowledgeToFolder(
ctx context.Context,
kbID string,
ids []string,
folderPath string,
) (int64, error)
// RenameKnowledgeFolder moves a folder and everything below it to a new path.
RenameKnowledgeFolder(ctx context.Context, kbID string, from string, to string) (int64, error)
// DeleteKnowledge deletes knowledge by ID.
DeleteKnowledge(ctx context.Context, id string) error
// DeleteKnowledgeList deletes multiple knowledge entries by IDs.
@ -252,6 +263,23 @@ type KnowledgeRepository interface {
tenantID uint64,
kbID string,
) ([]*types.KnowledgeFolderCount, error)
// UpdateKnowledgeFolderPath files the given entries under folderPath.
UpdateKnowledgeFolderPath(
ctx context.Context,
tenantID uint64,
kbID string,
ids []string,
folderPath string,
) (int64, error)
// RenameKnowledgeFolderPath rewrites folder_path for a folder and all of its
// descendants. Renaming onto an existing path merges the folders.
RenameKnowledgeFolderPath(
ctx context.Context,
tenantID uint64,
kbID string,
from string,
to string,
) (int64, error)
// AminusB returns the IDs of knowledge in A that have no counterpart in B,
// comparing file_hash as a multiset (so duplicate-count differences and
// NULL/empty hashes are handled correctly, letting a clone converge).