Skip to content

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

fix(knowledge): 文件夹树显示递归文档数,不再把有子目录的文件夹显示成 0 (#4428)

linus-liu-webe6dc60be3278
diff --git a/frontend/src/i18n/index.ts b/frontend/src/i18n/index.ts
index 1bfbb866b..1f3561c9b 100755
--- a/frontend/src/i18n/index.ts
+++ b/frontend/src/i18n/index.ts
@@ -6,6 +6,7 @@ import koKR from './locales/ko-KR.ts'
import jaJP from './locales/ja-JP.ts'
import zhTW from './locales/zh-TW.ts'
import { BUILT_IN_DEFAULT, resolveDefaultLocale } from './resolveDefaultLocale.ts'
+import { pluralRules } from './pluralizationRules.ts'
const messages = {
'zh-CN': zhCN,
@@ -27,6 +28,7 @@ const i18n = createI18n({
locale: savedLocale,
fallbackLocale: BUILT_IN_DEFAULT,
globalInjection: true,
+ pluralRules,
// Some translations intentionally embed `<strong>` markup (e.g. agent step summaries).
// We render them via v-html with our own sanitization, so silence vue-i18n's HTML warning
// to avoid flooding the console and slowing renders during history loads.
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 32c483ecf..5be33b96f 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -654,7 +654,7 @@ export default {
},
knowledgeBase: {
tagAddAction: 'Add tags',
- documentCount: '{count} documents',
+ documentCount: '{count} document | {count} documents',
filters: 'Filters',
clearFilters: 'Clear filters',
@@ -720,9 +720,11 @@ export default {
title: 'Folders',
rootRow: 'Root',
rootRowTip: 'Knowledge base root; documents not in a subfolder live here',
- folderCardCount: '{count} documents',
+ folderCardCount: '{count} document | {count} documents',
searchingSubtree: '(including sub-folders)',
emptyFolder: 'This folder has no documents yet',
+ emptyFolderWithSubfolders: 'This folder has no documents of its own, but {count} in sub-folders',
+ folderContentsCount: '{documents} documents / {folders} folder | {documents} documents / {folders} folders',
emptySearch: 'No matching documents',
collapse: 'Collapse folders',
expand: 'Expand folders',
diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts
index 90b3c2d86..dcd179a33 100644
--- a/frontend/src/i18n/locales/ja-JP.ts
+++ b/frontend/src/i18n/locales/ja-JP.ts
@@ -723,6 +723,8 @@ export default {
folderCardCount: '{count}件のドキュメント',
searchingSubtree: '(サブフォルダを含む)',
emptyFolder: 'このフォルダにはまだドキュメントがありません',
+ emptyFolderWithSubfolders: 'このフォルダに直接のドキュメントはありませんが、サブフォルダに {count} 件あります',
+ folderContentsCount: '{documents} 件のドキュメント / {folders} 個のフォルダ',
emptySearch: '該当するドキュメントがありません',
collapse: 'フォルダを折りたたむ',
expand: 'フォルダを展開',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index c54f1a911..69b77e18f 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -7670,6 +7670,8 @@ export default {
folderCardCount: '문서 {count}개',
searchingSubtree: '(하위 폴더 포함)',
emptyFolder: '이 폴더에는 아직 문서가 없습니다',
+ emptyFolderWithSubfolders: '이 폴더에는 직접 문서가 없지만 하위 폴더에 {count}개가 있습니다',
+ folderContentsCount: '문서 {documents}개 / 폴더 {folders}개',
emptySearch: '일치하는 문서가 없습니다',
collapse: '폴더 접기',
expand: '폴더 펼치기',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 1fb854617..85ac97fef 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -7670,6 +7670,8 @@ export default {
folderCardCount: 'Документов: {count}',
searchingSubtree: '(с вложенными папками)',
emptyFolder: 'В этой папке пока нет документов',
+ emptyFolderWithSubfolders: 'В этой папке нет собственных документов, но в подпапках есть {count}',
+ folderContentsCount: 'Документов: {documents} / {folders} папка | Документов: {documents} / {folders} папки | Документов: {documents} / {folders} папок',
emptySearch: 'Подходящих документов нет',
collapse: 'Свернуть папки',
expand: 'Развернуть папки',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 05d3412d5..610127eea 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -7671,6 +7671,8 @@ export default {
folderCardCount: '{count} 个文档',
searchingSubtree: '(含子目录)',
emptyFolder: '这个文件夹里还没有文档',
+ emptyFolderWithSubfolders: '这个目录里没有直接文档,子目录里有 {count} 个',
+ folderContentsCount: '{documents} 个文档 / {folders} 个文件夹',
emptySearch: '没有匹配的文档',
collapse: '收起目录',
expand: '展开目录',
diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts
index 8b2184d21..5216d02c0 100644
--- a/frontend/src/i18n/locales/zh-TW.ts
+++ b/frontend/src/i18n/locales/zh-TW.ts
@@ -7671,6 +7671,8 @@ export default {
folderCardCount: '{count} 個文件',
searchingSubtree: '(含子目錄)',
emptyFolder: '這個資料夾裡還沒有文件',
+ emptyFolderWithSubfolders: '這個目錄裡沒有直接文件,子目錄裡有 {count} 個',
+ folderContentsCount: '{documents} 個文件 / {folders} 個資料夾',
emptySearch: '沒有比對的文件',
collapse: '收起目錄',
expand: '展開目錄',
diff --git a/frontend/src/i18n/pluralizationRules.ts b/frontend/src/i18n/pluralizationRules.ts
new file mode 100644
index 000000000..b23e6f240
--- /dev/null
+++ b/frontend/src/i18n/pluralizationRules.ts
@@ -0,0 +1,18 @@
+/**
+ * vue-i18n's built-in plural rule only distinguishes "one" and "other". Russian
+ * has three forms (one / few / many), so messages written with three pipes need
+ * a selector that follows the CLDR rules. Only locales listed here are affected;
+ * everything else keeps the default rule.
+ */
+export const pluralRules: Record<string, (choice: number, choicesLength: number) => number> = {
+ ru: russianPluralRule,
+ 'ru-RU': russianPluralRule,
+}
+
+function russianPluralRule(choice: number, choicesLength: number): number {
+ if (choicesLength < 3) return Math.abs(choice) === 1 ? 0 : 1
+ const value = Math.abs(choice)
+ if (value % 10 === 1 && value % 100 !== 11) return 0
+ if (value % 10 >= 2 && value % 10 <= 4 && (value % 100 < 10 || value % 100 >= 20)) return 1
+ return 2
+}
diff --git a/frontend/src/views/knowledge/KnowledgeBase.vue b/frontend/src/views/knowledge/KnowledgeBase.vue
index 212902b74..50a6e5f60 100644
--- a/frontend/src/views/knowledge/KnowledgeBase.vue
+++ b/frontend/src/views/knowledge/KnowledgeBase.vue
@@ -68,7 +68,9 @@ import { resolveKnowledgeDownloadFileName } from './knowledgeDownloadFileName';
import {
buildUploadFileName,
canMoveFolderTo,
+ childFolders,
folderBreadcrumbs as buildFolderBreadcrumbs,
+ folderDocumentCounts,
folderPathExists as folderExistsInTree,
isFilteringDocuments,
ROOT_FOLDER_PATH,
@@ -817,7 +819,50 @@ const isFiltering = computed(() =>
);
// A row's folder is worth showing only when the list can span folders.
const showDocumentFolderPath = computed(() => hasFolders.value && isFiltering.value);
+// Browsing a folder lists its direct sub-folders as entries, the way a file
+// manager does. Filtering returns matching documents from the whole subtree,
+// so folder entries would be noise there.
+const visibleSubFolders = computed(() =>
+ isFiltering.value ? [] : childFolders(folderTree.value, selectedFolderPath.value),
+);
const folderBreadcrumbs = computed(() => buildFolderBreadcrumbs(selectedFolderPath.value));
+// What the breadcrumb reports is the folder's own contents the way a file
+// manager counts them: the documents this list can show plus its direct
+// sub-folders, which the sidebar tree lists as rows. A recursive document total
+// here would not match what the page shows, so that number stays on the tree row
+// and in the empty state below. Filtering searches the subtree instead and
+// reports only the flat result set, so it adds no folder number.
+const folderContentsCount = computed<{ documents: number; folders: number }>(() => ({
+ documents: total.value,
+ folders: isFiltering.value ? 0 : childFolders(folderTree.value, selectedFolderPath.value).length,
+}));
+// A folder with no sub-folders would otherwise end the breadcrumb with
+// "/ 0 folders"; the document-only message is the whole truth there.
+const showFolderContentsCount = computed(
+ () => !isFiltering.value && folderContentsCount.value.folders > 0,
+);
+const folderContentsMessage = computed(() => ({
+ documents: folderContentsCount.value.documents,
+ folders: folderContentsCount.value.folders,
+ // vue-i18n selects the plural form from `count`; folders are the noun that
+ // changes with the number.
+ count: folderContentsCount.value.folders,
+}));
+// Documents below the selected folder rather than directly inside it; this is
+// what tells "documents live in the sub-folders" apart from "nothing here yet".
+const folderSubfolderDocumentCount = computed(() => {
+ const counts = folderDocumentCounts(folderTree.value, selectedFolderPath.value);
+ if (!counts) return 0;
+ return Math.max(0, counts.total - counts.direct);
+});
+// Which empty state the document list needs: a search without matches, a folder
+// whose documents are all below it, a plain empty folder, or the onboarding
+// panel for a knowledge base that has no folders at all.
+const folderEmptyState = computed<'search' | 'subfolders' | 'folder' | 'none'>(() => {
+ if (isFiltering.value) return 'search';
+ if (folderSubfolderDocumentCount.value > 0) return 'subfolders';
+ return hasFolders.value || selectedFolderPath.value ? 'folder' : 'none';
+});
const filterParams = computed(() => {
const [start, end] = updatedTimeRange.value || [];
@@ -2457,7 +2502,11 @@ const handleKBEditorSuccess = (kbIdValue: string) => {
<span v-if="index === folderBreadcrumbs.length - 1" class="doc-folder-path__crumb is-current" :title="crumb.name" aria-current="page">{{ crumb.name }}</span>
<button v-else type="button" class="doc-folder-path__crumb" :title="crumb.name" @click="handleFolderSelect(crumb.path)">{{ crumb.name }}</button>
</template>
- <span v-if="!docListLoading" class="doc-folder-path__count">{{ $t(isFiltering ? 'knowledgeBase.folderTree.filteredCount' : 'knowledgeBase.documentCount', { count: total }) }}</span>
+ <span v-if="!docListLoading" class="doc-folder-path__count">
+ <template v-if="isFiltering">{{ $t('knowledgeBase.folderTree.filteredCount', { count: folderContentsCount.documents }) }}</template>
+ <template v-else-if="showFolderContentsCount">{{ $t('knowledgeBase.folderTree.folderContentsCount', folderContentsMessage) }}</template>
+ <template v-else>{{ $t('knowledgeBase.documentCount', { count: folderContentsCount.documents }) }}</template>
+ </span>
<t-tooltip v-if="showFolderTree && isFiltering" :content="$t('knowledgeBase.folderTree.searchingSubtree')">
<t-icon name="info-circle" class="doc-folder-path__sep" />
</t-tooltip>
@@ -2590,7 +2639,7 @@ const handleKBEditorSuccess = (kbIdValue: string) => {
</div>
<div class="doc-scroll-container"
:class="{
- 'is-empty': !cardList.length && !docListLoading,
+ 'is-empty': !cardList.length && !visibleSubFolders.length && !docListLoading,
'is-marquee-active': docMarqueeVisible,
}"
ref="knowledgeScroll" @scroll="handleScroll" @mousedown="onDocMarqueeMouseDown">
@@ -2618,10 +2667,11 @@ const handleKBEditorSuccess = (kbIdValue: string) => {
</div>
</div>
</div>
- <template v-else-if="cardList.length && viewMode === 'grid'">
+ <template v-else-if="(cardList.length || visibleSubFolders.length) && viewMode === 'grid'">
<DocumentCardView :kb-id="kbId"
:items="cardList"
:folder-options="folderOptions"
+ :sub-folders="visibleSubFolders"
:selected-ids="selectedIds"
:batch-mode="batchMode"
:can-edit="canEdit"
@@ -2648,8 +2698,9 @@ const handleKBEditorSuccess = (kbIdValue: string) => {
@update:move-mode="(mode: any) => moveMode = mode"
/>
</template>
- <template v-else-if="cardList.length && viewMode === 'list'">
+ <template v-else-if="(cardList.length || visibleSubFolders.length) && viewMode === 'list'">
<DocumentListView :kb-id="kbId" :items="cardList" :folder-options="folderOptions"
+ :sub-folders="visibleSubFolders"
:selected-ids="selectedIds"
:can-edit="canEdit" :can-download="canDownloadKnowledge" :can-mutate-knowledge="canMutateKnowledge"
:trace-visible-ids="traceAvailableById"
@@ -2674,10 +2725,14 @@ const handleKBEditorSuccess = (kbIdValue: string) => {
</template>
<template v-else-if="!docListLoading">
<div class="doc-empty-state">
- <p v-if="hasFolders || selectedFolderPath || isFiltering" class="doc-empty-folder">
- {{ isFiltering
- ? $t('knowledgeBase.folderTree.emptySearch')
- : $t('knowledgeBase.folderTree.emptyFolder') }}
+ <p v-if="folderEmptyState === 'search'" class="doc-empty-folder">
+ {{ $t('knowledgeBase.folderTree.emptySearch') }}
+ </p>
+ <p v-else-if="folderEmptyState === 'subfolders'" class="doc-empty-folder">
+ {{ $t('knowledgeBase.folderTree.emptyFolderWithSubfolders', { count: folderSubfolderDocumentCount }) }}
+ </p>
+ <p v-else-if="folderEmptyState === 'folder'" class="doc-empty-folder">
+ {{ $t('knowledgeBase.folderTree.emptyFolder') }}
</p>
<EmptyKnowledge v-else />
</div>
diff --git a/frontend/src/views/knowledge/KnowledgeBaseFolderCounts.test.ts b/frontend/src/views/knowledge/KnowledgeBaseFolderCounts.test.ts
new file mode 100644
index 000000000..8e66a4eee
--- /dev/null
+++ b/frontend/src/views/knowledge/KnowledgeBaseFolderCounts.test.ts
@@ -0,0 +1,306 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test, { type TestContext } from 'node:test'
+import { createI18n } from 'vue-i18n'
+import * as vue from 'vue'
+import * as stall from '../../utils/knowledgeProcessingStall.ts'
+import { fixture, flush } from '../../test-utils/vueFixture.ts'
+import enUS from '../../i18n/locales/en-US'
+import zhCN from '../../i18n/locales/zh-CN'
+import zhTW from '../../i18n/locales/zh-TW'
+import jaJP from '../../i18n/locales/ja-JP'
+import koKR from '../../i18n/locales/ko-KR'
+import ruRU from '../../i18n/locales/ru-RU'
+import { pluralRules } from '../../i18n/pluralizationRules'
+
+const source = readFileSync(new URL('./KnowledgeBase.vue', import.meta.url), 'utf8')
+
+// Mirrors the deployed DingTalk sync, which produces multi-level folders:
+// 售后 holds 2 documents of its own plus a video sub-folder with 1 more, so its
+// direct, sub-folder and recursive numbers are all different. The root has 3
+// documents of its own and 5 top-level folders, and the whole base holds 17.
+const syncedTree = {
+ root_document_count: 3,
+ total_document_count: 17,
+ folders: [
+ { path: '培训材料库', name: '培训材料库', document_count: 3, total_count: 3 },
+ {
+ path: '天诛渗透攻防',
+ name: '天诛渗透攻防',
+ document_count: 0,
+ total_count: 5,
+ children: [
+ { path: '天诛渗透攻防/FAQ', name: 'FAQ', document_count: 2, total_count: 2 },
+ {
+ path: '天诛渗透攻防/售后',
+ name: '售后',
+ document_count: 2,
+ total_count: 3,
+ children: [
+ {
+ path: '天诛渗透攻防/售后/2024使用培训视频',
+ name: '2024使用培训视频',
+ document_count: 1,
+ total_count: 1,
+ },
+ ],
+ },
+ ],
+ },
+ { path: '设计规范', name: '设计规范', document_count: 4, total_count: 4 },
+ { path: '历史归档', name: '历史归档', document_count: 2, total_count: 2 },
+ { path: '空目录', name: '空目录', document_count: 0, total_count: 0 },
+ ],
+}
+
+async function setup(t: TestContext, tree: unknown) {
+ const f = fixture(t)
+ const route = vue.reactive({ params: { kbId: 'kb' }, query: {} })
+ const hook = {
+ cardList: vue.ref<any[]>([]), total: vue.ref(0), moreIndex: vue.ref(-1),
+ details: vue.reactive({ id: 'doc' }), getKnowled: t.mock.fn(async () => {}),
+ getCardDetails: t.mock.fn(), getfDetails() {}, onVisibleChange() {},
+ }
+ const listKnowledgeFolders = t.mock.fn(async (_id: string) => ({ data: tree }))
+ const fetchKnowledgeBaseById = t.mock.fn(async (_id: string, _force: boolean) => ({ id: 'kb', type: 'document' }))
+ const page = f.component(new URL('./KnowledgeBase.vue', import.meta.url), {
+ 'vue-router': { useRoute: () => route, useRouter: () => ({ replace() {} }) },
+ 'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
+ 'tdesign-vue-next': { MessagePlugin: {} },
+ '@/hooks/useKnowledgeBase': () => hook,
+ '@/stores/ui': { useUIStore: () => ({ clearSelectedTagIds() {} }) },
+ '@/stores/organization': { useOrganizationStore: () => ({ sharedKnowledgeBases: [], getKBPermission: () => 'owner' }) },
+ '@/stores/auth': { useAuthStore: () => ({ hasRole: () => true }) },
+ '@/stores/chatResources': { useChatResourcesStore: () => ({
+ fetchKnowledgeBaseById, rawKnowledgeBases: [], async ensureKnowledgeBases() {},
+ }) },
+ '@/stores/editorResources': { useEditorResourcesStore: () => ({ parserEngines: [], async ensureParserEngines() {} }) },
+ '@/stores/uploadConfirm': { useUploadConfirmStore: () => ({}) },
+ '@/stores/uploadTasks': { useUploadTasksStore: () => ({}) },
+ '@/hooks/useMarqueeSelect': { useMarqueeSelect: () => ({}) },
+ '@/composables/useAssistantPageContext': { useAssistantPageContext() {} },
+ '@/utils/kbPermission': {}, '@/utils/knowledgeDeletion': {}, '@/utils/knowledgeTrace': {},
+ '@/utils/knowledgeProcessingStall': stall, '@/api/wiki': {}, '@/api/knowledge-base': {},
+ '@/api/knowledge-base/index': { listKnowledgeFolders, listKnowledgeTags: async () => ({ data: { data: [], total: 0 } }) },
+ })
+ await flush()
+ return { ...f, ...page, hook, listKnowledgeFolders }
+}
+
+async function selectFolder(f: Awaited<ReturnType<typeof setup>>, path: string) {
+ f.vm.selectedFolderPath = path
+ await flush()
+}
+
+// ── Breadcrumb ──────────────────────────────────────────────────────────────
+
+test('the breadcrumb counts the documents and sub-folders the page can show', async t => {
+ const f = await setup(t, syncedTree)
+ f.hook.total.value = 2 // the two documents directly inside 售后
+ await selectFolder(f, '天诛渗透攻防/售后')
+ assert.equal(f.vm.folderContentsCount.documents, 2)
+ assert.equal(f.vm.folderContentsCount.folders, 1)
+ // 3 is the recursive document total (2 direct + 1 in the video sub-folder),
+ // which is what used to be shown next to a list of only 2.
+ assert.notEqual(f.vm.folderContentsCount.documents, 3)
+ // Fed through the real zh-CN bundle, the pair renders as DingTalk does.
+ assert.equal(renderFolderContents('zh-CN', f.vm.folderContentsCount), '2 个文档 / 1 个文件夹')
+})
+
+test('the root breadcrumb counts the root documents and the top-level folders', async t => {
+ const f = await setup(t, syncedTree)
+ f.hook.total.value = 3 // the root-level documents only
+ assert.equal(f.vm.selectedFolderPath, '')
+ assert.equal(f.vm.folderContentsCount.documents, 3)
+ assert.equal(f.vm.folderContentsCount.folders, 5)
+ // 17 is the whole knowledge base, not what the root list shows.
+ assert.notEqual(f.vm.folderContentsCount.documents, 17)
+})
+
+test('the sub-folder number is direct children, not the documents below them', async t => {
+ const f = await setup(t, syncedTree)
+ f.hook.total.value = 0
+ await selectFolder(f, '天诛渗透攻防')
+ // FAQ and 售后: the two direct sub-folders.
+ assert.equal(f.vm.folderContentsCount.folders, 2)
+ // The empty state still reports the 5 documents inside those sub-folders.
+ assert.equal(f.vm.folderSubfolderDocumentCount, 5)
+ assert.equal(f.vm.folderEmptyState, 'subfolders')
+})
+
+test('the breadcrumb omits the folder segment when the folder has no sub-folders', async t => {
+ const f = await setup(t, syncedTree)
+ f.hook.total.value = 2
+ await selectFolder(f, '培训材料库')
+ assert.equal(f.vm.folderContentsCount.folders, 0)
+ assert.equal(f.vm.isFiltering, false)
+ assert.equal(f.vm.showFolderContentsCount, false)
+ // The same branch feeds the existing single-number message; rendered for
+ // real, it cannot contain a "/ 0 folders" tail.
+ const i18n = createI18n({ legacy: false, locale: 'zh-CN', messages: { 'zh-CN': zhCN } })
+ const text = i18n.global.t('knowledgeBase.documentCount', { count: 2 })
+ assert.equal(text, '2 个文档')
+ assert.doesNotMatch(text, /文件夹/)
+})
+
+test('filtering keeps the flat result count and adds no folder number', async t => {
+ const f = await setup(t, syncedTree)
+ await selectFolder(f, '天诛渗透攻防/售后')
+ f.hook.total.value = 2 // two matching documents inside the subtree
+ f.vm.docSearchKeyword = 'FAQ'
+ await flush()
+ assert.equal(f.vm.isFiltering, true)
+ assert.equal(f.vm.folderContentsCount.documents, 2)
+ assert.equal(f.vm.folderContentsCount.folders, 0)
+})
+
+// ── Sub-folders as list entries ─────────────────────────────────────────────
+// Browsing a folder lists its direct children, the way a file manager does.
+// The document list and card grid receive exactly this array.
+
+test('the page lists exactly the direct sub-folders of the current folder', async t => {
+ const f = await setup(t, syncedTree)
+ await selectFolder(f, '天诛渗透攻防')
+ assert.deepEqual(
+ f.vm.visibleSubFolders.map((node: { path: string }) => node.path),
+ ['天诛渗透攻防/FAQ', '天诛渗透攻防/售后'],
+ )
+
+ await selectFolder(f, '')
+ assert.equal(f.vm.visibleSubFolders.length, 5)
+})
+
+test('filtering hides sub-folder entries because it lists matching documents', async t => {
+ const f = await setup(t, syncedTree)
+ await selectFolder(f, '天诛渗透攻防')
+ f.vm.docSearchKeyword = 'FAQ'
+ await flush()
+ assert.equal(f.vm.isFiltering, true)
+ assert.equal(f.vm.visibleSubFolders.length, 0)
+})
+
+test('an unloaded folder tree contributes no sub-folder entries', async t => {
+ const f = await setup(t, null)
+ await selectFolder(f, '天诛渗透攻防')
+ assert.equal(f.vm.folderTree, null)
+ assert.equal(f.vm.visibleSubFolders.length, 0)
+})
+
+test('an unloaded folder tree reports no folders instead of crashing', async t => {
+ const f = await setup(t, null)
+ f.hook.total.value = 4
+ await selectFolder(f, '天诛渗透攻防')
+ assert.equal(f.vm.folderTree, null)
+ assert.equal(f.vm.folderContentsCount.documents, 4)
+ assert.equal(f.vm.folderContentsCount.folders, 0)
+})
+
+test('a stale folder path reports no folders instead of crashing', async t => {
+ const f = await setup(t, syncedTree)
+ f.hook.total.value = 2
+ await selectFolder(f, '已删除/目录')
+ assert.equal(f.vm.folderContentsCount.documents, 2)
+ assert.equal(f.vm.folderContentsCount.folders, 0)
+})
+
+// ── Wording ─────────────────────────────────────────────────────────────────
+// The rendered numbers are the pair above; these assertions pin the message the
+// template feeds them into, so a single-number message cannot come back.
+const FOLDER_CONTENTS = 'knowledgeBase.folderTree.folderContentsCount'
+const locales = {
+ 'zh-CN': zhCN, 'zh-TW': zhTW, 'en-US': enUS, 'ja-JP': jaJP, 'ko-KR': koKR, 'ru-RU': ruRU,
+}
+
+function renderFolderContents(
+ locale: keyof typeof locales,
+ counts: { documents: number; folders: number } = { documents: 2, folders: 1 },
+): string {
+ const i18n = createI18n({ legacy: false, locale, pluralRules, messages: { [locale]: locales[locale] } })
+ // `count` is what vue-i18n uses to pick the plural form; the folder number is
+ // the noun that changes, so it drives the choice.
+ return i18n.global.t(FOLDER_CONTENTS, { ...counts, count: counts.folders })
+}
+
+test('every locale renders both numbers as "documents / folders"', () => {
+ assert.equal(renderFolderContents('zh-CN'), '2 个文档 / 1 个文件夹')
+ assert.equal(renderFolderContents('zh-TW'), '2 個文件 / 1 個資料夾')
+ assert.equal(renderFolderContents('en-US'), '2 documents / 1 folder')
+ assert.equal(renderFolderContents('ja-JP'), '2 件のドキュメント / 1 個のフォルダ')
+ assert.equal(renderFolderContents('ko-KR'), '문서 2개 / 폴더 1개')
+ assert.equal(renderFolderContents('ru-RU'), 'Документов: 2 / 1 папка')
+})
+
+test('plural locales inflect the folder noun', () => {
+ assert.equal(renderFolderContents('en-US', { documents: 2, folders: 2 }), '2 documents / 2 folders')
+ assert.equal(renderFolderContents('ru-RU', { documents: 2, folders: 2 }), 'Документов: 2 / 2 папки')
+ assert.equal(renderFolderContents('ru-RU', { documents: 2, folders: 5 }), 'Документов: 2 / 5 папок')
+ // No plural change in these locales; the number alone changes.
+ assert.equal(renderFolderContents('zh-CN', { documents: 2, folders: 2 }), '2 个文档 / 2 个文件夹')
+ assert.equal(renderFolderContents('ja-JP', { documents: 1, folders: 1 }), '1 件のドキュメント / 1 個のフォルダ')
+ assert.equal(renderFolderContents('ko-KR', { documents: 2, folders: 2 }), '문서 2개 / 폴더 2개')
+})
+
+// ── Empty state ─────────────────────────────────────────────────────────────
+
+test('a folder whose documents live in sub-folders is not called empty', async t => {
+ const f = await setup(t, syncedTree)
+ await selectFolder(f, '天诛渗透攻防')
+ assert.equal(f.vm.folderSubfolderDocumentCount, 5)
+ assert.equal(f.vm.folderEmptyState, 'subfolders')
+})
+
+test('a folder that really has no documents keeps the plain empty message', async t => {
+ const f = await setup(t, syncedTree)
+ await selectFolder(f, '空目录')
+ assert.equal(f.vm.folderSubfolderDocumentCount, 0)
+ assert.equal(f.vm.folderEmptyState, 'folder')
+})
+
+test('filtering keeps the no-match empty message', async t => {
+ const f = await setup(t, syncedTree)
+ await selectFolder(f, '天诛渗透攻防')
+ f.vm.docSearchKeyword = 'nothing matches this'
+ await flush()
+ assert.equal(f.vm.folderEmptyState, 'search')
+})
+
+test('a knowledge base without folders keeps the onboarding empty state', async t => {
+ const f = await setup(t, { root_document_count: 0, total_document_count: 0, folders: [] })
+ assert.equal(f.vm.folderEmptyState, 'none')
+})
+
+// The rendered count and message come from the template, which the mounted
+// fixture does not render; these assertions keep the wiring honest.
+function expectSource(pattern: RegExp) {
+ assert.ok(pattern.test(source), `KnowledgeBase.vue should match ${pattern}`)
+}
+
+test('the breadcrumb wires both numbers into the two-part message', () => {
+ expectSource(/\$t\('knowledgeBase\.folderTree\.folderContentsCount', folderContentsMessage\)/)
+ expectSource(
+ /\$t\('knowledgeBase\.folderTree\.filteredCount', \{ count: folderContentsCount\.documents \}\)/,
+ )
+ expectSource(/v-if="isFiltering"/)
+ expectSource(/v-else-if="showFolderContentsCount"/)
+ // With no sub-folders the two-part message would end in "0 folders", so the
+ // breadcrumb falls back to the existing document-only message.
+ expectSource(/\$t\('knowledgeBase\.documentCount', \{ count: folderContentsCount\.documents \}\)/)
+})
+
+test('the document views receive the current sub-folders', () => {
+ const passed = source.match(/:sub-folders="visibleSubFolders"/g) || []
+ assert.equal(passed.length, 2, 'both the list and the card grid should receive the folders')
+})
+
+test('the empty state tells sub-folder documents apart from an empty folder', () => {
+ const search = source.indexOf("knowledgeBase.folderTree.emptySearch")
+ const subfolders = source.indexOf("knowledgeBase.folderTree.emptyFolderWithSubfolders")
+ const emptyFolder = source.indexOf("knowledgeBase.folderTree.emptyFolder')")
+
+ assert.ok(search >= 0, 'the no-match message should stay')
+ assert.ok(subfolders > search, 'the sub-folder message should follow the no-match one')
+ assert.ok(emptyFolder > subfolders, 'the plain empty message should be the last resort')
+ assert.match(source, /v-else-if="folderEmptyState === 'subfolders'"/)
+ assert.match(source, /emptyFolderWithSubfolders', \{ count: folderSubfolderDocumentCount \}/)
+ assert.match(source, /v-else-if="folderEmptyState === 'folder'"/)
+})
diff --git a/frontend/src/views/knowledge/components/DocumentCardView.vue b/frontend/src/views/knowledge/components/DocumentCardView.vue
index 717975c69..92d077940 100644
--- a/frontend/src/views/knowledge/components/DocumentCardView.vue
+++ b/frontend/src/views/knowledge/components/DocumentCardView.vue
@@ -9,6 +9,7 @@ import DocumentActionMenu from './DocumentActionMenu.vue';
import FolderPickerMenu, { type FolderOption } from './FolderPickerMenu.vue';
import KnowledgeProcessingTimeline from '@/components/knowledge-processing-timeline.vue';
import { shownStall } from '@/utils/knowledgeProcessingStall';
+import type { FolderEntry } from '../folderTree';
interface KnowledgeCard {
id: string;
@@ -47,6 +48,12 @@ const props = defineProps<{
traceAvailableById: Record<string, boolean>;
/** Every folder of the knowledge base, for the "move to folder" picker. */
folderOptions?: FolderOption[];
+ /**
+ * Direct sub-folders of the folder being browsed. They lead the grid, the way
+ * a file manager shows folders before files. Filtering searches the subtree
+ * for documents, so the caller passes an empty list.
+ */
+ subFolders?: FolderEntry[];
/**
* Replace the updated-at line with the card's folder. Only meaningful when
* the grid spans several folders, i.e. while filtering.
@@ -78,6 +85,7 @@ const emit = defineEmits<{
const { t } = useI18n();
const tagEditorId = ref<string | null>(null);
+const subFolderCards = computed(() => props.subFolders || []);
const cardSummaries = computed(() => new Map(props.items.map(item => [item.id, formatReferenceSnippet(item.description)])));
// Which row's action popup is currently showing the folder picker. Kept local so
@@ -328,6 +336,33 @@ const handleAction = (action: 'download' | 'edit' | 'view-trace' | 'reparse' | '
<div class="doc-card-view">
<div class="doc-card-list doc-card-list-animated">
+ <div
+ v-for="folder in subFolderCards"
+ :key="`folder:${folder.path}`"
+ class="knowledge-card folder-card"
+ :data-folder-path="folder.path"
+ role="button"
+ tabindex="0"
+ @click="onOpenFolder(folder.path)"
+ @keydown.enter="onOpenFolder(folder.path)"
+ >
+ <div class="card-content">
+ <div class="card-content-nav">
+ <div class="card-file-icon folder-card-icon">
+ <t-icon name="folder" size="28px" />
+ </div>
+ <span class="card-content-title folder-card-title" :title="folder.path">{{ folder.name }}</span>
+ </div>
+ <div class="card-preview">
+ <div class="card-content-txt folder-card-count"
+ :title="t('knowledgeBase.folderTree.countHint', { direct: folder.document_count, total: folder.total_count })">
+ <t-icon name="file" size="12px" />
+ <span>{{ t('knowledgeBase.folderTree.folderCardCount', { count: folder.total_count }) }}</span>
+ </div>
+ </div>
+ </div>
+ </div>
+
<div
class="knowledge-card"
:class="{ 'is-selected': selectedIds.has(item.id), 'batch-mode': batchMode }"
@@ -792,6 +827,25 @@ const handleAction = (action: 'download' | 'edit' | 'view-trace' | 'reparse' | '
span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.t-icon { flex-shrink: 0; }
}
+
+ /* A folder card uses the same shell as a document card, so the grid rhythm
+ and the hover treatment stay identical; only its body is folder-specific. */
+ &.folder-card {
+ .folder-card-icon {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--td-warning-color);
+ }
+ .folder-card-title { cursor: pointer; }
+ .folder-card-count {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ color: var(--td-text-color-placeholder);
+ .t-icon { flex-shrink: 0; }
+ }
+ }
}
.card-tags {
diff --git a/frontend/src/views/knowledge/components/DocumentFolderEntries.test.ts b/frontend/src/views/knowledge/components/DocumentFolderEntries.test.ts
new file mode 100644
index 000000000..4abe0b7e1
--- /dev/null
+++ b/frontend/src/views/knowledge/components/DocumentFolderEntries.test.ts
@@ -0,0 +1,305 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import { compileScript, parse } from '@vue/compiler-sfc'
+import ts from 'typescript'
+import { runInNewContext } from 'node:vm'
+import * as vue from 'vue'
+import * as vueI18n from 'vue-i18n'
+import { createI18n } from 'vue-i18n'
+import enUS from '../../../i18n/locales/en-US'
+import * as files from '../../../utils/files.ts'
+import * as referenceSources from '../../../utils/referenceSources.ts'
+import * as processingStall from '../../../utils/knowledgeProcessingStall.ts'
+
+/**
+ * The document list and card grid are rendered for real here: the SFC is
+ * compiled with its template inlined and mounted on a tiny host renderer. The
+ * host tree is enough to assert row order and to click a row, which source
+ * regexes alone cannot do.
+ */
+
+type HostNode = {
+ kind: 'element' | 'text' | 'comment'
+ tag?: unknown
+ text?: string
+ props: Record<string, any>
+ children: HostNode[]
+ parent: HostNode | null
+ style?: Record<string, string>
+}
+
+function hostElement(tag: unknown): HostNode {
+ return { kind: 'element', tag, text: '', props: {}, children: [], parent: null, style: {} } as HostNode
+}
+
+const noopComponent = vue.defineComponent({ name: 'Stub', setup: () => () => null })
+
+function evaluateModule(source: string, dependencies: Record<string, unknown>): any {
+ const exports: any = {}
+ const teleportTarget = hostElement('teleport-target')
+ const fakeDocument = {
+ querySelector: () => teleportTarget,
+ createElement: () => hostElement('detached'),
+ body: teleportTarget,
+ }
+ runInNewContext(
+ ts.transpileModule(source, {
+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
+ }).outputText,
+ {
+ exports,
+ console,
+ Set,
+ document: fakeDocument,
+ require(name: string) {
+ if (name in dependencies) return dependencies[name]
+ throw new Error(`Unexpected dependency: ${name}`)
+ },
+ },
+ )
+ return exports
+}
+
+const componentCache = new Map<string, any>()
+
+function loadView(file: URL, extraDependencies: Record<string, unknown> = {}): any {
+ const key = file.pathname
+ const cached = componentCache.get(key)
+ if (cached) return cached
+ const { descriptor } = parse(readFileSync(file, 'utf8'), { filename: file.pathname })
+ const script = compileScript(descriptor, { id: `folder-entry-${key}`, inlineTemplate: true }).content
+ const module = evaluateModule(script, {
+ vue,
+ 'vue-i18n': vueI18n,
+ '@/utils/files': files,
+ '@/utils/referenceSources': referenceSources,
+ '@/utils/knowledgeProcessingStall': processingStall,
+ './KnowledgeTagPopover.vue': noopComponent,
+ './DocumentFileIcon.vue': noopComponent,
+ './DocumentActionMenu.vue': noopComponent,
+ './FolderPickerMenu.vue': noopComponent,
+ '@/components/knowledge-processing-timeline.vue': noopComponent,
+ ...extraDependencies,
+ })
+ componentCache.set(key, module.default)
+ return module.default
+}
+
+function hostRenderer() {
+ const teleportTarget = hostElement('teleport-target')
+ return vue.createRenderer<HostNode, HostNode>({
+ querySelector: () => teleportTarget,
+ createElement: (tag) => hostElement(tag),
+ insert(child, parent, anchor) {
+ child.parent = parent
+ const index = anchor ? parent.children.indexOf(anchor) : -1
+ if (index >= 0) parent.children.splice(index, 0, child)
+ else parent.children.push(child)
+ },
+ remove(child) {
+ const parent = child.parent
+ if (!parent) return
+ const index = parent.children.indexOf(child)
+ if (index >= 0) parent.children.splice(index, 1)
+ },
+ createText: (text) => ({ kind: 'text', text, props: {}, children: [], parent: null }),
+ createComment: (text) => ({ kind: 'comment', text, props: {}, children: [], parent: null }),
+ setText(node, text) {
+ node.text = text
+ },
+ setElementText(node, text) {
+ node.children = [{ kind: 'text', text, props: {}, children: [], parent: node }]
+ },
+ patchProp(el, key, _previous, next) {
+ el.props[key] = next
+ },
+ parentNode: (node) => node.parent,
+ nextSibling: (node) => {
+ const parent = node.parent
+ if (!parent) return null
+ const index = parent.children.indexOf(node)
+ return parent.children[index + 1] ?? null
+ },
+ })
+}
+
+function mountView(file: URL, props: Record<string, unknown>) {
+ const renderer = hostRenderer()
+ const app = renderer.createApp(loadView(file), {
+ canEdit: false,
+ canDownload: false,
+ canMutateKnowledge: false,
+ moveMenuMode: 'normal',
+ moveTargetKbs: [],
+ moveTargetsLoading: false,
+ moveSelectedTargetName: '',
+ moveMode: 'reuse_vectors',
+ moveSubmitting: false,
+ ...props,
+ } as any)
+ app.use(createI18n({ legacy: false, locale: 'en-US', messages: { 'en-US': enUS } }))
+ for (const name of [
+ 't-icon',
+ 't-checkbox',
+ 't-popup',
+ 't-tag',
+ 't-button',
+ 't-radio',
+ 't-loading',
+ 't-tooltip',
+ 't-skeleton',
+ 't-input',
+ ]) {
+ app.component(
+ name,
+ vue.defineComponent({ name, setup: (_, { slots }) => () => vue.h('span', slots.default?.()) }),
+ )
+ }
+ const root = hostElement('root')
+ const vm = app.mount(root) as any
+ return {
+ root,
+ vm,
+ unmount: () => app.unmount(),
+ }
+}
+
+function allElements(node: HostNode): HostNode[] {
+ const elements: HostNode[] = []
+ const walk = (current: HostNode) => {
+ if (current.kind === 'element') elements.push(current)
+ current.children.forEach(walk)
+ }
+ walk(node)
+ return elements
+}
+
+function classesOf(node: HostNode): string[] {
+ return String(node.props.class ?? '').split(/\s+/).filter(Boolean)
+}
+
+function textOf(node: HostNode): string {
+ if (node.kind === 'text') return node.text ?? ''
+ return node.children.map(textOf).join('')
+}
+
+const folder = {
+ path: '培训材料库/2024使用培训视频',
+ name: '2024使用培训视频',
+ document_count: 1,
+ total_count: 1,
+}
+
+const documents = [
+ { id: 'doc-1', file_name: '天诛渗透攻防平台用户手册V202403', parse_status: 'completed', file_type: 'pdf' },
+ { id: 'doc-2', file_name: '【使用必看】天诛2024新版本', parse_status: 'completed', file_type: 'pdf' },
+]
+
+function mountList(overrides: Record<string, unknown> = {}) {
+ return mountView(new URL('./DocumentListView.vue', import.meta.url), {
+ items: documents,
+ subFolders: [folder],
+ kbId: 'kb',
+ selectedIds: new Set<string>(),
+ traceVisibleIds: {},
+ ...overrides,
+ })
+}
+
+function mountCards(overrides: Record<string, unknown> = {}) {
+ return mountView(new URL('./DocumentCardView.vue', import.meta.url), {
+ items: documents,
+ subFolders: [folder],
+ kbId: 'kb',
+ selectedIds: new Set<string>(),
+ batchMode: false,
+ traceAvailableById: {},
+ ...overrides,
+ })
+}
+
+test('the list renders one folder row before the document rows', () => {
+ const opened: string[] = []
+ const view = mountList({ onOpenFolder: (path: string) => opened.push(path) })
+ try {
+ const rows = allElements(view.root).filter((element) => classesOf(element).includes('doc-list-row'))
+ const folderRows = rows.filter((row) => row.props['data-folder-path'] !== undefined)
+ const documentRows = rows.filter((row) => row.props['data-folder-path'] === undefined)
+
+ assert.equal(folderRows.length, 1)
+ assert.equal(documentRows.length, 2)
+ assert.ok(rows.indexOf(folderRows[0]) < rows.indexOf(documentRows[0]), 'folder row comes first')
+ assert.equal(folderRows[0].props['data-folder-path'], folder.path)
+ assert.match(textOf(folderRows[0]), /2024使用培训视频/)
+ // The folder takes no part in batch selection: its checkbox cell stays empty.
+ assert.equal(
+ allElements(folderRows[0]).filter((element) => classesOf(element).includes('doc-list-check')).length,
+ 0,
+ )
+
+ folderRows[0].props.onClick({ stopPropagation() {} })
+ assert.deepEqual(opened, [folder.path])
+ } finally {
+ view.unmount()
+ }
+})
+
+test('the card grid renders one folder card before the document cards', () => {
+ const opened: string[] = []
+ const view = mountCards({ onOpenFolder: (path: string) => opened.push(path) })
+ try {
+ const cards = allElements(view.root).filter((element) => classesOf(element).includes('knowledge-card'))
+ const folderCards = cards.filter((card) => card.props['data-folder-path'] !== undefined)
+ const documentCards = cards.filter((card) => card.props['data-folder-path'] === undefined)
+
+ assert.equal(folderCards.length, 1)
+ assert.equal(documentCards.length, 2)
+ assert.ok(cards.indexOf(folderCards[0]) < cards.indexOf(documentCards[0]), 'folder card comes first')
+ assert.equal(folderCards[0].props['data-folder-path'], folder.path)
+ assert.match(textOf(folderCards[0]), /2024使用培训视频/)
+
+ folderCards[0].props.onClick({ stopPropagation() {} })
+ assert.deepEqual(opened, [folder.path])
+ } finally {
+ view.unmount()
+ }
+})
+
+test('no folder rows or cards are rendered when the caller filters them out', () => {
+ const list = mountList({ subFolders: [] })
+ try {
+ const rows = allElements(list.root).filter((element) => classesOf(element).includes('doc-list-row'))
+ assert.equal(rows.filter((row) => row.props['data-folder-path'] !== undefined).length, 0)
+ assert.equal(rows.length, 2)
+ } finally {
+ list.unmount()
+ }
+
+ const cards = mountCards({ subFolders: [] })
+ try {
+ const cardElements = allElements(cards.root).filter((element) => classesOf(element).includes('knowledge-card'))
+ assert.equal(cardElements.filter((card) => card.props['data-folder-path'] !== undefined).length, 0)
+ assert.equal(cardElements.length, 2)
+ } finally {
+ cards.unmount()
+ }
+})
+
+test('an absent folder list renders no folder rows and does not crash', () => {
+ const list = mountList({ subFolders: undefined })
+ try {
+ const rows = allElements(list.root).filter((element) => classesOf(element).includes('doc-list-row'))
+ assert.equal(rows.length, 2)
+ } finally {
+ list.unmount()
+ }
+
+ const cards = mountCards({ subFolders: undefined })
+ try {
+ const cardElements = allElements(cards.root).filter((element) => classesOf(element).includes('knowledge-card'))
+ assert.equal(cardElements.length, 2)
+ } finally {
+ cards.unmount()
+ }
+})
diff --git a/frontend/src/views/knowledge/components/DocumentListView.vue b/frontend/src/views/knowledge/components/DocumentListView.vue
index 1c03f32e4..a21681689 100644
--- a/frontend/src/views/knowledge/components/DocumentListView.vue
+++ b/frontend/src/views/knowledge/components/DocumentListView.vue
@@ -7,6 +7,7 @@ import DocumentFileIcon from './DocumentFileIcon.vue';
import DocumentActionMenu from './DocumentActionMenu.vue';
import FolderPickerMenu, { type FolderOption } from './FolderPickerMenu.vue';
import { shownStall } from '@/utils/knowledgeProcessingStall';
+import type { FolderEntry } from '../folderTree';
interface Tag {
id: string;
@@ -45,6 +46,12 @@ const props = defineProps<{
loading?: boolean;
/** Every folder of the knowledge base, for the "move to folder" picker. */
folderOptions?: FolderOption[];
+ /**
+ * Direct sub-folders of the folder being browsed. They are listed ahead of
+ * the documents, the way a file manager shows folders before files. Filtering
+ * searches the subtree for documents, so the caller passes an empty list.
+ */
+ subFolders?: FolderEntry[];
/**
* Show each row's folder under its name. Only useful when the list spans
* several folders, i.e. while filtering; inside one folder the path would be
@@ -79,6 +86,8 @@ const emit = defineEmits<{
const { t } = useI18n();
const tagEditorId = ref<string | null>(null);
+const subFolderRows = computed(() => props.subFolders || []);
+const openFolder = (folder: FolderEntry) => emit('open-folder', folder.path);
const formatTime = (time?: string) => {
if (!time) return '--';
@@ -278,6 +287,28 @@ const handleAction = (action: 'download' | 'edit' | 'reparse' | 'cancel-parse' |
</div>
<div class="doc-list-body" role="rowgroup">
+ <div v-for="folder in subFolderRows" :key="`folder:${folder.path}`" class="doc-list-row folder-row"
+ :data-folder-path="folder.path" role="row" @click="openFolder(folder)">
+ <!-- Folders are navigation entries, not documents: no batch checkbox. -->
+ <div class="cell cell-check" role="cell"></div>
+
+ <div class="cell cell-name" role="cell">
+ <span class="folder-row-icon" aria-hidden="true">
+ <t-icon name="folder" size="26px" />
+ </span>
+ <div class="row-file-text">
+ <div class="row-title-line">
+ <button type="button" class="row-file-name" :title="folder.path"
+ @click.stop="openFolder(folder)">{{ folder.name }}</button>
+ </div>
+ </div>
+ </div>
+
+ <div class="cell cell-tags" role="cell"></div>
+ <div class="cell cell-status" role="cell"></div>
+ <div class="cell cell-actions" role="cell"></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)">
@@ -545,6 +576,22 @@ const handleAction = (action: 'download' | 'edit' | 'reparse' | 'cancel-parse' |
}
}
+/* A folder is an entry in the same grid as a document, so every column stays
+ aligned; only the cells a folder has no value for stay empty. */
+.folder-row {
+ min-height: 56px;
+}
+
+.folder-row-icon {
+ flex: 0 0 32px;
+ width: 32px;
+ height: 38px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--td-warning-color);
+}
+
.cell {
display: flex;
align-items: center;
diff --git a/frontend/src/views/knowledge/components/KbFolderTree.test.ts b/frontend/src/views/knowledge/components/KbFolderTree.test.ts
index 5f35aabac..12f14bcca 100644
--- a/frontend/src/views/knowledge/components/KbFolderTree.test.ts
+++ b/frontend/src/views/knowledge/components/KbFolderTree.test.ts
@@ -1,6 +1,13 @@
import assert from 'node:assert/strict'
-import test from 'node:test'
+import test, { after, before } from 'node:test'
import { readFileSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import { createServer, type ViteDevServer } from 'vite'
+import vue from '@vitejs/plugin-vue'
+import { createSSRApp, defineComponent, h, type Component } from 'vue'
+import { renderToString } from 'vue/server-renderer'
+import { createI18n } from 'vue-i18n'
+import en from '../../../i18n/locales/en-US'
const tree = readFileSync(new URL('./KbFolderTree.vue', import.meta.url), 'utf8')
const batchBar = readFileSync(new URL('./DocumentBatchBar.vue', import.meta.url), 'utf8')
@@ -52,3 +59,81 @@ test('folder navigation cancels stale card hover popovers', () => {
assert.match(cardView, /const onOpenFolder = \(path: string\)[\s\S]*?dismissCardPopover\(\)[\s\S]*?emit\('open-folder', path\)/)
assert.match(cardView, /@click\.stop="onOpenFolder\(item\.folder_path\)"/)
})
+
+// The counts the sidebar shows come from the connector-produced folder tree, so
+// they have to be rendered for real: a folder whose documents all sit in
+// sub-folders used to count 0 here, which read as "empty". The rendered HTML is
+// the assertion, not the template source, so a wrong binding cannot pass.
+let server: ViteDevServer
+let KbFolderTree: Component
+before(async () => {
+ server = await createServer({
+ configFile: false,
+ optimizeDeps: { noDiscovery: true, entries: [] },
+ plugins: [vue()],
+ resolve: { alias: { '@': fileURLToPath(new URL('../../../', import.meta.url)) } },
+ server: { middlewareMode: true },
+ appType: 'custom',
+ })
+ KbFolderTree = (await server.ssrLoadModule('/src/views/knowledge/components/KbFolderTree.vue')).default
+})
+after(async () => { await server?.close() })
+
+// Mirrors the deployed DingTalk-synced knowledge base: multi-level folders, so
+// the direct document count of a parent is 0 while its subtree holds 5.
+const folderTree = {
+ root_document_count: 3,
+ total_document_count: 17,
+ folders: [
+ { path: '培训材料库', name: '培训材料库', document_count: 3, total_count: 17 },
+ {
+ path: '天诛渗透攻防',
+ name: '天诛渗透攻防',
+ document_count: 0,
+ total_count: 5,
+ children: [
+ { path: '天诛渗透攻防/FAQ', name: 'FAQ', document_count: 2, total_count: 2 },
+ { path: '天诛渗透攻防/售后', name: '售后', document_count: 2, total_count: 2 },
+ { path: '天诛渗透攻防/2024使用培训视频', name: '2024使用培训视频', document_count: 1, total_count: 1 },
+ ],
+ },
+ ],
+}
+
+async function renderTree(props: Record<string, unknown>): Promise<string> {
+ const app = createSSRApp({ render: () => h(KbFolderTree, props) })
+ app.use(createI18n({ legacy: false, locale: 'en-US', messages: { 'en-US': en } }))
+ // The TDesign widgets are registered globally by the app; empty shells keep
+ // the rendered row markup readable here.
+ for (const name of ['t-icon', 't-tooltip', 't-popup', 't-skeleton']) {
+ app.component(name, defineComponent({ setup: (_, { slots }) => () => h('span', slots.default?.()) }))
+ }
+ return renderToString(app)
+}
+
+/** Markup of one rendered row, isolated from the rows around it. */
+function rowHtml(html: string, marker: string): string {
+ const starts = [...html.matchAll(/<div class="[^"]*kb-folder-row[^"]*"/g)].map((match) => match.index!)
+ const row = starts
+ .map((start, index) => html.slice(start, starts[index + 1]))
+ .find((markup) => markup.includes(marker))
+ assert.ok(row, `row ${marker} should render`)
+ return row
+}
+
+test('a folder row shows the recursive document count', async () => {
+ const html = await renderTree({ tree: folderTree, selectedPath: '天诛渗透攻防' })
+ const row = rowHtml(html, 'title="天诛渗透攻防"')
+ assert.match(row, /kb-folder-row__count[^>]*>5</)
+ assert.doesNotMatch(row, /kb-folder-row__count[^>]*>0</)
+ // The tooltip keeps the direct/recursive split visible, so the number is not
+ // mistaken for the folder's own contents.
+ assert.match(row, /0 documents in this folder; 5 including subfolders/)
+})
+
+test('the root row shows the knowledge base total, not the root-level count', async () => {
+ const html = await renderTree({ tree: folderTree, selectedPath: '' })
+ const row = rowHtml(html, 'is-root')
+ assert.match(row, /kb-folder-row__count[^>]*>17</)
+ assert.doesNotMatch(row, /kb-folder-row__count[^>]*>3</)
+})
diff --git a/frontend/src/views/knowledge/components/KbFolderTree.vue b/frontend/src/views/knowledge/components/KbFolderTree.vue
index bda0a0d08..4b310458a 100644
--- a/frontend/src/views/knowledge/components/KbFolderTree.vue
+++ b/frontend/src/views/knowledge/components/KbFolderTree.vue
@@ -95,7 +95,7 @@
<span class="kb-folder-row__trailing">
<span class="kb-folder-row__count"
:title="t('knowledgeBase.folderTree.countHint', { direct: row.documentCount, total: row.totalCount })">
- {{ row.documentCount }}
+ {{ row.totalCount }}
</span>
<t-popup
v-if="canEdit && row.kind === 'folder'"
diff --git a/frontend/src/views/knowledge/folderTree.test.ts b/frontend/src/views/knowledge/folderTree.test.ts
index eae26f4e1..545ec773f 100644
--- a/frontend/src/views/knowledge/folderTree.test.ts
+++ b/frontend/src/views/knowledge/folderTree.test.ts
@@ -8,6 +8,7 @@ import {
childFolders,
folderAncestorPaths,
folderBreadcrumbs,
+ folderDocumentCounts,
folderOptionFromPath,
folderPathExists,
isFilteringDocuments,
@@ -156,6 +157,46 @@ test('tree rows carry the recursive total, which is how much a folder contains',
assert.equal(handbook.documentCount, 1)
})
+// The breadcrumb and the empty state both report the folder's size, which is the
+// recursive total once connector-produced trees nest. `direct` stays available so
+// a caller can tell an empty folder from one whose documents live below it.
+test('folder counts separate a folder from its whole subtree', () => {
+ assert.deepEqual(folderDocumentCounts(tree, ROOT_FOLDER_PATH), { direct: 2, total: 7 })
+ assert.deepEqual(folderDocumentCounts(tree, 'handbook'), { direct: 1, total: 4 })
+ assert.deepEqual(folderDocumentCounts(tree, 'handbook/onboarding'), { direct: 2, total: 3 })
+ assert.deepEqual(folderDocumentCounts(tree, 'handbook/onboarding/day-one'), { direct: 1, total: 1 })
+
+ // A path that is no longer in the tree and an unloaded tree both leave the
+ // caller to fall back to the document list it did load.
+ assert.equal(folderDocumentCounts(tree, 'handbook/gone'), null)
+ assert.equal(folderDocumentCounts(null, ROOT_FOLDER_PATH), null)
+ assert.equal(folderDocumentCounts(null, 'handbook'), null)
+})
+
+// The regression this guards: the deployed DingTalk tree has a folder whose
+// documents all sit one level down, so its direct count is 0. Reading that as
+// the folder's size made the sidebar and the empty state claim it was empty.
+test('a folder that only groups sub-folders still reports a total', () => {
+ const grouped = {
+ root_document_count: 0,
+ total_document_count: 5,
+ folders: [{
+ path: '天诛渗透攻防',
+ name: '天诛渗透攻防',
+ document_count: 0,
+ total_count: 5,
+ children: [
+ { path: '天诛渗透攻防/FAQ', name: 'FAQ', document_count: 2, total_count: 2 },
+ { path: '天诛渗透攻防/售后', name: '售后', document_count: 2, total_count: 2 },
+ { path: '天诛渗透攻防/2024使用培训视频', name: '2024使用培训视频', document_count: 1, total_count: 1 },
+ ],
+ }],
+ }
+ assert.deepEqual(folderDocumentCounts(grouped, '天诛渗透攻防'), { direct: 0, total: 5 })
+ const counts = folderDocumentCounts(grouped, '天诛渗透攻防')!
+ assert.equal(counts.total - counts.direct, 5, 'all five documents are below the folder')
+})
+
// 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.
diff --git a/frontend/src/views/knowledge/folderTree.ts b/frontend/src/views/knowledge/folderTree.ts
index 426ee6858..1f1ec71f9 100644
--- a/frontend/src/views/knowledge/folderTree.ts
+++ b/frontend/src/views/knowledge/folderTree.ts
@@ -23,6 +23,15 @@ export type UploadFileLike = {
webkitRelativePath?: string
}
+/**
+ * A folder listed as a row or card in the document list. It is the subset of a
+ * tree node the list needs: the path to navigate to and the two counts.
+ */
+export type FolderEntry = Pick<
+ KnowledgeFolderNode,
+ 'path' | 'name' | 'document_count' | 'total_count'
+>
+
/**
* One rendered row of the flattened tree. The root row carries the knowledge
* base totals; the component supplies its label.
@@ -147,9 +156,22 @@ export function buildFolderRows(
return [root, ...flattenFolders(folders, expanded, 1)]
}
+/** Depth-first lookup of one folder node anywhere in the tree. */
+function findFolderNode(
+ folders: KnowledgeFolderNode[],
+ path: string,
+): KnowledgeFolderNode | undefined {
+ for (const node of folders) {
+ if (node.path === path) return node
+ const found = findFolderNode(node.children || [], path)
+ if (found) return found
+ }
+ return undefined
+}
+
/**
- * 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.
+ * Direct sub-folders of a folder: the rows the sidebar tree renders underneath
+ * it. The root's children are the top-level folders.
*/
export function childFolders(
tree: KnowledgeFolderTree | null,
@@ -157,15 +179,29 @@ export function childFolders(
): 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 findFolderNode(folders, path)?.children ?? []
+}
+
+/**
+ * How many documents a folder holds: the ones stored directly in it, and the
+ * ones in its whole subtree. Returns null when the tree is unavailable or the
+ * path is not in it, so callers can fall back to the loaded document list.
+ *
+ * The two numbers differ as soon as folders nest: a parent that only groups
+ * sub-folders has 0 direct documents but a non-zero total, and showing the
+ * direct count there reads as "empty".
+ */
+export function folderDocumentCounts(
+ tree: KnowledgeFolderTree | null,
+ path: string,
+): { direct: number; total: number } | null {
+ if (!tree) return null
+ if (path === ROOT_FOLDER_PATH) {
+ return { direct: tree.root_document_count ?? 0, total: tree.total_document_count ?? 0 }
}
- return find(folders)?.children ?? []
+ const node = findFolderNode(tree.folders ?? [], path)
+ if (!node) return null
+ return { direct: node.document_count ?? 0, total: node.total_count ?? 0 }
}
/**