Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat: Implement knowledge tag management and batch updates for FAQ entries
wizardchenfdf5d9d78146
diff --git a/frontend/src/api/knowledge-base/index.ts b/frontend/src/api/knowledge-base/index.tsindex 5cc7470b9..90fd99793 100644--- a/frontend/src/api/knowledge-base/index.ts+++ b/frontend/src/api/knowledge-base/index.ts@@ -90,6 +90,38 @@ export function getChunkByIdOnly(chunkId: string) {return get(`/api/v1/chunks/by-id/${chunkId}`);}+export function listKnowledgeTags(kbId: string) {+ return get(`/api/v1/knowledge-bases/${kbId}/tags`);+}++export function createKnowledgeBaseTag(+ kbId: string,+ data: { name: string; color?: string; sort_order?: number },+) {+ return post(`/api/v1/knowledge-bases/${kbId}/tags`, data);+}++export function updateKnowledgeBaseTag(+ kbId: string,+ tagId: string,+ data: { name?: string; color?: string; sort_order?: number },+) {+ return put(`/api/v1/knowledge-bases/${kbId}/tags/${tagId}`, data);+}++export function deleteKnowledgeBaseTag(kbId: string, tagId: string, params?: { force?: boolean }) {+ const forceQuery = params?.force ? '?force=true' : '';+ return del(`/api/v1/knowledge-bases/${kbId}/tags/${tagId}${forceQuery}`);+}++export function updateKnowledgeTagBatch(data: { updates: Record<string, string | null> }) {+ return put(`/api/v1/knowledge/tags`, data);+}++export function updateFAQEntryTagBatch(kbId: string, data: { updates: Record<string, string | null> }) {+ return put(`/api/v1/knowledge-bases/${kbId}/faq/entries/tags`, data);+}+const buildQuery = (params?: Record<string, any>) => {if (!params) return '';const query = new URLSearchParams();@@ -114,6 +146,10 @@ export function updateFAQEntry(kbId: string, entryId: string, data: any) {return put(`/api/v1/knowledge-bases/${kbId}/faq/entries/${entryId}`, data);}+export function updateFAQEntryStatusBatch(kbId: string, data: { updates: Record<string, boolean> }) {+ return put(`/api/v1/knowledge-bases/${kbId}/faq/entries/status`, data);+}+export function deleteFAQEntries(kbId: string, ids: string[]) {return del(`/api/v1/knowledge-bases/${kbId}/faq/entries`, { ids });}diff --git a/frontend/src/components/doc-content.vue b/frontend/src/components/doc-content.vueindex a93c6b7e0..cfc823672 100644--- a/frontend/src/components/doc-content.vue+++ b/frontend/src/components/doc-content.vue@@ -3,7 +3,6 @@ import { marked } from "marked";import { onMounted, ref, nextTick, onUnmounted, onUpdated, watch } from "vue";import { downKnowledgeDetails } from "@/api/knowledge-base/index";import { MessagePlugin } from "tdesign-vue-next";-import picturePreview from '@/components/picture-preview.vue';import { sanitizeHTML, safeMarkdownToHTML, createSafeImage, isValidImageURL } from '@/utils/security';import { useI18n } from 'vue-i18n';@@ -19,8 +18,6 @@ let doc = null;let down = ref()let mdContentWrap = ref()let url = ref('')-let reviewUrl = ref('')-let reviewImg = ref(false)onMounted(() => {nextTick(() => {doc = document.getElementsByClassName('t-drawer__body')[0]@@ -61,10 +58,6 @@ watch(() => props.details.md, (newVal) => {const images = mdContentWrap.value.querySelectorAll('img.markdown-image');if (images) {images.forEach(async item => {- item.addEventListener('click', function (event) {- reviewUrl.value = event.target.src;- reviewImg.value = true- })const isValid = await checkImage(item.src);if (!isValid) {item.remove();@@ -103,10 +96,6 @@ const processMarkdown = (markdownText) => {return sanitizedHTML;};-const closePreImg = () => {- reviewImg.value = false- reviewUrl.value = '';-}const handleClose = () => {emit("closeDoc", false);doc.scrollTop = 0;@@ -179,7 +168,6 @@ const handleDetailsScroll = () => {<t-button theme="default" @click="handleClose">{{ $t('common.cancel') }}</t-button></template></t-drawer>- <picturePreview :reviewImg="reviewImg" :reviewUrl="reviewUrl" @closePreImg="closePreImg"></picturePreview></div></template><style scoped lang="less">diff --git a/frontend/src/hooks/useKnowledgeBase.ts b/frontend/src/hooks/useKnowledgeBase.tsindex e73e08291..3c112927c 100644--- a/frontend/src/hooks/useKnowledgeBase.ts+++ b/frontend/src/hooks/useKnowledgeBase.ts@@ -24,7 +24,10 @@ export default function (knowledgeBaseId?: string) {id: "",total: 0});- const getKnowled = (query = { page: 1, page_size: 35 }, kbId?: string) => {+ const getKnowled = (+ query: { page: number; page_size: number; tag_id?: string } = { page: 1, page_size: 35 },+ kbId?: string,+ ) => {const targetKbId = kbId || knowledgeBaseId;if (!targetKbId) return;diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex d601dd051..692e584bd 100644--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -24,6 +24,27 @@ export default {description: 'Description',files: 'Files',settings: 'Settings',+ documentCategoryTitle: 'Document Categories',+ tagUpdateSuccess: 'Tag updated successfully',+ category: 'Category',+ faqCategoryTitle: 'FAQ Categories',+ untagged: 'Uncategorized',+ tagSearchTooltip: 'Search tags',+ tagCreateAction: 'Create tag',+ tagSearchPlaceholder: 'Type to filter tags',+ tagNamePlaceholder: 'Enter tag name',+ tagNameRequired: 'Please provide a tag name',+ tagCreateSuccess: 'Tag created',+ tagEditSuccess: 'Tag updated',+ tagDeleteTitle: 'Delete tag',+ tagDeleteDesc: 'Delete tag "{name}"? Related FAQs will become untagged.',+ tagDeleteSuccess: 'Tag deleted',+ tagEditAction: 'Rename',+ tagDeleteAction: 'Delete',+ tagEmptyResult: 'No matching tags',+ tagLabel: 'Category',+ tagPlaceholder: 'Please select a category',+ noTags: 'No categories',upload: 'Upload File',uploadSuccess: 'File uploaded successfully!',uploadFailed: 'File upload failed!',@@ -730,6 +751,7 @@ export default {questionIndexModeLabel: 'Question Indexing Mode',questionIndexModeDescription: 'Combined: Standard and similar questions are indexed together. Separate: Each question is indexed independently for more precise retrieval but requires more storage.',entryGuide: 'Each FAQ entry contains a primary question, similar questions, negative examples, and multiple answers. Manage them in the FAQ knowledge base detail view.',+ tagDesc: 'Select category for FAQ entries',modes: {questionOnly: 'Questions only',questionAnswer: 'Question + answer',@@ -740,6 +762,8 @@ export default {answers: 'Answers',similarQuestions: 'Similar Questions',negativeQuestions: 'Negative Examples',+ categoryLabel: 'FAQ Category',+ categoryButton: 'Switch Category',editorCreate: 'Create FAQ Entry',editorEdit: 'Edit FAQ Entry',addAnswer: 'Add Answer',@@ -771,6 +795,15 @@ export default {matchTypeEmbedding: 'Vector Match',matchTypeKeywords: 'Keyword Match',similarityThresholdLabel: 'Similarity Threshold',+ statusEnabled: 'Enabled',+ statusDisabled: 'Disabled',+ statusEnableSuccess: 'FAQ entry enabled',+ statusDisableSuccess: 'FAQ entry disabled',+ statusUpdateFailed: 'Failed to update status',+ batchUpdateTag: 'Batch Update Category',+ batchUpdateTagTip: 'Set category for {count} selected entries',+ batchEnable: 'Batch Enable',+ batchDisable: 'Batch Disable',},faqImport: {title: 'Batch Import FAQ',diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex ab542925c..0cd96a701 100644--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -24,6 +24,27 @@ export default {description: 'Описание',files: 'Файлы',settings: 'Настройки',+ documentCategoryTitle: 'Категории документов',+ faqCategoryTitle: 'Категории FAQ',+ untagged: 'Без метки',+ tagSearchTooltip: 'Поиск тегов',+ tagUpdateSuccess: 'Тег успешно обновлен',+ category: 'Категория',+ tagCreateAction: 'Создать тег',+ tagSearchPlaceholder: 'Введите название тега',+ tagNamePlaceholder: 'Введите название тега',+ tagNameRequired: 'Пожалуйста, укажите название тега',+ tagCreateSuccess: 'Тег создан',+ tagEditSuccess: 'Тег обновлён',+ tagDeleteTitle: 'Удаление тега',+ tagDeleteDesc: 'Удалить тег «{name}»? Связанные FAQ будут без метки.',+ tagDeleteSuccess: 'Тег удалён',+ tagEditAction: 'Переименовать',+ tagDeleteAction: 'Удалить',+ tagEmptyResult: 'Подходящие теги не найдены',+ tagLabel: 'Категория',+ tagPlaceholder: 'Пожалуйста, выберите категорию',+ noTags: 'Нет категорий',upload: 'Загрузить файл',uploadSuccess: 'Файл успешно загружен!',uploadFailed: 'Ошибка загрузки файла!',@@ -820,6 +841,7 @@ export default {questionIndexModeLabel: 'Режим индексации вопросов',questionIndexModeDescription: 'Объединенная: стандартные и похожие вопросы индексируются вместе. Раздельная: каждый вопрос индексируется независимо для более точного поиска, но требует больше места.',entryGuide: 'Каждый FAQ включает основной вопрос, похожие вопросы, негативные примеры и несколько ответов. Управляйте ими в деталях FAQ-базы.',+ tagDesc: 'Выберите категорию для записей FAQ',modes: {questionOnly: 'Только вопросы',questionAnswer: 'Вопрос + ответ',@@ -830,6 +852,8 @@ export default {answers: 'Ответы',similarQuestions: 'Похожие вопросы',negativeQuestions: 'Негативные примеры',+ categoryLabel: 'Категория FAQ',+ categoryButton: 'Сменить категорию',editorCreate: 'Создать FAQ запись',editorEdit: 'Редактировать FAQ запись',addAnswer: 'Добавить ответ',@@ -861,6 +885,15 @@ export default {matchTypeEmbedding: 'Векторное совпадение',matchTypeKeywords: 'Совпадение ключевых слов',similarityThresholdLabel: 'Порог сходства',+ statusEnabled: 'Включено',+ statusDisabled: 'Выключено',+ statusEnableSuccess: 'Запись FAQ включена',+ statusDisableSuccess: 'Запись FAQ отключена',+ statusUpdateFailed: 'Не удалось обновить статус',+ batchUpdateTag: 'Пакетное обновление категории',+ batchUpdateTagTip: 'Установить категорию для {count} выбранных записей',+ batchEnable: 'Пакетное включение',+ batchDisable: 'Пакетное отключение',},faqImport: {title: 'Пакетный импорт FAQ',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 9bd99a512..9b44df21e 100644--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -24,6 +24,27 @@ export default {description: "描述",files: "文件",settings: "设置",+ documentCategoryTitle: "文档分类",+ faqCategoryTitle: "问题分类",+ untagged: "未分类",+ tagUpdateSuccess: "标签更新成功",+ tagSearchTooltip: "搜索标签",+ category: "分类",+ tagCreateAction: "新建标签",+ tagSearchPlaceholder: "输入标签名称关键字",+ tagNamePlaceholder: "请输入标签名称",+ tagNameRequired: "请先输入标签名称",+ tagCreateSuccess: "标签创建成功",+ tagEditSuccess: "标签更新成功",+ tagDeleteTitle: "删除标签",+ tagDeleteDesc: "确定删除标签“{name}”?已关联的 FAQ 将被标记为未分类",+ tagDeleteSuccess: "标签已删除",+ tagEditAction: "重命名",+ tagDeleteAction: "删除",+ tagEmptyResult: "未找到匹配的标签",+ tagLabel: "分类",+ tagPlaceholder: "请选择分类",+ noTags: "暂无分类",upload: "上传文件",uploadSuccess: "文件上传成功!",uploadFailed: "文件上传失败!",@@ -1049,6 +1070,7 @@ export default {questionIndexModeLabel: "问题索引方式",questionIndexModeDescription: "合并索引:标准问和相似问合并索引;分别索引:标准问和每个相似问独立索引,检索更精确但需要更多存储",entryGuide: "FAQ 条目由标准问、相似问、反例和多个答案组成,可在知识库详情中批量导入、编辑。",+ tagDesc: "为 FAQ 条目选择分类",modes: {questionOnly: "仅标准问/相似问",questionAnswer: "标准问 + 答案",@@ -1063,6 +1085,8 @@ export default {similarQuestionsDesc: "添加与标准问意思相同但表述不同的问题,帮助系统更好地匹配用户查询。",negativeQuestions: "反例",negativeQuestionsDesc: "添加不应匹配此答案的问题,用于排除误匹配的情况。",+ categoryLabel: "FAQ 分类",+ categoryButton: "切换分类",editorCreate: "新增 FAQ 条目",editorEdit: "编辑 FAQ 条目",addAnswer: "添加答案",@@ -1094,6 +1118,15 @@ export default {matchTypeEmbedding: "向量匹配",matchTypeKeywords: "关键词匹配",similarityThresholdLabel: "相似度阈值",+ statusEnabled: "已启用",+ statusDisabled: "已禁用",+ statusEnableSuccess: "FAQ 条目已启用",+ statusDisableSuccess: "FAQ 条目已禁用",+ statusUpdateFailed: "更新状态失败",+ batchUpdateTag: "批量分类",+ batchUpdateTagTip: "将为 {count} 个选中的条目设置分类",+ batchEnable: "批量启用",+ batchDisable: "批量禁用",},faqImport: {title: "批量导入 FAQ",diff --git a/frontend/src/views/knowledge/KnowledgeBase.vue b/frontend/src/views/knowledge/KnowledgeBase.vueindex 27fd1d462..b389fd6ba 100644--- a/frontend/src/views/knowledge/KnowledgeBase.vue+++ b/frontend/src/views/knowledge/KnowledgeBase.vue@@ -1,7 +1,7 @@<script setup lang="ts">-import { ref, onMounted, onUnmounted, watch, reactive, computed } from "vue";+import { ref, onMounted, onUnmounted, watch, reactive, computed, nextTick, type ComponentPublicInstance } from "vue";+import { MessagePlugin } from "tdesign-vue-next";import DocContent from "@/components/doc-content.vue";-import InputField from "@/components/Input-field.vue";import useKnowledgeBase from '@/hooks/useKnowledgeBase';import { useRoute, useRouter } from 'vue-router';import EmptyKnowledge from '@/components/empty-knowledge.vue';@@ -14,12 +14,16 @@ const uiStore = useUIStore();const router = useRouter();import {batchQueryKnowledge,- listKnowledgeFiles,getKnowledgeBaseById,+ listKnowledgeTags,+ updateKnowledgeTagBatch,+ createKnowledgeBaseTag,+ updateKnowledgeBaseTag,+ deleteKnowledgeBaseTag,} from "@/api/knowledge-base/index";import FAQEntryManager from './components/FAQEntryManager.vue';-import { formatStringDate } from "@/utils/index";import { useI18n } from 'vue-i18n';+import { formatStringDate } from '@/utils';const route = useRoute();const { t } = useI18n();const kbId = computed(() => (route.params as any).kbId as string || '');@@ -35,7 +39,60 @@ let knowledgeIndex = ref(-1)let knowledgeScroll = ref()let page = 1;let pageSize = 35;-const selectedTagId = ref<string | null>(null);+const selectedTagId = ref<string>("");+const tagList = ref<any[]>([]);+const tagLoading = ref(false);+const overallKnowledgeTotal = ref(0);+const tagSearchQuery = ref('');+type TagInputInstance = ComponentPublicInstance<{ focus: () => void; select: () => void }>;+const tagDropdownOptions = computed(() => {+ const options = [+ { content: t('knowledgeBase.untagged') || '未分类', value: "" },+ ...tagList.value.map((tag: any) => ({+ content: tag.name,+ value: tag.id,+ })),+ ];+ return options;+});+const tagMap = computed<Record<string, any>>(() => {+ const map: Record<string, any> = {};+ tagList.value.forEach((tag) => {+ map[tag.id] = tag;+ });+ return map;+});+const sidebarCategoryCount = computed(() => tagList.value.length + 1);+const assignedKnowledgeTotal = computed(() =>+ tagList.value.reduce((sum, tag) => sum + (tag.knowledge_count || 0), 0),+);+const untaggedKnowledgeCount = computed(() => {+ return Math.max(overallKnowledgeTotal.value - assignedKnowledgeTotal.value, 0);+});+const filteredTags = computed(() => {+ const query = tagSearchQuery.value.trim().toLowerCase();+ if (!query) return tagList.value;+ return tagList.value.filter((tag) => (tag.name || '').toLowerCase().includes(query));+});++const editingTagInputRefs = new Map<string, TagInputInstance | null>();+const setEditingTagInputRef = (el: TagInputInstance | null, tagId: string) => {+ if (el) {+ editingTagInputRefs.set(tagId, el);+ } else {+ editingTagInputRefs.delete(tagId);+ }+};+const setEditingTagInputRefByTag = (tagId: string) => (el: TagInputInstance | null) => {+ setEditingTagInputRef(el, tagId);+};+const newTagInputRef = ref<TagInputInstance | null>(null);+const creatingTag = ref(false);+const creatingTagLoading = ref(false);+const newTagName = ref('');+const editingTagId = ref<string | null>(null);+const editingTagName = ref('');+const editingTagSubmitting = ref(false);const getPageSize = () => {const viewportHeight = window.innerHeight || document.documentElement.clientHeight;const itemHeight = 174;@@ -44,45 +101,209 @@ const getPageSize = () => {}getPageSize()// 直接调用 API 获取知识库文件列表-const loadKnowledgeFiles = async (kbIdValue: string) => {+const getTagName = (tagId?: string | number) => {+ if (!tagId && tagId !== 0) return t('knowledgeBase.untagged') || '未分类';+ const key = String(tagId);+ return tagMap.value[key]?.name || (t('knowledgeBase.untagged') || '未分类');+};++const formatDocTime = (time?: string) => {+ if (!time) return '--'+ const formatted = formatStringDate(new Date(time))+ return formatted.slice(2, 16) // "YY-MM-DD HH:mm"+}++const loadKnowledgeFiles = (kbIdValue: string) => {if (!kbIdValue) return;-- try {- const result = await listKnowledgeFiles(kbIdValue, {+ getKnowled(+ {page: 1,page_size: pageSize,tag_id: selectedTagId.value || undefined,+ },+ kbIdValue,+ );+};++const loadTags = async (kbIdValue: string) => {+ if (!kbIdValue) {+ tagList.value = [];+ return;+ }+ tagLoading.value = true;+ try {+ const res: any = await listKnowledgeTags(kbIdValue);+ tagList.value = (res?.data || []).map((tag: any) => ({+ ...tag,+ id: String(tag.id),+ }));+ } catch (error) {+ console.error('Failed to load tags', error);+ } finally {+ tagLoading.value = false;+ }+};++const handleTagFilterChange = (value: string) => {+ selectedTagId.value = value;+ page = 1;+ loadKnowledgeFiles(kbId.value);+};++const handleTagRowClick = (tagId: string) => {+ const normalizedId = String(tagId);+ if (editingTagId.value && editingTagId.value !== normalizedId) {+ editingTagId.value = null;+ editingTagName.value = '';+ }+ if (creatingTag.value) {+ creatingTag.value = false;+ newTagName.value = '';+ }+ if (selectedTagId.value === normalizedId) {+ return;+ }+ handleTagFilterChange(normalizedId);+};++const handleUntaggedClick = () => {+ if (creatingTag.value) {+ creatingTag.value = false;+ newTagName.value = '';+ }+ if (editingTagId.value) {+ editingTagId.value = null;+ editingTagName.value = '';+ }+ if (selectedTagId.value === '') return;+ handleTagFilterChange('');+};++const startCreateTag = () => {+ if (!kbId.value) {+ MessagePlugin.warning(t('knowledgeEditor.messages.missingId'));+ return;+ }+ if (creatingTag.value) {+ return;+ }+ editingTagId.value = null;+ editingTagName.value = '';+ creatingTag.value = true;+ nextTick(() => {+ newTagInputRef.value?.focus?.();+ newTagInputRef.value?.select?.();+ });+};++const cancelCreateTag = () => {+ creatingTag.value = false;+ newTagName.value = '';+};++const submitCreateTag = async () => {+ if (!kbId.value) {+ MessagePlugin.warning(t('knowledgeEditor.messages.missingId'));+ return;+ }+ const name = newTagName.value.trim();+ if (!name) {+ MessagePlugin.warning(t('knowledgeBase.tagNameRequired'));+ return;+ }+ creatingTagLoading.value = true;+ try {+ await createKnowledgeBaseTag(kbId.value, { name });+ MessagePlugin.success(t('knowledgeBase.tagCreateSuccess'));+ cancelCreateTag();+ await loadTags(kbId.value);+ } catch (error: any) {+ MessagePlugin.error(error?.message || t('common.operationFailed'));+ } finally {+ creatingTagLoading.value = false;+ }+};++const startEditTag = (tag: any) => {+ creatingTag.value = false;+ newTagName.value = '';+ editingTagId.value = tag.id;+ editingTagName.value = tag.name;+ nextTick(() => {+ const inputRef = editingTagInputRefs.get(tag.id);+ inputRef?.focus?.();+ inputRef?.select?.();+ });+};++const cancelEditTag = () => {+ editingTagId.value = null;+ editingTagName.value = '';+};++const submitEditTag = async () => {+ if (!kbId.value || !editingTagId.value) {+ return;+ }+ const name = editingTagName.value.trim();+ if (!name) {+ MessagePlugin.warning(t('knowledgeBase.tagNameRequired'));+ return;+ }+ if (name === tagMap.value[editingTagId.value]?.name) {+ cancelEditTag();+ return;+ }+ editingTagSubmitting.value = true;+ try {+ await updateKnowledgeBaseTag(kbId.value, editingTagId.value, { name });+ MessagePlugin.success(t('knowledgeBase.tagEditSuccess'));+ cancelEditTag();+ await loadTags(kbId.value);+ } catch (error: any) {+ MessagePlugin.error(error?.message || t('common.operationFailed'));+ } finally {+ editingTagSubmitting.value = false;+ }+};++const confirmDeleteTag = (tag: any) => {+ if (!kbId.value) {+ MessagePlugin.warning(t('knowledgeEditor.messages.missingId'));+ return;+ }+ if (creatingTag.value) {+ cancelCreateTag();+ }+ if (editingTagId.value) {+ cancelEditTag();+ }+ const confirm = window.confirm(+ t('knowledgeBase.tagDeleteDesc', { name: tag.name }) as string,+ );+ if (!confirm) return;+ deleteKnowledgeBaseTag(kbId.value, tag.id)+ .then(() => {+ MessagePlugin.success(t('knowledgeBase.tagDeleteSuccess'));+ if (selectedTagId.value === tag.id) {+ handleTagFilterChange('');+ }+ loadTags(kbId.value);+ loadKnowledgeFiles(kbId.value);+ })+ .catch((error: any) => {+ MessagePlugin.error(error?.message || t('common.operationFailed'));});-- // 由于响应拦截器已经返回了 data,所以 result 就是响应的 data 部分- // 按照 useKnowledgeBase hook 中的方式处理- const { data, total: totalResult } = result as any;-- if (!data || !Array.isArray(data)) {- console.error('Invalid data format. Expected array, got:', typeof data, data);- return;- }-- const cardList_ = data.map((item: any) => {- const rawName = item.file_name || item.title || item.source || t('knowledgeBase.untitledDocument')- const dotIndex = rawName.lastIndexOf('.')- const displayName = dotIndex > 0 ? rawName.substring(0, dotIndex) : rawName- const fileTypeSource = item.file_type || (item.type === 'manual' ? 'MANUAL' : '')- return {- ...item,- original_file_name: item.file_name,- display_name: displayName,- file_name: displayName,- updated_at: formatStringDate(new Date(item.updated_at)),- isMore: false,- file_type: fileTypeSource ? String(fileTypeSource).toLocaleUpperCase() : '',- };- });-- cardList.value = cardList_ as any[];- total.value = totalResult;- } catch (err) {- console.error('Failed to load knowledge files:', err);+};++const handleKnowledgeTagChange = async (knowledgeId: string, tagValue: string) => {+ try {+ await updateKnowledgeTagBatch({ updates: { [knowledgeId]: tagValue || null } });+ MessagePlugin.success(t('knowledgeBase.tagUpdateSuccess') || '分类已更新');+ loadKnowledgeFiles(kbId.value);+ loadTags(kbId.value);+ } catch (error: any) {+ MessagePlugin.error(error?.message || t('common.operationFailed'));}};@@ -95,13 +316,16 @@ const loadKnowledgeBaseInfo = async (targetKbId: string) => {try {const res: any = await getKnowledgeBaseById(targetKbId);kbInfo.value = res?.data || null;+ selectedTagId.value = "";if (!isFAQ.value) {- getKnowled({ page: 1, page_size: pageSize }, targetKbId);+ getKnowled({ page: 1, page_size: pageSize, tag_id: undefined }, targetKbId);loadKnowledgeFiles(targetKbId);} else {cardList.value = [];total.value = 0;}+ loadTags(targetKbId);+ overallKnowledgeTotal.value = total.value;} catch (error) {console.error('Failed to load knowledge base info:', error);kbInfo.value = null;@@ -117,6 +341,19 @@ watch(() => kbId.value, (newKbId, oldKbId) => {}}, { immediate: false });+watch(selectedTagId, (newVal, oldVal) => {+ if (oldVal === undefined) return+ if (newVal !== oldVal && kbId.value) {+ loadKnowledgeFiles(kbId.value);+ }+});++watch(total, (val) => {+ if (selectedTagId.value === '') {+ overallKnowledgeTotal.value = val || 0;+ }+});+// 监听文件上传事件const handleFileUploaded = (event: CustomEvent) => {const uploadedKbId = event.detail.kbId;@@ -125,6 +362,7 @@ const handleFileUploaded = (event: CustomEvent) => {console.log('匹配当前知识库,开始刷新文件列表');// 如果上传的文件属于当前知识库,使用 loadKnowledgeFiles 刷新文件列表loadKnowledgeFiles(uploadedKbId);+ loadTags(uploadedKbId);}};@@ -167,6 +405,7 @@ type KnowledgeCard = {isMore?: boolean;metadata?: any;error_message?: string;+ tag_id?: string;};const updateStatus = (analyzeList: KnowledgeCard[]) => {let query = ``;@@ -234,7 +473,7 @@ const handleScroll = () => {if (scrollTop + clientHeight >= scrollHeight) {page++;if (cardList.value.length < total.value && page <= pageNum) {- getKnowled({ page, page_size: pageSize });+ getKnowled({ page, page_size: pageSize, tag_id: selectedTagId.value || undefined });}}}@@ -248,10 +487,6 @@ const delCardConfirm = () => {delKnowledge(knowledgeIndex.value, knowledge.value);};-const sendMsg = (value: string) => {- createNewSession(value);-};-// 处理知识库编辑成功后的回调const handleKBEditorSuccess = (kbIdValue: string) => {// 如果编辑的是当前知识库,刷新文件列表@@ -294,96 +529,301 @@ async function createNewSession(value: string): Promise<void> {<template><template v-if="!isFAQ">- <div v-show="cardList.length" class="knowledge-card-box" style="position: relative">- <!-- Header -->+ <div class="knowledge-layout"><div class="document-header"><div class="document-header-title"><h2>{{ $t('knowledgeEditor.document.title') }}</h2><p class="document-subtitle">{{ $t('knowledgeEditor.document.subtitle') }}</p></div></div>- <div class="knowledge-card-wrap" ref="knowledgeScroll" @scroll="handleScroll">- <div class="knowledge-card" v-for="(item, index) in cardList" :key="index" @click="openCardDetails(item)">- <div class="card-content">- <div class="card-content-nav">- <span class="card-content-title">{{ item.file_name }}</span>- <t-popup v-model="item.isMore" overlayClassName="card-more"- :on-visible-change="onVisibleChange" trigger="click" destroy-on-close placement="bottom-right">- <div variant="outline" class="more-wrap" @click.stop="openMore(index)"- :class="[moreIndex == index ? 'active-more' : '']">- <img class="more" src="@/assets/img/more.png" alt="" />+ <div class="knowledge-main">+ <aside class="tag-sidebar">+ <div class="sidebar-header">+ <div class="sidebar-title">+ <span>{{ $t('knowledgeBase.documentCategoryTitle') }}</span>+ <span class="sidebar-count">({{ sidebarCategoryCount }})</span>+ </div>+ <div class="sidebar-actions">+ <t-button+ size="small"+ variant="text"+ class="create-tag-btn"+ :aria-label="$t('knowledgeBase.tagCreateAction')"+ :title="$t('knowledgeBase.tagCreateAction')"+ @click="startCreateTag"+ >+ <span class="create-tag-plus" aria-hidden="true">+</span>+ </t-button>+ </div>+ </div>+ <div class="tag-search-bar">+ <t-input+ v-model.trim="tagSearchQuery"+ size="small"+ :placeholder="$t('knowledgeBase.tagSearchPlaceholder')"+ clearable+ >+ <template #prefix-icon>+ <t-icon name="search" size="14px" />+ </template>+ </t-input>+ </div>+ <t-loading :loading="tagLoading" size="small">+ <div class="tag-list">+ <div+ class="tag-list-item"+ :class="{ active: selectedTagId === '' }"+ @click="handleUntaggedClick"+ >+ <div class="tag-list-left">+ <t-icon name="folder" size="18px" />+ <span>{{ $t('knowledgeBase.untagged') || '未分类' }}</span>+ </div>+ <span class="tag-count">{{ untaggedKnowledgeCount }}</span>+ </div>+ <div v-if="creatingTag" class="tag-list-item tag-editing" @click.stop>+ <div class="tag-list-left">+ <t-icon name="folder" size="18px" />+ <div class="tag-edit-input">+ <t-input+ ref="newTagInputRef"+ v-model="newTagName"+ size="small"+ :maxlength="40"+ :placeholder="$t('knowledgeBase.tagNamePlaceholder')"+ @keydown.enter.stop.prevent="submitCreateTag"+ @keydown.esc.stop.prevent="cancelCreateTag"+ />+ </div></div>- <template #content>- <div class="card-menu">- <div- v-if="item.type === 'manual'"- class="card-menu-item"- @click.stop="handleManualEdit(index, item)"- >- <t-icon class="icon" name="edit" />- <span>{{ t('knowledgeBase.editDocument') }}</span>+ <div class="tag-inline-actions">+ <t-button+ variant="text"+ theme="default"+ size="small"+ class="tag-action-btn confirm"+ :loading="creatingTagLoading"+ @click.stop="submitCreateTag"+ >+ <t-icon name="check" size="16px" />+ </t-button>+ <t-button+ variant="text"+ theme="default"+ size="small"+ class="tag-action-btn cancel"+ @click.stop="cancelCreateTag"+ >+ <t-icon name="close" size="16px" />+ </t-button>+ </div>+ </div>++ <template v-if="filteredTags.length">+ <div+ v-for="tag in filteredTags"+ :key="tag.id"+ class="tag-list-item"+ :class="{ active: selectedTagId === tag.id, editing: editingTagId === tag.id }"+ @click="handleTagRowClick(tag.id)"+ >+ <div class="tag-list-left">+ <t-icon name="folder" size="18px" />+ <template v-if="editingTagId === tag.id">+ <div class="tag-edit-input" @click.stop>+ <t-input+ :ref="setEditingTagInputRefByTag(tag.id)"+ v-model="editingTagName"+ size="small"+ :maxlength="40"+ @keydown.enter.stop.prevent="submitEditTag"+ @keydown.esc.stop.prevent="cancelEditTag"+ />+ </div>+ </template>+ <template v-else>+ <span class="tag-name" :title="tag.name">{{ tag.name }}</span>+ </template>+ </div>+ <div class="tag-list-right">+ <span class="tag-count">{{ tag.knowledge_count || 0 }}</span>+ <div v-if="editingTagId === tag.id" class="tag-inline-actions" @click.stop>+ <t-button+ variant="text"+ theme="default"+ size="small"+ class="tag-action-btn confirm"+ :loading="editingTagSubmitting"+ @click.stop="submitEditTag"+ >+ <t-icon name="check" size="16px" />+ </t-button>+ <t-button+ variant="text"+ theme="default"+ size="small"+ class="tag-action-btn cancel"+ @click.stop="cancelEditTag"+ >+ <t-icon name="close" size="16px" />+ </t-button></div>- <div- class="card-menu-item danger"- @click.stop="delCard(index, item)"- >- <t-icon class="icon" name="delete" />- <span>{{ t('knowledgeBase.deleteDocument') }}</span>+ <div v-else class="tag-more" @click.stop>+ <t-popup trigger="click" placement="top-right" overlayClassName="tag-more-popup">+ <div class="tag-more-btn">+ <t-icon name="more" size="14px" />+ </div>+ <template #content>+ <div class="tag-menu">+ <div class="tag-menu-item" @click="startEditTag(tag)">+ <t-icon class="menu-icon" name="edit" />+ <span>{{ $t('knowledgeBase.tagEditAction') }}</span>+ </div>+ <div class="tag-menu-item danger" @click="confirmDeleteTag(tag)">+ <t-icon class="menu-icon" name="delete" />+ <span>{{ $t('knowledgeBase.tagDeleteAction') }}</span>+ </div>+ </div>+ </template>+ </t-popup></div></div>- </template>- </t-popup>- </div>- <div- v-if="item.parse_status === 'processing' || item.parse_status === 'pending'"- class="card-analyze"- >- <t-icon name="loading" class="card-analyze-loading"></t-icon>- <span class="card-analyze-txt">{{ t('knowledgeBase.parsingInProgress') }}</span>+ </div>+ </template>+ <div v-else class="tag-empty-state">+ {{ $t('knowledgeBase.tagEmptyResult') }}+ </div></div>+ </t-loading>+ </aside>+ <div class="tag-content">+ <div class="doc-card-area"><div- v-else-if="item.parse_status === 'failed'"- class="card-analyze failure"+ class="doc-scroll-container"+ :class="{ 'is-empty': !cardList.length }"+ ref="knowledgeScroll"+ @scroll="handleScroll">- <t-icon name="close-circle" class="card-analyze-loading failure"></t-icon>- <span class="card-analyze-txt failure">{{ t('knowledgeBase.parsingFailed') }}</span>- </div>- <div v-else-if="item.parse_status === 'draft'" class="card-draft">- <t-tag size="small" theme="warning" variant="light-outline">{{ t('knowledgeBase.draft') }}</t-tag>- <span class="card-draft-tip">{{ t('knowledgeBase.draftTip') }}</span>- </div>- <div v-else-if="item.parse_status === 'completed'" class="card-content-txt">- {{ item.description }}+ <template v-if="cardList.length">+ <div class="doc-card-list">+ <div+ class="knowledge-card"+ v-for="(item, index) in cardList"+ :key="index"+ @click="openCardDetails(item)"+ >+ <div class="card-content">+ <div class="card-content-nav">+ <span class="card-content-title">{{ item.file_name }}</span>+ <t-popup+ v-model="item.isMore"+ overlayClassName="card-more"+ :on-visible-change="onVisibleChange"+ trigger="click"+ destroy-on-close+ placement="bottom-right"+ >+ <div+ variant="outline"+ class="more-wrap"+ @click.stop="openMore(index)"+ :class="[moreIndex == index ? 'active-more' : '']"+ >+ <img class="more" src="@/assets/img/more.png" alt="" />+ </div>+ <template #content>+ <div class="card-menu">+ <div+ v-if="item.type === 'manual'"+ class="card-menu-item"+ @click.stop="handleManualEdit(index, item)"+ >+ <t-icon class="icon" name="edit" />+ <span>{{ t('knowledgeBase.editDocument') }}</span>+ </div>+ <div class="card-menu-item danger" @click.stop="delCard(index, item)">+ <t-icon class="icon" name="delete" />+ <span>{{ t('knowledgeBase.deleteDocument') }}</span>+ </div>+ </div>+ </template>+ </t-popup>+ </div>+ <div+ v-if="item.parse_status === 'processing' || item.parse_status === 'pending'"+ class="card-analyze"+ >+ <t-icon name="loading" class="card-analyze-loading"></t-icon>+ <span class="card-analyze-txt">{{ t('knowledgeBase.parsingInProgress') }}</span>+ </div>+ <div v-else-if="item.parse_status === 'failed'" class="card-analyze failure">+ <t-icon name="close-circle" class="card-analyze-loading failure"></t-icon>+ <span class="card-analyze-txt failure">{{ t('knowledgeBase.parsingFailed') }}</span>+ </div>+ <div v-else-if="item.parse_status === 'draft'" class="card-draft">+ <t-tag size="small" theme="warning" variant="light-outline">{{ t('knowledgeBase.draft') }}</t-tag>+ <span class="card-draft-tip">{{ t('knowledgeBase.draftTip') }}</span>+ </div>+ <div v-else-if="item.parse_status === 'completed'" class="card-content-txt">+ {{ item.description }}+ </div>+ </div>+ <div class="card-bottom">+ <span class="card-time">{{ formatDocTime(item.updated_at) }}</span>+ <div class="card-bottom-right">+ <div v-if="tagList.length" class="card-tag-selector" @click.stop>+ <t-dropdown+ :options="tagDropdownOptions"+ trigger="click"+ @click="(data: any) => handleKnowledgeTagChange(item.id, data.value as string)"+ >+ <t-tag size="small" variant="light-outline">+ <span class="tag-text">{{ getTagName(item.tag_id) }}</span>+ </t-tag>+ </t-dropdown>+ </div>+ <div class="card-type">+ <span>{{ item.file_type }}</span>+ </div>+ </div>+ </div>+ </div>+ </div>+ </template>+ <template v-else>+ <div class="doc-empty-state">+ <EmptyKnowledge />+ </div>+ </template></div></div>- <div class="card-bottom">- <span class="card-time">{{ item.updated_at }}</span>- <div class="card-type">- <span>{{ item.file_type }}</span>+ <t-dialog+ v-model:visible="delDialog"+ dialogClassName="del-knowledge"+ :closeBtn="false"+ :cancelBtn="null"+ :confirmBtn="null"+ >+ <div class="circle-wrap">+ <div class="header">+ <img class="circle-img" src="@/assets/img/circle.png" alt="" />+ <span class="circle-title">{{ t('knowledgeBase.deleteConfirmation') }}</span>+ </div>+ <span class="del-circle-txt">+ {{ t('knowledgeBase.confirmDeleteDocument', { fileName: knowledge.file_name || '' }) }}+ </span>+ <div class="circle-btn">+ <span class="circle-btn-txt" @click="delDialog = false">{{ t('common.cancel') }}</span>+ <span class="circle-btn-txt confirm" @click="delCardConfirm">+ {{ t('knowledgeBase.confirmDelete') }}+ </span>+ </div></div>- </div>+ </t-dialog>+ <DocContent :visible="isCardDetails" :details="details" @closeDoc="closeDoc" @getDoc="getDoc"></DocContent></div>- <t-dialog v-model:visible="delDialog" dialogClassName="del-knowledge" :closeBtn="false" :cancelBtn="null"- :confirmBtn="null">- <div class="circle-wrap">- <div class="header">- <img class="circle-img" src="@/assets/img/circle.png" alt="">- <span class="circle-title">{{ t('knowledgeBase.deleteConfirmation') }}</span>- </div>- <span class="del-circle-txt">- {{ t('knowledgeBase.confirmDeleteDocument', { fileName: knowledge.file_name || '' }) }}- </span>- <div class="circle-btn">- <span class="circle-btn-txt" @click="delDialog = false">{{ t('common.cancel') }}</span>- <span class="circle-btn-txt confirm" @click="delCardConfirm">{{ t('knowledgeBase.confirmDelete') }}</span>- </div>- </div>- </t-dialog></div>- <InputField @send-msg="sendMsg"></InputField>- <DocContent :visible="isCardDetails" :details="details" @closeDoc="closeDoc" @getDoc="getDoc"></DocContent></div>- <EmptyKnowledge v-show="!cardList.length"></EmptyKnowledge></template><template v-else><div class="faq-manager-wrapper">@@ -415,13 +855,367 @@ async function createNewSession(value: string): Promise<void> {.card-more .t-popup__content:hover {color: inherit !important;}++.tag-more-popup {+ z-index: 99 !important;++ .t-popup__content {+ padding: 4px 0 !important;+ margin-top: 4px !important;+ min-width: 120px;+ }+}</style><style scoped lang="less">-.knowledge-card-box {- flex: 1;+.knowledge-layout {display: flex;flex-direction: column;+ gap: 16px;height: 100%;+ flex: 1;+ width: 100%;+ min-width: 0;+ padding: 24px 44px 32px;+ box-sizing: border-box;+}++.knowledge-main {+ display: flex;+ gap: 12px;+ flex: 1;+ min-height: 0;+}++.tag-sidebar {+ width: 230px;+ background: #fff;+ border-radius: 12px;+ border: 1px solid #e7ebf0;+ padding: 16px;+ display: flex;+ flex-direction: column;+ flex-shrink: 0;++ .sidebar-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin-bottom: 12px;+ color: #1d2129;++ .sidebar-title {+ display: flex;+ align-items: baseline;+ gap: 4px;+ font-weight: 600;++ .sidebar-count {+ font-size: 12px;+ color: #86909c;+ }+ }++ .sidebar-actions {+ display: flex;+ gap: 8px;+ color: #c9ced6;+ align-items: center;++ .create-tag-btn {+ width: 28px;+ height: 28px;+ padding: 0;+ border-radius: 6px;+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 18px;+ font-weight: 600;+ color: #00a870;+ line-height: 1;+ transition: background 0.2s ease, color 0.2s ease;++ &:hover {+ background: #f3f5f7;+ color: #05a04f;+ }+ }++ .create-tag-plus {+ line-height: 1;+ }+ }+ }++ .tag-search-bar {+ margin-bottom: 12px;++ :deep(.t-input) {+ font-size: 12px;+ background-color: #f7f9fc;+ border-color: #e5e9f2;+ }+ }++ .tag-list {+ display: flex;+ flex-direction: column;+ gap: 4px;+ overflow: auto;++ .tag-list-item {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 10px 12px;+ border-radius: 8px;+ color: #4e5969;+ cursor: pointer;+ transition: all 0.2s ease;++ .tag-list-left {+ display: flex;+ align-items: center;+ gap: 8px;+ min-width: 0;++ .t-icon {+ flex-shrink: 0;+ color: #4e5969;+ }+ }++ .tag-name {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .tag-list-right {+ display: flex;+ align-items: center;+ gap: 4px;+ margin-left: 8px;+ min-width: 0;+ }++ .tag-count {+ font-size: 12px;+ color: #86909c;+ }++ &:hover {+ background: #f3f5f7;+ }++ &.active {+ background: #e6f7ec;+ color: #00a870;++ .tag-count {+ color: #00a870;+ }+ }++ &.editing {+ background: transparent;+ border: none;+ }++ &.tag-editing {+ cursor: default;+ padding-right: 8px;+ background: transparent;+ border: none;++ .tag-edit-input {+ flex: 1;+ }+ }++ &.tag-editing .tag-edit-input {+ width: 100%;+ }++ .tag-inline-actions {+ display: flex;+ gap: 4px;+ margin-left: auto;++ :deep(.t-button) {+ padding: 0 4px;+ height: 24px;+ }++ :deep(.tag-action-btn) {+ border-radius: 4px;+ transition: all 0.2s ease;++ .t-icon {+ font-size: 14px;+ }+ }++ :deep(.tag-action-btn.confirm) {+ background: #eefcf5;+ color: #059669;++ &:hover {+ background: #d9f7e9;+ color: #047857;+ }+ }++ :deep(.tag-action-btn.cancel) {+ background: #f9fafb;+ color: #6b7280;++ &:hover {+ background: #f3f4f6;+ color: #4b5563;+ }+ }+ }++ .tag-edit-input {+ flex: 1;+ min-width: 0;+ max-width: 100%;++ :deep(.t-input) {+ font-size: 12px;+ background-color: transparent;+ border: none;+ border-bottom: 1px solid #d0d5dd;+ border-radius: 0;+ box-shadow: none;+ padding-left: 0;+ padding-right: 0;+ }++ :deep(.t-input__wrap) {+ background-color: transparent;+ border: none;+ border-bottom: 1px solid #d0d5dd;+ border-radius: 0;+ box-shadow: none;+ }++ :deep(.t-input__inner) {+ padding-left: 0;+ padding-right: 0;+ color: #1d2129;+ caret-color: #1d2129;+ }++ :deep(.t-input:hover),+ :deep(.t-input.t-is-focused),+ :deep(.t-input__wrap:hover),+ :deep(.t-input__wrap.t-is-focused) {+ border-bottom-color: #00a870;+ }+ }++ .tag-more-btn {+ width: 24px;+ height: 24px;+ display: flex;+ align-items: center;+ justify-content: center;+ border-radius: 4px;+ color: #6b7280;+ transition: background 0.2s ease, color 0.2s ease;++ &:hover {+ background: #e6f0ff;+ color: #0052d9;+ }+ }++ .tag-more {+ display: flex;+ align-items: center;+ }+ }++ .tag-empty-state {+ text-align: center;+ padding: 12px 8px;+ color: #a1a7b3;+ font-size: 12px;+ }+ }+}++:deep(.tag-menu) {+ display: flex;+ flex-direction: column;+}++:deep(.tag-menu-item) {+ display: flex;+ align-items: center;+ padding: 8px 16px;+ cursor: pointer;+ transition: all 0.2s ease;+ color: #000000e6;+ font-family: 'PingFang SC';+ font-size: 14px;+ font-weight: 400;++ .menu-icon {+ margin-right: 8px;+ font-size: 16px;+ }++ &:hover {+ background: #f5f5f5;+ color: #000000e6;+ }++ &.danger {+ color: #000000e6;++ &:hover {+ background: #fff1f0;+ color: #fa5151;++ .menu-icon {+ color: #fa5151;+ }+ }+ }+}++.tag-content {+ flex: 1;+ display: flex;+ flex-direction: column;+ min-height: 0;+}++.doc-card-area {+ flex: 1;+ display: flex;+ flex-direction: column;+ min-height: 0;+}++.doc-scroll-container {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ overflow-x: hidden;+ padding-right: 4px;++ &.is-empty {+ display: flex;+ align-items: center;+ justify-content: center;+ overflow-y: hidden;+ }}// Header 样式@@ -429,7 +1223,7 @@ async function createNewSession(value: string): Promise<void> {display: flex;align-items: center;justify-content: space-between;- padding: 24px 44px 0;+ padding: 0;margin-bottom: 20px;flex-shrink: 0;@@ -458,6 +1252,55 @@ async function createNewSession(value: string): Promise<void> {}}+.tag-filter-bar {+ display: flex;+ align-items: center;+ gap: 16px;++ .tag-filter-label {+ color: #00000099;+ font-size: 14px;+ }+}++.card-tag-selector {+ display: flex;+ align-items: center;++ :deep(.t-tag) {+ cursor: pointer;+ max-width: 160px;+ border-radius: 999px;+ border-color: #e5e7eb;+ color: #374151;+ padding: 0 10px;+ background: #f9fafb;+ transition: all 0.2s ease;++ &:hover {+ border-color: #07c05f;+ color: #059669;+ background: #ecfdf5;+ }+ }++ .tag-text {+ display: inline-block;+ max-width: 110px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ vertical-align: middle;+ font-size: 12px;+ }+}++.card-bottom-right {+ display: flex;+ align-items: center;+ gap: 8px;+}+.faq-manager-wrapper {flex: 1;padding: 24px 44px;@@ -504,15 +1347,22 @@ async function createNewSession(value: string): Promise<void> {}}-.knowledge-card-wrap {- // padding: 24px 44px;- padding: 0 44px 80px 44px;+.doc-card-list {box-sizing: border-box;display: grid;gap: 20px;- overflow-y: auto;- height: 100%;align-content: flex-start;+ width: 100%;+}++.doc-empty-state {+ flex: 1;+ width: 100%;+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 60px 20px;+ min-height: 100%;}:deep(.del-knowledge) {@@ -714,6 +1564,7 @@ async function createNewSession(value: string): Promise<void> {display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 3;+ line-clamp: 3;overflow: hidden;color: #00000066;font-family: "PingFang SC";@@ -791,7 +1642,7 @@ async function createNewSession(value: string): Promise<void> {margin: 0 auto;}-.knowledge-card-wrap {+.doc-card-list {grid-template-columns: 1fr;}@@ -801,28 +1652,28 @@ async function createNewSession(value: string): Promise<void> {/* 小屏幕平板 - 2列 */@media (min-width: 900px) {- .knowledge-card-wrap {+ .doc-card-list {grid-template-columns: repeat(2, 1fr);}}/* 中等屏幕 - 3列 */@media (min-width: 1250px) {- .knowledge-card-wrap {+ .doc-card-list {grid-template-columns: repeat(3, 1fr);}}/* 中等屏幕 - 3列 */@media (min-width: 1600px) {- .knowledge-card-wrap {+ .doc-card-list {grid-template-columns: repeat(4, 1fr);}}/* 大屏幕 - 4列 */@media (min-width: 2000px) {- .knowledge-card-wrap {+ .doc-card-list {grid-template-columns: repeat(5, 1fr);}}diff --git a/frontend/src/views/knowledge/components/FAQEntryManager.vue b/frontend/src/views/knowledge/components/FAQEntryManager.vueindex 7b4617139..0c3c0dc1b 100644--- a/frontend/src/views/knowledge/components/FAQEntryManager.vue+++ b/frontend/src/views/knowledge/components/FAQEntryManager.vue@@ -1,209 +1,416 @@<template><div class="faq-manager">- <!-- Header -->- <div class="faq-header">- <div class="faq-header-title">- <h2>{{ $t('knowledgeEditor.faq.title') }}</h2>- <p class="faq-subtitle">{{ $t('knowledgeEditor.faq.subtitle') }}</p>- </div>- <div class="action-buttons">- <button class="create-btn ghost" @click="openEditor()">- <t-icon name="add" size="16px" class="btn-icon" />- <span>{{ $t('knowledgeEditor.faq.editorCreate') }}</span>- </button>- <t-dropdown- :options="toolbarActionOptions"- placement="bottom-left"- trigger="click"- @click="handleToolbarAction"- >- <div class="toolbar-action-trigger">- <t-icon name="more" />- </div>- </t-dropdown>+ <div class="faq-content">+ <!-- Header -->+ <div class="faq-header">+ <div class="faq-header-title">+ <h2>{{ $t('knowledgeEditor.faq.title') }}</h2>+ <p class="faq-subtitle">{{ $t('knowledgeEditor.faq.subtitle') }}</p>+ </div>+ <div class="action-buttons">+ <button class="create-btn ghost" @click="openEditor()">+ <t-icon name="add" size="16px" class="btn-icon" />+ <span>{{ $t('knowledgeEditor.faq.editorCreate') }}</span>+ </button>+ <t-dropdown+ :options="toolbarActionOptions"+ placement="bottom-left"+ trigger="click"+ @click="handleToolbarAction"+ >+ <div class="toolbar-action-trigger">+ <t-icon name="more" />+ </div>+ </t-dropdown>+ </div></div>- </div>- <!-- Card List Container with Scroll -->- <div ref="scrollContainer" class="faq-scroll-container" @scroll="handleScroll">- <t-loading :loading="loading && entries.length === 0" size="medium">- <!-- Card List -->- <div v-if="entries.length > 0" ref="cardListRef" class="faq-card-list">- <div- v-for="entry in entries"- :key="entry.id"- class="faq-card"- :class="{ 'selected': selectedRowKeys.includes(entry.id) }"- @click="handleCardSelect(entry.id, !selectedRowKeys.includes(entry.id))"- >- <!-- Card Header -->- <div class="faq-card-header">- <div class="faq-question" :title="entry.standard_question">- {{ entry.standard_question }}+ <div class="faq-main">+ <aside class="faq-tag-panel">+ <div class="sidebar-header">+ <div class="sidebar-title">+ <span>{{ $t('knowledgeBase.faqCategoryTitle') }}</span>+ <span class="sidebar-count">({{ sidebarCategoryCount }})</span></div>- <t-popup- v-model="entry.showMore"- overlayClassName="faq-card-popup"- trigger="click"- destroy-on-close- placement="bottom-right"- @visible-change="(visible: boolean) => entry.showMore = visible"+ <div class="sidebar-actions">+ <t-button+ size="small"+ variant="text"+ class="create-tag-btn"+ :aria-label="$t('knowledgeBase.tagCreateAction')"+ :title="$t('knowledgeBase.tagCreateAction')"+ @click="startCreateTag"+ >+ <span class="create-tag-plus" aria-hidden="true">+</span>+ </t-button>+ </div>+ </div>+ <div class="tag-search-bar">+ <t-input+ v-model.trim="tagSearchQuery"+ size="small"+ :placeholder="$t('knowledgeBase.tagSearchPlaceholder')"+ clearable>- <div class="card-more-btn" @click.stop>- <img class="more-icon" src="@/assets/img/more.png" alt="" />- </div>- <template #content>- <div class="card-menu" @click.stop>- <div class="card-menu-item" @click.stop="handleMenuEdit(entry)">- <t-icon class="menu-icon" name="edit" />- <span>{{ $t('common.edit') }}</span>- </div>- <div class="card-menu-item danger" @click.stop="handleMenuDelete(entry)">- <t-icon class="menu-icon" name="delete" />- <span>{{ $t('common.delete') }}</span>- </div>- </div>+ <template #prefix-icon>+ <t-icon name="search" size="14px" /></template>- </t-popup>+ </t-input></div>-- <!-- Card Body -->- <div class="faq-card-body">- <!-- Similar Questions Section -->- <div v-if="entry.similar_questions?.length" class="faq-section similar">- <div- class="faq-section-label clickable"- @click.stop="entry.similarCollapsed = !entry.similarCollapsed"+ <t-loading :loading="tagLoading" size="small">+ <div class="faq-tag-list">+ <div+ class="faq-tag-item"+ :class="{ active: selectedTagId === '' }"+ @click="handleUntaggedClick">- <span>{{ $t('knowledgeEditor.faq.similarQuestions') }}</span>- <span class="section-count">- ({{ entry.similar_questions.length }})- </span>- <t-icon- :name="entry.similarCollapsed ? 'chevron-right' : 'chevron-down'"- class="collapse-icon"- />+ <div class="faq-tag-left">+ <t-icon name="folder" size="18px" />+ <span>{{ $t('knowledgeBase.untagged') }}</span>+ </div>+ <span class="faq-tag-count">{{ untaggedFAQCount }}</span></div>- <Transition name="slide-down">- <div v-if="!entry.similarCollapsed" class="faq-tags">- <FAQTagTooltip- v-for="question in entry.similar_questions"- :key="question"- :content="question"- type="similar"- placement="top"- >- <t-tag++ <div v-if="creatingTag" class="faq-tag-item tag-editing" @click.stop>+ <div class="faq-tag-left">+ <t-icon name="folder" size="18px" />+ <div class="tag-edit-input">+ <t-input+ ref="newTagInputRef"+ v-model="newTagName"size="small"- variant="light-outline"- class="question-tag"- >- {{ question }}- </t-tag>- </FAQTagTooltip>+ :maxlength="40"+ :placeholder="$t('knowledgeBase.tagNamePlaceholder')"+ @keydown.enter.stop.prevent="submitCreateTag"+ @keydown.esc.stop.prevent="cancelCreateTag"+ />+ </div></div>- </Transition>- </div>-- <!-- Negative Questions Section -->- <div v-if="entry.negative_questions?.length" class="faq-section negative">- <div- class="faq-section-label clickable"- @click.stop="entry.negativeCollapsed = !entry.negativeCollapsed"- >- <span>{{ $t('knowledgeEditor.faq.negativeQuestions') }}</span>- <span class="section-count">- ({{ entry.negative_questions.length }})- </span>- <t-icon- :name="entry.negativeCollapsed ? 'chevron-right' : 'chevron-down'"- class="collapse-icon"- />- </div>- <Transition name="slide-down">- <div v-if="!entry.negativeCollapsed" class="faq-tags">- <FAQTagTooltip- v-for="question in entry.negative_questions"- :key="question"- :content="question"- type="negative"- placement="top"+ <div class="tag-inline-actions">+ <t-button+ variant="text"+ theme="default"+ size="small"+ class="tag-action-btn confirm"+ :loading="creatingTagLoading"+ @click.stop="submitCreateTag">- <t-tag- size="small"- theme="warning"- variant="light-outline"- class="question-tag"- >- {{ question }}- </t-tag>- </FAQTagTooltip>+ <t-icon name="check" size="16px" />+ </t-button>+ <t-button+ variant="text"+ theme="default"+ size="small"+ class="tag-action-btn cancel"+ @click.stop="cancelCreateTag"+ >+ <t-icon name="close" size="16px" />+ </t-button></div>- </Transition>- </div>-- <!-- Answers Section -->- <div class="faq-section answers">- <div- class="faq-section-label clickable"- @click.stop="entry.answersCollapsed = !entry.answersCollapsed"- >- <span>{{ $t('knowledgeEditor.faq.answers') }}</span>- <span v-if="entry.answers?.length" class="section-count">- ({{ entry.answers.length }})- </span>- <t-icon- :name="entry.answersCollapsed ? 'chevron-right' : 'chevron-down'"- class="collapse-icon"- /></div>- <Transition name="slide-down">- <div v-if="!entry.answersCollapsed" class="faq-tags">- <FAQTagTooltip- v-for="answer in entry.answers"- :key="answer"- :content="answer"- type="answer"- placement="top"- >- <t-tag- size="small"- variant="light-outline"- class="question-tag"- >- {{ answer }}- </t-tag>- </FAQTagTooltip>- <span v-if="!entry.answers?.length" class="empty-tip">- {{ $t('knowledgeEditor.faq.noAnswer') }}- </span>++ <template v-if="filteredTags.length">+ <div+ v-for="tag in filteredTags"+ :key="tag.id"+ class="faq-tag-item"+ :class="{ active: selectedTagId === tag.id, editing: editingTagId === tag.id }"+ @click="handleTagRowClick(tag.id)"+ >+ <div class="faq-tag-left">+ <t-icon name="folder" size="18px" />+ <template v-if="editingTagId === tag.id">+ <div class="tag-edit-input" @click.stop>+ <t-input+ :ref="setEditingTagInputRefByTag(tag.id)"+ v-model="editingTagName"+ size="small"+ :maxlength="40"+ @keydown.enter.stop.prevent="submitEditTag"+ @keydown.esc.stop.prevent="cancelEditTag"+ />+ </div>+ </template>+ <template v-else>+ <span class="tag-name" :title="tag.name">{{ tag.name }}</span>+ </template>+ </div>+ <div class="faq-tag-right">+ <span class="faq-tag-count">{{ tag.chunk_count || 0 }}</span>+ <div v-if="editingTagId === tag.id" class="tag-inline-actions" @click.stop>+ <t-button+ variant="text"+ theme="default"+ size="small"+ class="tag-action-btn confirm"+ :loading="editingTagSubmitting"+ @click.stop="submitEditTag"+ >+ <t-icon name="check" size="16px" />+ </t-button>+ <t-button+ variant="text"+ theme="default"+ size="small"+ class="tag-action-btn cancel"+ @click.stop="cancelEditTag"+ >+ <t-icon name="close" size="16px" />+ </t-button>+ </div>+ <div v-else class="tag-more" @click.stop>+ <t-popup trigger="click" placement="top-right" overlayClassName="tag-more-popup">+ <div class="tag-more-btn">+ <t-icon name="more" size="14px" />+ </div>+ <template #content>+ <div class="tag-menu">+ <div class="tag-menu-item" @click="startEditTag(tag)">+ <t-icon class="menu-icon" name="edit" />+ <span>{{ $t('knowledgeBase.tagEditAction') }}</span>+ </div>+ <div class="tag-menu-item danger" @click="confirmDeleteTag(tag)">+ <t-icon class="menu-icon" name="delete" />+ <span>{{ $t('knowledgeBase.tagDeleteAction') }}</span>+ </div>+ </div>+ </template>+ </t-popup>+ </div>+ </div></div>- </Transition>+ </template>+ <div v-else class="tag-empty-state">+ {{ $t('knowledgeBase.tagEmptyResult') }}+ </div></div>- </div>+ </t-loading>+ </aside>++ <div class="faq-card-area">+ <!-- Card List Container with Scroll -->+ <div ref="scrollContainer" class="faq-scroll-container" @scroll="handleScroll">+ <t-loading :loading="loading && entries.length === 0" size="medium">+ <!-- Card List -->+ <template v-if="entries.length > 0">+ <div ref="cardListRef" class="faq-card-list">+ <div+ v-for="entry in entries"+ :key="entry.id"+ class="faq-card"+ :class="{ 'selected': selectedRowKeys.includes(entry.id) }"+ @click="handleCardSelect(entry.id, !selectedRowKeys.includes(entry.id))"+ >+ <!-- Card Header -->+ <div class="faq-card-header">+ <div class="faq-header-top">+ <div class="faq-question" :title="entry.standard_question">+ {{ entry.standard_question }}+ </div>+ <div class="faq-card-actions">+ <t-popup+ v-model="entry.showMore"+ overlayClassName="faq-card-popup"+ trigger="click"+ destroy-on-close+ placement="bottom-right"+ @visible-change="(visible: boolean) => (entry.showMore = visible)"+ >+ <div class="card-more-btn" @click.stop>+ <img class="more-icon" src="@/assets/img/more.png" alt="" />+ </div>+ <template #content>+ <div class="card-menu" @click.stop>+ <div class="card-menu-item" @click.stop="handleMenuEdit(entry)">+ <t-icon class="menu-icon" name="edit" />+ <span>{{ $t('common.edit') }}</span>+ </div>+ <div class="card-menu-item danger" @click.stop="handleMenuDelete(entry)">+ <t-icon class="menu-icon" name="delete" />+ <span>{{ $t('common.delete') }}</span>+ </div>+ </div>+ </template>+ </t-popup>+ </div>+ </div>+ </div>- </div>- </div>+ <!-- Card Body -->+ <div class="faq-card-body">+ <!-- Similar Questions Section -->+ <div v-if="entry.similar_questions?.length" class="faq-section similar">+ <div+ class="faq-section-label clickable"+ @click.stop="entry.similarCollapsed = !entry.similarCollapsed"+ >+ <span>{{ $t('knowledgeEditor.faq.similarQuestions') }}</span>+ <span class="section-count">+ ({{ entry.similar_questions.length }})+ </span>+ <t-icon+ :name="entry.similarCollapsed ? 'chevron-right' : 'chevron-down'"+ class="collapse-icon"+ />+ </div>+ <Transition name="slide-down">+ <div v-if="!entry.similarCollapsed" class="faq-tags">+ <FAQTagTooltip+ v-for="question in entry.similar_questions"+ :key="question"+ :content="question"+ type="similar"+ placement="top"+ >+ <t-tag+ size="small"+ variant="light-outline"+ class="question-tag"+ >+ {{ question }}+ </t-tag>+ </FAQTagTooltip>+ </div>+ </Transition>+ </div>++ <!-- Negative Questions Section -->+ <div v-if="entry.negative_questions?.length" class="faq-section negative">+ <div+ class="faq-section-label clickable"+ @click.stop="entry.negativeCollapsed = !entry.negativeCollapsed"+ >+ <span>{{ $t('knowledgeEditor.faq.negativeQuestions') }}</span>+ <span class="section-count">+ ({{ entry.negative_questions.length }})+ </span>+ <t-icon+ :name="entry.negativeCollapsed ? 'chevron-right' : 'chevron-down'"+ class="collapse-icon"+ />+ </div>+ <Transition name="slide-down">+ <div v-if="!entry.negativeCollapsed" class="faq-tags">+ <FAQTagTooltip+ v-for="question in entry.negative_questions"+ :key="question"+ :content="question"+ type="negative"+ placement="top"+ >+ <t-tag+ size="small"+ theme="warning"+ variant="light-outline"+ class="question-tag"+ >+ {{ question }}+ </t-tag>+ </FAQTagTooltip>+ </div>+ </Transition>+ </div>- <!-- Empty State -->- <div v-else-if="!loading" class="faq-empty-state">- <div class="empty-content">- <t-icon name="file-add" size="48px" class="empty-icon" />- <div class="empty-text">{{ $t('knowledgeEditor.faq.emptyTitle') }}</div>- <div class="empty-desc">{{ $t('knowledgeEditor.faq.emptyDesc') }}</div>+ <!-- Answers Section -->+ <div class="faq-section answers">+ <div+ class="faq-section-label clickable"+ @click.stop="entry.answersCollapsed = !entry.answersCollapsed"+ >+ <span>{{ $t('knowledgeEditor.faq.answers') }}</span>+ <span v-if="entry.answers?.length" class="section-count">+ ({{ entry.answers.length }})+ </span>+ <t-icon+ :name="entry.answersCollapsed ? 'chevron-right' : 'chevron-down'"+ class="collapse-icon"+ />+ </div>+ <Transition name="slide-down">+ <div v-if="!entry.answersCollapsed" class="faq-tags">+ <FAQTagTooltip+ v-for="answer in entry.answers"+ :key="answer"+ :content="answer"+ type="answer"+ placement="top"+ >+ <t-tag+ size="small"+ theme="success"+ variant="light-outline"+ class="question-tag"+ >+ {{ answer }}+ </t-tag>+ </FAQTagTooltip>+ </div>+ </Transition>+ </div>+ </div>++ <!-- Card Footer -->+ <div class="faq-card-footer">+ <div class="faq-card-tag" @click.stop>+ <template v-if="tagList.length">+ <t-dropdown+ :options="tagDropdownOptions"+ trigger="click"+ @click="(data: any) => handleEntryTagChange(entry.id, data.value as string)"+ >+ <t-tag size="small" variant="light-outline" class="faq-tag-chip">+ <span class="tag-text">{{ getTagName(entry.tag_id) || $t('knowledgeBase.untagged') }}</span>+ </t-tag>+ </t-dropdown>+ </template>+ <template v-else>+ <t-tag size="small" variant="light-outline" class="faq-tag-chip">+ <span class="tag-text">{{ getTagName(entry.tag_id) || $t('knowledgeBase.untagged') }}</span>+ </t-tag>+ </template>+ </div>+ <div class="faq-card-status" @click.stop>+ <t-tooltip+ :content="entry.is_enabled ? $t('knowledgeEditor.faq.statusEnabled') : $t('knowledgeEditor.faq.statusDisabled')"+ placement="top"+ >+ <div class="status-item-compact">+ <t-switch+ :key="`${entry.id}-${entry.is_enabled}`"+ size="small"+ :value="entry.is_enabled"+ :loading="!!entryStatusLoading[entry.id]"+ :disabled="!!entryStatusLoading[entry.id]"+ @click.stop+ @change="(value: boolean) => handleEntryStatusChange(entry, value)"+ />+ </div>+ </t-tooltip>+ </div>+ </div>+ </div>+ </div>+ </template>+ <template v-else>+ <div v-if="!loading" class="faq-empty-state">+ <div class="empty-content">+ <t-icon name="file-add" size="48px" class="empty-icon" />+ <div class="empty-text">{{ $t('knowledgeEditor.faq.emptyTitle') }}</div>+ <div class="empty-desc">{{ $t('knowledgeEditor.faq.emptyDesc') }}</div>+ </div>+ </div>+ </template>+ </t-loading>+ <div v-if="loadingMore" class="faq-load-more">+ <t-loading size="small" :text="$t('common.loading')" />+ </div>+ <div v-if="hasMore === false && entries.length > 0" class="faq-no-more">+ {{ $t('common.noMoreData') }}+ </div></div></div>- </t-loading>-- <!-- Load More Indicator -->- <div v-if="loadingMore" class="faq-load-more">- <t-loading size="small" :text="$t('common.loading')" />- </div>- <div v-if="hasMore === false && entries.length > 0" class="faq-no-more">- {{ $t('common.noMoreData') }}</div></div>-<!-- Editor Drawer --><t-drawerv-model:visible="editorVisible"@@ -387,6 +594,22 @@</div></div></div>++ <div class="setting-row vertical">+ <div class="setting-info">+ <label>{{ $t('knowledgeBase.category') || '分类' }}</label>+ <p class="desc">{{ $t('knowledgeEditor.faq.tagDesc') || '为 FAQ 条目选择分类' }}</p>+ </div>+ <div class="setting-control">+ <t-select+ v-model="editorForm.tag_id"+ class="full-width-input"+ :options="tagSelectOptions"+ clearable+ :placeholder="$t('knowledgeEditor.faq.tagPlaceholder') || '选择分类'"+ />+ </div>+ </div></div></t-form></div>@@ -520,6 +743,39 @@</Transition></Teleport>+ <!-- Batch Tag Dialog -->+ <t-dialog+ v-model:visible="batchTagDialogVisible"+ :header="$t('knowledgeEditor.faq.batchUpdateTag')"+ width="480px"+ :confirm-btn="{ content: $t('common.confirm'), theme: 'primary' }"+ :cancel-btn="{ content: $t('common.cancel') }"+ @confirm="handleBatchTag"+ >+ <div class="batch-tag-dialog-content">+ <p class="batch-tag-dialog-tip">+ {{ $t('knowledgeEditor.faq.batchUpdateTagTip', { count: selectedRowKeys.length }) }}+ </p>+ <t-form layout="vertical" class="batch-tag-form">+ <t-form-item :label="$t('knowledgeBase.tagLabel')">+ <t-select+ v-model="batchTagValue"+ :options="tagSelectOptions"+ :placeholder="$t('knowledgeBase.tagPlaceholder')"+ clearable+ filterable+ >+ <template #empty>+ <div class="tag-select-empty">+ {{ $t('knowledgeBase.noTags') }}+ </div>+ </template>+ </t-select>+ </t-form-item>+ </t-form>+ </div>+ </t-dialog>+<!-- Search Test Drawer --><t-drawerv-model:visible="searchDrawerVisible"@@ -682,15 +938,22 @@<script setup lang="ts">import { ref, reactive, watch, onMounted, computed, nextTick, onUnmounted } from 'vue'-import { MessagePlugin } from 'tdesign-vue-next'+import type { ComponentPublicInstance } from 'vue'+import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'import type { FormRules, FormInstanceFunctions } from 'tdesign-vue-next'import { useI18n } from 'vue-i18n'import {listFAQEntries,upsertFAQEntries,updateFAQEntry,+ updateFAQEntryStatusBatch,deleteFAQEntries,searchFAQEntries,+ listKnowledgeTags,+ updateFAQEntryTagBatch,+ createKnowledgeBaseTag,+ updateKnowledgeBaseTag,+ deleteKnowledgeBaseTag,} from '@/api/knowledge-base'import * as XLSX from 'xlsx'import FAQTagTooltip from '@/components/FAQTagTooltip.vue'@@ -700,6 +963,8 @@ interface FAQEntry {chunk_id: stringknowledge_id: stringknowledge_base_id: string+ tag_id?: string+ is_enabled: booleanstandard_question: stringsimilar_questions: string[]negative_questions: string[]@@ -719,6 +984,7 @@ interface FAQEntryPayload {similar_questions: string[]negative_questions: string[]answers: string[]+ tag_id?: string}const props = defineProps<{@@ -730,12 +996,67 @@ const { t } = useI18n()const loading = ref(false)const loadingMore = ref(false)const entries = ref<FAQEntry[]>([])+const entryStatusLoading = reactive<Record<string, boolean>>({})const selectedRowKeys = ref<string[]>([])const scrollContainer = ref<HTMLElement | null>(null)const cardListRef = ref<HTMLElement | null>(null)const hasMore = ref(true)const pageSize = 20let currentPage = 1+type TagInputInstance = ComponentPublicInstance<{ focus: () => void; select: () => void }>++const tagList = ref<any[]>([])+const tagLoading = ref(false)+const selectedTagId = ref<string>('')+const overallFAQTotal = ref(0)+const tagSearchQuery = ref('')+const editingTagInputRefs = new Map<string, TagInputInstance | null>()+const setEditingTagInputRef = (el: TagInputInstance | null, tagId: string) => {+ if (el) {+ editingTagInputRefs.set(tagId, el)+ } else {+ editingTagInputRefs.delete(tagId)+ }+}+const setEditingTagInputRefByTag = (tagId: string) => (el: TagInputInstance | null) => {+ setEditingTagInputRef(el, tagId)+}+const newTagInputRef = ref<TagInputInstance | null>(null)+const creatingTag = ref(false)+const creatingTagLoading = ref(false)+const newTagName = ref('')+const editingTagId = ref<string | null>(null)+const editingTagName = ref('')+const editingTagSubmitting = ref(false)+const tagDropdownOptions = computed(() => [+ { content: t('knowledgeBase.untagged') || '未分类', value: '' },+ ...tagList.value.map((tag: any) => ({ content: tag.name, value: tag.id })),+])+const tagMap = computed<Record<string, any>>(() => {+ const map: Record<string, any> = {}+ tagList.value.forEach((tag) => {+ map[tag.id] = tag+ })+ return map+})+const tagSelectOptions = computed(() => [+ { label: t('knowledgeBase.untagged') || '未分类', value: '' },+ ...tagList.value.map((tag: any) => ({ label: tag.name, value: tag.id })),+])+const sidebarCategoryCount = computed(() => tagList.value.length + 1)+const assignedFAQCount = computed(() =>+ tagList.value.reduce((sum, tag) => sum + (tag.chunk_count || 0), 0),+)+const untaggedFAQCount = computed(() =>+ Math.max(overallFAQTotal.value - assignedFAQCount.value, 0),+)+const filteredTags = computed(() => {+ const query = tagSearchQuery.value.trim().toLowerCase()+ if (!query) {+ return tagList.value+ }+ return tagList.value.filter((tag) => (tag.name || '').toLowerCase().includes(query))+})const editorVisible = ref(false)const editorMode = ref<'create' | 'edit'>('create')@@ -745,6 +1066,7 @@ const editorForm = reactive<FAQEntryPayload>({similar_questions: [],negative_questions: [],answers: [],+ tag_id: '',})const editorFormRef = ref<FormInstanceFunctions>()const savingEntry = ref(false)@@ -781,13 +1103,30 @@ const toolbarActionOptions = computed(() => {{ content: t('knowledgeEditor.faq.searchTest'), value: 'search', icon: 'search' },]- // 如果有选中的条目,添加批量删除选项+ // 如果有选中的条目,添加批量操作选项if (selectedRowKeys.value.length > 0) {- options.push({- content: `${t('knowledgeEditor.faqImport.deleteSelected')} (${selectedRowKeys.value.length})`,- value: 'delete',- icon: 'delete',- })+ options.push(+ {+ content: `${t('knowledgeEditor.faq.batchUpdateTag')} (${selectedRowKeys.value.length})`,+ value: 'batchTag',+ icon: 'folder',+ },+ {+ content: `${t('knowledgeEditor.faq.batchEnable')} (${selectedRowKeys.value.length})`,+ value: 'batchEnable',+ icon: 'check-circle',+ },+ {+ content: `${t('knowledgeEditor.faq.batchDisable')} (${selectedRowKeys.value.length})`,+ value: 'batchDisable',+ icon: 'close-circle',+ },+ {+ content: `${t('knowledgeEditor.faqImport.deleteSelected')} (${selectedRowKeys.value.length})`,+ value: 'delete',+ icon: 'delete',+ }+ )}return options@@ -801,12 +1140,242 @@ const handleToolbarAction = (data: { value: string }) => {case 'search':searchDrawerVisible.value = truebreak+ case 'batchTag':+ openBatchTagDialog()+ break+ case 'batchEnable':+ handleBatchStatusChange(true)+ break+ case 'batchDisable':+ handleBatchStatusChange(false)+ breakcase 'delete':handleBatchDelete()break}}+const loadTags = async () => {+ if (!props.kbId) {+ tagList.value = []+ return+ }+ tagLoading.value = true+ try {+ const res: any = await listKnowledgeTags(props.kbId)+ tagList.value = (res?.data || []).map((tag: any) => ({+ ...tag,+ id: String(tag.id),+ }))+ } catch (error: any) {+ MessagePlugin.error(error?.message || t('common.operationFailed'))+ } finally {+ tagLoading.value = false+ }+}++const getTagName = (tagId?: string) => {+ if (!tagId) return t('knowledgeBase.untagged') || '未分类'+ return tagMap.value[tagId]?.name || (t('knowledgeBase.untagged') || '未分类')+}++const handleTagFilterChange = (value: string) => {+ selectedTagId.value = value+}++const handleTagRowClick = (tagId: string) => {+ const normalizedId = String(tagId)+ if (editingTagId.value && editingTagId.value !== normalizedId) {+ cancelEditTag()+ }+ if (creatingTag.value) {+ cancelCreateTag()+ }+ if (selectedTagId.value === normalizedId) {+ return+ }+ handleTagFilterChange(normalizedId)+}++const handleUntaggedClick = () => {+ if (creatingTag.value) {+ cancelCreateTag()+ }+ if (editingTagId.value) {+ cancelEditTag()+ }+ if (selectedTagId.value === '') return+ handleTagFilterChange('')+}++const startCreateTag = () => {+ if (!props.kbId) {+ MessagePlugin.warning(t('knowledgeEditor.messages.missingId'))+ return+ }+ if (creatingTag.value) {+ return+ }+ cancelEditTag()+ creatingTag.value = true+ nextTick(() => {+ newTagInputRef.value?.focus?.()+ newTagInputRef.value?.select?.()+ })+}++const cancelCreateTag = () => {+ creatingTag.value = false+ newTagName.value = ''+}++const submitCreateTag = async () => {+ if (!props.kbId) {+ MessagePlugin.warning(t('knowledgeEditor.messages.missingId'))+ return+ }+ const name = newTagName.value.trim()+ if (!name) {+ MessagePlugin.warning(t('knowledgeBase.tagNameRequired'))+ return+ }+ creatingTagLoading.value = true+ try {+ await createKnowledgeBaseTag(props.kbId, { name })+ MessagePlugin.success(t('knowledgeBase.tagCreateSuccess'))+ cancelCreateTag()+ await loadTags()+ } catch (error: any) {+ MessagePlugin.error(error?.message || t('common.operationFailed'))+ } finally {+ creatingTagLoading.value = false+ }+}++const startEditTag = (tag: any) => {+ cancelCreateTag()+ editingTagId.value = tag.id+ editingTagName.value = tag.name+ nextTick(() => {+ const inputRef = editingTagInputRefs.get(tag.id)+ inputRef?.focus?.()+ inputRef?.select?.()+ })+}++const cancelEditTag = () => {+ editingTagId.value = null+ editingTagName.value = ''+}++const submitEditTag = async () => {+ if (!props.kbId || !editingTagId.value) {+ return+ }+ const name = editingTagName.value.trim()+ if (!name) {+ MessagePlugin.warning(t('knowledgeBase.tagNameRequired'))+ return+ }+ if (name === tagMap.value[editingTagId.value]?.name) {+ cancelEditTag()+ return+ }+ editingTagSubmitting.value = true+ try {+ await updateKnowledgeBaseTag(props.kbId, editingTagId.value, { name })+ MessagePlugin.success(t('knowledgeBase.tagEditSuccess'))+ cancelEditTag()+ await loadTags()+ } catch (error: any) {+ MessagePlugin.error(error?.message || t('common.operationFailed'))+ } finally {+ editingTagSubmitting.value = false+ }+}++const confirmDeleteTag = (tag: any) => {+ if (!props.kbId) {+ MessagePlugin.warning(t('knowledgeEditor.messages.missingId'))+ return+ }+ if (creatingTag.value) {+ cancelCreateTag()+ }+ if (editingTagId.value) {+ cancelEditTag()+ }+ const confirmDialog = DialogPlugin.confirm({+ header: t('knowledgeBase.tagDeleteTitle'),+ body: t('knowledgeBase.tagDeleteDesc', { name: tag.name }),+ confirmBtn: { content: t('common.delete'), theme: 'danger' },+ cancelBtn: t('common.cancel'),+ onConfirm: async () => {+ try {+ await deleteKnowledgeBaseTag(props.kbId, tag.id)+ MessagePlugin.success(t('knowledgeBase.tagDeleteSuccess'))+ if (selectedTagId.value === tag.id) {+ handleTagFilterChange('')+ }+ await loadTags()+ confirmDialog.hide()+ } catch (error: any) {+ MessagePlugin.error(error?.message || t('common.operationFailed'))+ }+ },+ })+}++const handleEntryTagChange = async (entryId: string, value?: string) => {+ if (!props.kbId) return+ const targetEntry = entries.value.find((item) => item.id === entryId)+ const previousTagId = targetEntry ? targetEntry.tag_id : ''+ const normalizedValue = value ?? ''+ if (normalizedValue === previousTagId) {+ return+ }+ try {+ await updateFAQEntryTagBatch(props.kbId, { updates: { [entryId]: normalizedValue || null } })+ MessagePlugin.success(t('knowledgeEditor.messages.updateSuccess'))+ await loadEntries()+ await loadTags()+ } catch (error: any) {+ if (targetEntry) {+ targetEntry.tag_id = previousTagId+ }+ MessagePlugin.error(error?.message || t('common.operationFailed'))+ }+}++const handleEntryStatusChange = async (entry: FAQEntry, value: boolean) => {+ if (!props.kbId) {+ return+ }+ const entryIndex = entries.value.findIndex(e => e.id === entry.id)+ if (entryIndex === -1) {+ return+ }+ // 从数组中获取实际的对象引用,确保使用最新的数据+ const actualEntry = entries.value[entryIndex]+ const previous = actualEntry.is_enabled+ if (previous === value) {+ return+ }+ // 直接更新属性,Vue 3 的响应式系统应该能够检测到+ actualEntry.is_enabled = value+ entryStatusLoading[entry.id] = true+ try {+ await updateFAQEntryStatusBatch(props.kbId, { updates: { [entry.id]: value } })+ MessagePlugin.success(t(value ? 'knowledgeEditor.faq.statusEnableSuccess' : 'knowledgeEditor.faq.statusDisableSuccess'))+ } catch (error: any) {+ // 失败时回滚+ actualEntry.is_enabled = previous+ MessagePlugin.error(error?.message || t('knowledgeEditor.faq.statusUpdateFailed'))+ } finally {+ entryStatusLoading[entry.id] = false+ }+}+const editorRules: FormRules<FAQEntryPayload> = {standard_question: [{ required: true, message: t('knowledgeEditor.messages.nameRequired') },@@ -828,12 +1397,16 @@ const loadEntries = async (append = false) => {currentPage = 1entries.value = []selectedRowKeys.value = []+ Object.keys(entryStatusLoading).forEach((key) => {+ delete entryStatusLoading[key]+ })}try {const res = await listFAQEntries(props.kbId, {page: currentPage,page_size: pageSize,+ tag_id: selectedTagId.value || undefined,})const pageData = (res.data || {}) as {data: FAQEntry[]@@ -844,7 +1417,9 @@ const loadEntries = async (append = false) => {showMore: false,similarCollapsed: false, // 相似问默认展开negativeCollapsed: true, // 反例默认折叠- answersCollapsed: true // 答案默认折叠+ answersCollapsed: true, // 答案默认折叠+ tag_id: entry.tag_id ? String(entry.tag_id) : '',+ is_enabled: entry.is_enabled !== false,}))if (append) {@@ -852,7 +1427,9 @@ const loadEntries = async (append = false) => {} else {entries.value = newEntries}-+ if (selectedTagId.value === '') {+ overallFAQTotal.value = pageData.total || 0+ }// 判断是否还有更多数据hasMore.value = entries.value.length < (pageData.total || 0)currentPage++@@ -900,6 +1477,7 @@ const resetEditorForm = () => {editorForm.similar_questions = []editorForm.negative_questions = []editorForm.answers = []+ editorForm.tag_id = ''answerInput.value = ''similarInput.value = ''negativeInput.value = ''@@ -913,6 +1491,7 @@ const openEditor = (entry?: FAQEntry) => {editorForm.similar_questions = [...(entry.similar_questions || [])]editorForm.negative_questions = [...(entry.negative_questions || [])]editorForm.answers = [...(entry.answers || [])]+ editorForm.tag_id = entry.tag_id || ''} else {editorMode.value = 'create'currentEntryId.value = null@@ -982,14 +1561,21 @@ const handleSubmitEntry = async () => {savingEntry.value = truetry {+ const payload: FAQEntryPayload = {+ standard_question: editorForm.standard_question,+ similar_questions: [...editorForm.similar_questions],+ negative_questions: [...editorForm.negative_questions],+ answers: [...editorForm.answers],+ tag_id: editorForm.tag_id || '',+ }if (editorMode.value === 'create') {await upsertFAQEntries(props.kbId, {- entries: [editorForm],+ entries: [payload],mode: 'append',})MessagePlugin.success(t('knowledgeEditor.messages.createSuccess'))} else if (currentEntryId.value) {- await updateFAQEntry(props.kbId, currentEntryId.value, editorForm)+ await updateFAQEntry(props.kbId, currentEntryId.value, payload)MessagePlugin.success(t('knowledgeEditor.messages.updateSuccess'))}editorVisible.value = false@@ -1006,6 +1592,51 @@ const handleBatchDelete = async () => {try {await deleteFAQEntries(props.kbId, selectedRowKeys.value)MessagePlugin.success(t('knowledgeEditor.faqImport.deleteSuccess'))+ selectedRowKeys.value = []+ await loadEntries()+ } catch (error: any) {+ MessagePlugin.error(error?.message || t('common.operationFailed'))+ }+}++// 批量状态更新对话框+const batchTagDialogVisible = ref(false)+const batchTagValue = ref<string>('')++const openBatchTagDialog = () => {+ if (!selectedRowKeys.value.length) return+ batchTagValue.value = ''+ batchTagDialogVisible.value = true+}++const handleBatchTag = async () => {+ if (!selectedRowKeys.value.length || !props.kbId) return+ try {+ const updates: Record<string, string | null> = {}+ selectedRowKeys.value.forEach(id => {+ updates[id] = batchTagValue.value || null+ })+ await updateFAQEntryTagBatch(props.kbId, { updates })+ MessagePlugin.success(t('knowledgeEditor.messages.updateSuccess'))+ batchTagDialogVisible.value = false+ selectedRowKeys.value = []+ await loadEntries()+ await loadTags()+ } catch (error: any) {+ MessagePlugin.error(error?.message || t('common.operationFailed'))+ }+}++const handleBatchStatusChange = async (isEnabled: boolean) => {+ if (!selectedRowKeys.value.length || !props.kbId) return+ try {+ const updates: Record<string, boolean> = {}+ selectedRowKeys.value.forEach(id => {+ updates[id] = isEnabled+ })+ await updateFAQEntryStatusBatch(props.kbId, { updates })+ MessagePlugin.success(t(isEnabled ? 'knowledgeEditor.faq.statusEnableSuccess' : 'knowledgeEditor.faq.statusDisableSuccess'))+ selectedRowKeys.value = []await loadEntries()} catch (error: any) {MessagePlugin.error(error?.message || t('common.operationFailed'))@@ -1169,6 +1800,7 @@ const normalizePayload = (payload: Partial<FAQEntryPayload>): FAQEntryPayload =>answers: payload.answers?.filter(Boolean) || [],similar_questions: payload.similar_questions?.filter(Boolean) || [],negative_questions: payload.negative_questions?.filter(Boolean) || [],+ tag_id: payload.tag_id || '',})const handleImport = async () => {@@ -1291,11 +1923,26 @@ watch(() => {currentPage = 1hasMore.value = true+ selectedTagId.value = ''+ cancelCreateTag()+ cancelEditTag()+ tagSearchQuery.value = ''loadEntries()+ loadTags()},{ immediate: true },)+watch(selectedTagId, (newVal, oldVal) => {+ if (oldVal === undefined) return+ if (newVal !== oldVal) {+ currentPage = 1+ entries.value = []+ selectedRowKeys.value = []+ loadEntries()+ }+})+const handleSearch = async () => {if (!searchForm.query.trim()) {MessagePlugin.warning(t('knowledgeEditor.faq.queryPlaceholder'))@@ -1450,72 +2097,467 @@ const arrangeCards = () => {})}-// 监听窗口大小变化(使用防抖)-let resizeTimer: ReturnType<typeof setTimeout> | null = null-const handleResize = () => {- if (resizeTimer) {- clearTimeout(resizeTimer)+// 监听窗口大小变化(使用防抖)+let resizeTimer: ReturnType<typeof setTimeout> | null = null+const handleResize = () => {+ if (resizeTimer) {+ clearTimeout(resizeTimer)+ }+ resizeTimer = setTimeout(() => {+ arrangeCards()+ resizeTimer = null+ }, 150)+}++onMounted(() => {+ if (props.kbId) {+ loadEntries()+ }+ window.addEventListener('resize', handleResize)+})++onUnmounted(() => {+ window.removeEventListener('resize', handleResize)+ if (arrangeCardsTimer) {+ clearTimeout(arrangeCardsTimer)+ }+ if (resizeTimer) {+ clearTimeout(resizeTimer)+ }+})++// 监听 entries 变化,重新布局+watch(() => entries.value.length, () => {+ nextTick(() => {+ arrangeCards()+ })+})++// 监听折叠状态变化,重新布局(使用防抖和动画完成后的回调)+watch(() => entries.value.map(e => ({+ id: e.id,+ similarCollapsed: e.similarCollapsed,+ negativeCollapsed: e.negativeCollapsed,+ answersCollapsed: e.answersCollapsed+})), () => {+ // 使用 nextTick 确保 DOM 更新+ nextTick(() => {+ // 等待一个渲染帧,让高度变化生效+ requestAnimationFrame(() => {+ // 再等待一个渲染帧,确保高度计算准确+ requestAnimationFrame(() => {+ // 等待 Transition 动画完成后再布局(slide-down 动画时长约 200ms)+ // 使用防抖避免频繁调用+ debounceArrangeCards(250)+ })+ })+ })+}, { deep: true })+</script>++<style lang="less">+.tag-more-popup {+ z-index: 99 !important;++ .t-popup__content {+ padding: 4px 0 !important;+ margin-top: 4px !important;+ min-width: 120px;+ }+}+</style>+<style scoped lang="less">+.faq-manager {+ display: flex;+ flex-direction: column;+ height: 100%;+}++.fade-enter-active,+.fade-leave-active {+ transition: opacity 0.15s ease;+}++.fade-enter-from,+.fade-leave-to {+ opacity: 0;+}++.faq-content {+ flex: 1;+ display: flex;+ flex-direction: column;+ min-height: 0;+}++.faq-main {+ display: flex;+ gap: 16px;+ flex: 1;+ min-height: 0;+}++.faq-tag-panel {+ width: 230px;+ background: #fff;+ border: 1px solid #e7ebf0;+ border-radius: 12px;+ padding: 16px;+ flex-shrink: 0;+ display: flex;+ flex-direction: column;++ .sidebar-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin-bottom: 12px;+ color: #1d2129;++ .sidebar-title {+ display: flex;+ align-items: baseline;+ gap: 4px;+ font-weight: 600;++ .sidebar-count {+ font-size: 12px;+ color: #86909c;+ }+ }++ .sidebar-actions {+ display: flex;+ gap: 8px;+ color: #c9ced6;++ .create-tag-btn {+ width: 28px;+ height: 28px;+ padding: 0;+ border-radius: 6px;+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 18px;+ font-weight: 600;+ color: #00a870;+ line-height: 1;+ transition: background 0.2s ease, color 0.2s ease;++ &:hover {+ background: #f3f5f7;+ color: #05a04f;+ }+ }++ .create-tag-plus {+ line-height: 1;+ }++ .sidebar-action-icon {+ width: 28px;+ height: 28px;+ border-radius: 6px;+ display: flex;+ align-items: center;+ justify-content: center;+ cursor: pointer;+ transition: background 0.2s ease, color 0.2s ease;++ &:hover {+ background: #f3f5f7;+ color: #00a870;+ }+ }+ }+ }++ .tag-search-bar {+ margin-bottom: 12px;++ :deep(.t-input) {+ font-size: 12px;+ background-color: #f7f9fc;+ border-color: #e5e9f2;+ }+ }++ .faq-tag-list {+ display: flex;+ flex-direction: column;+ gap: 6px;+ overflow: auto;++ .faq-tag-item {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 8px 10px;+ border-radius: 6px;+ color: #4e5969;+ cursor: pointer;+ transition: all 0.2s ease;+ font-size: 13px;++ .faq-tag-left {+ display: flex;+ align-items: center;+ gap: 8px;+ min-width: 0;+ flex: 1;++ .t-icon {+ flex-shrink: 0;+ color: #86909c;+ font-size: 16px;+ transition: color 0.2s ease;+ }+ }++ .tag-name {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-weight: 400;+ }++ .faq-tag-right {+ display: flex;+ align-items: center;+ gap: 6px;+ margin-left: 8px;+ min-width: 0;+ flex-shrink: 0;+ }++ .faq-tag-count {+ font-size: 12px;+ color: #86909c;+ font-weight: 500;+ padding: 2px 6px;+ border-radius: 10px;+ background: #f7f9fc;+ transition: all 0.2s ease;+ }++ &:hover {+ background: #f7f9fc;+ color: #1d2129;++ .faq-tag-left .t-icon {+ color: #4e5969;+ }++ .faq-tag-count {+ background: #e5e9f2;+ color: #4e5969;+ }+ }++ &.active {+ background: #e6f7ec;+ color: #00a870;+ font-weight: 500;++ .faq-tag-left .t-icon {+ color: #00a870;+ }++ .faq-tag-count {+ background: #b8f0d3;+ color: #00a870;+ font-weight: 600;+ }++ &:hover {+ background: #d4f4e3;+ }+ }++ &.editing {+ background: transparent;+ border: none;+ }++ &.tag-editing {+ cursor: default;+ padding-right: 8px;+ background: transparent;+ border: none;++ .tag-edit-input {+ flex: 1;+ }+ }++ &.tag-editing .tag-edit-input {+ width: 100%;+ }++ .tag-inline-actions {+ display: flex;+ gap: 4px;+ margin-left: auto;++ :deep(.t-button) {+ padding: 0 4px;+ height: 24px;+ }++ :deep(.tag-action-btn) {+ border-radius: 4px;+ transition: all 0.2s ease;++ .t-icon {+ font-size: 14px;+ }+ }++ :deep(.tag-action-btn.confirm) {+ background: #eefcf5;+ color: #059669;++ &:hover {+ background: #d9f7e9;+ color: #047857;+ }+ }++ :deep(.tag-action-btn.cancel) {+ background: #f9fafb;+ color: #6b7280;++ &:hover {+ background: #f3f4f6;+ color: #4b5563;+ }+ }+ }++ .tag-edit-input {+ flex: 1;+ min-width: 0;+ max-width: 100%;++ :deep(.t-input) {+ font-size: 12px;+ background-color: transparent;+ border: none;+ border-bottom: 1px solid #d0d5dd;+ border-radius: 0;+ box-shadow: none;+ padding-left: 0;+ padding-right: 0;+ }++ :deep(.t-input__wrap) {+ background-color: transparent;+ border: none;+ border-bottom: 1px solid #d0d5dd;+ border-radius: 0;+ box-shadow: none;+ }++ :deep(.t-input__inner) {+ padding-left: 0;+ padding-right: 0;+ color: #1d2129;+ caret-color: #1d2129;+ }++ :deep(.t-input:hover),+ :deep(.t-input.t-is-focused),+ :deep(.t-input__wrap:hover),+ :deep(.t-input__wrap.t-is-focused) {+ border-bottom-color: #00a870;+ }+ }++ .tag-more-btn {+ width: 24px;+ height: 24px;+ display: flex;+ align-items: center;+ justify-content: center;+ border-radius: 4px;+ color: #86909c;+ transition: all 0.2s ease;+ opacity: 0.6;++ &:hover {+ background: #f3f5f7;+ color: #4e5969;+ opacity: 1;+ }+ }+++ .tag-more {+ display: flex;+ align-items: center;+ }+ }++ .tag-empty-state {+ text-align: center;+ padding: 12px 8px;+ color: #a1a7b3;+ font-size: 12px;+ }}- resizeTimer = setTimeout(() => {- arrangeCards()- resizeTimer = null- }, 150)}-onMounted(() => {- if (props.kbId) {- loadEntries()- }- window.addEventListener('resize', handleResize)-})+.faq-card-area {+ flex: 1;+ min-width: 0;+ min-height: 0;+ display: flex;+ flex-direction: column;+}-onUnmounted(() => {- window.removeEventListener('resize', handleResize)- if (arrangeCardsTimer) {- clearTimeout(arrangeCardsTimer)+:deep(.tag-menu) {+ display: flex;+ flex-direction: column;+}++:deep(.tag-menu-item) {+ display: flex;+ align-items: center;+ padding: 8px 16px;+ cursor: pointer;+ transition: all 0.2s ease;+ color: #000000e6;+ font-family: "PingFang SC";+ font-size: 14px;+ font-weight: 400;++ .menu-icon {+ margin-right: 8px;+ font-size: 16px;}- if (resizeTimer) {- clearTimeout(resizeTimer)++ &:hover {+ background: #f5f5f5;+ color: #000000e6;}-})-// 监听 entries 变化,重新布局-watch(() => entries.value.length, () => {- nextTick(() => {- arrangeCards()- })-})+ &.danger {+ color: #000000e6;-// 监听折叠状态变化,重新布局(使用防抖和动画完成后的回调)-watch(() => entries.value.map(e => ({- id: e.id,- similarCollapsed: e.similarCollapsed,- negativeCollapsed: e.negativeCollapsed,- answersCollapsed: e.answersCollapsed-})), () => {- // 使用 nextTick 确保 DOM 更新- nextTick(() => {- // 等待一个渲染帧,让高度变化生效- requestAnimationFrame(() => {- // 再等待一个渲染帧,确保高度计算准确- requestAnimationFrame(() => {- // 等待 Transition 动画完成后再布局(slide-down 动画时长约 200ms)- // 使用防抖避免频繁调用- debounceArrangeCards(250)- })- })- })-}, { deep: true })-</script>+ &:hover {+ background: #fff1f0;+ color: #fa5151;-<style scoped lang="less">-.faq-manager {- display: flex;- flex-direction: column;- height: 100%;+ .menu-icon {+ color: #fa5151;+ }+ }+ }}-// Header 样式.faq-header {display: flex;align-items: center;@@ -1548,6 +2590,18 @@ watch(() => entries.value.map(e => ({}}+.tag-filter-bar {+ display: flex;+ align-items: center;+ gap: 12px;+ margin-bottom: 12px;++ .tag-filter-label {+ color: #6B7280;+ font-size: 14px;+ }+}+.action-buttons {display: flex;gap: 12px;@@ -1659,13 +2713,176 @@ watch(() => entries.value.map(e => ({.faq-card-header {display: flex;- align-items: flex-start;- gap: 8px;- padding-bottom: 8px;+ flex-direction: column;+ gap: 10px;+ padding-bottom: 12px;border-bottom: 1px solid #F3F4F6;position: relative;}+.faq-header-top {+ display: flex;+ align-items: flex-start;+ gap: 12px;+}++.faq-card-actions {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-left: auto;+ flex-shrink: 0;+}++.faq-header-meta {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 10px;+ padding-top: 6px;+ border-top: 1px dashed #F3F4F6;+}++.faq-meta-item {+ display: inline-flex;+ align-items: baseline;+ gap: 6px;+ padding: 4px 10px;+ border-radius: 999px;+ background: #F9FAFB;+ border: 1px solid #EEF2F7;++ .meta-label {+ font-size: 12px;+ color: #6B7280;+ font-weight: 500;+ }++ .meta-value {+ font-size: 13px;+ color: #111827;+ font-weight: 600;+ }+}++.faq-card-footer {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding-top: 12px;+ border-top: 1px solid #F3F4F6;+ flex-wrap: wrap;+}++.faq-card-status {+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+ flex: 1;+ min-width: 0;+}++.status-item {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 4px 10px;+ border-radius: 999px;+ background: #F9FAFB;+ border: 1px solid #EEF2F7;+ font-size: 12px;+ color: #4B5563;+ font-family: "PingFang SC";++ .status-icon {+ font-size: 14px;+ color: #9CA3AF;++ &.warning {+ color: #F97316;+ }++ &.success {+ color: #10B981;+ }+ }+}++.status-item-compact {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 4px 8px;+ border-radius: 6px;+ background: #F9FAFB;+ border: 1px solid #EEF2F7;+ cursor: pointer;+ transition: all 0.2s ease;++ &:hover {+ background: #F3F4F6;+ border-color: #D1D5DB;+ }++ .status-icon {+ font-size: 16px;+ flex-shrink: 0;++ &.warning {+ color: #F97316;+ }++ &.success {+ color: #10B981;+ }+ }++ :deep(.t-switch) {+ flex-shrink: 0;+ }+}++.faq-card-tag {+ display: flex;+ align-items: center;+ justify-content: flex-end;+ flex-shrink: 0;++ :deep(.t-tag) {+ display: inline-flex;+ align-items: center;+ cursor: pointer;+ max-width: 170px;+ border-radius: 999px;+ border-color: #e5e7eb;+ color: #374151;+ padding: 0 12px;+ background: #f9fafb;+ transition: all 0.2s ease;++ &:hover {+ border-color: #07c05f;+ color: #059669;+ background: #ecfdf5;+ }+ }+}++.faq-tag-chip {+ display: inline-flex;+ align-items: center;+ cursor: pointer;++ .tag-text {+ max-width: 160px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: 12px;+ }+}+.card-more-btn {display: flex;width: 28px;@@ -1675,7 +2892,6 @@ watch(() => entries.value.map(e => ({border-radius: 6px;cursor: pointer;flex-shrink: 0;- margin-left: auto;opacity: 0.6;&:hover {@@ -1683,6 +2899,10 @@ watch(() => entries.value.map(e => ({opacity: 1;}+ &.mobile {+ display: none;+ }+.more-icon {width: 16px;height: 16px;@@ -1692,39 +2912,41 @@ watch(() => entries.value.map(e => ({.card-menu {display: flex;flex-direction: column;- min-width: 140px;- padding: 4px;- border-radius: 8px;}.card-menu-item {display: flex;align-items: center;- gap: 10px;- padding: 10px 14px;+ padding: 8px 16px;cursor: pointer;- color: #111827;+ transition: all 0.2s ease;+ color: #000000e6;font-family: "PingFang SC";font-size: 14px;- border-radius: 6px;+ font-weight: 400;++ .menu-icon {+ margin-right: 8px;+ font-size: 16px;+ flex-shrink: 0;+ }&:hover {- background: #F3F4F6;- color: #07C05F;+ background: #f5f5f5;+ color: #000000e6;}&.danger {- color: #EF4444;+ color: #000000e6;&:hover {- background: #FEE2E2;- color: #DC2626;- }- }+ background: #fff1f0;+ color: #fa5151;- .menu-icon {- font-size: 16px;- flex-shrink: 0;+ .menu-icon {+ color: #fa5151;+ }+ }}}@@ -3351,6 +4573,28 @@ watch(() => entries.value.map(e => ({gap: 8px;}+.batch-tag-dialog-content {+ padding: 8px 0;+}++.batch-tag-dialog-tip {+ margin: 0 0 20px 0;+ font-size: 14px;+ color: #4e5969;+ line-height: 1.5;+}++.batch-tag-form {+ margin-top: 0;+}++.tag-select-empty {+ padding: 8px 12px;+ text-align: center;+ color: #86909c;+ font-size: 14px;+}+.section-label {font-family: "PingFang SC";font-size: 12px;diff --git a/internal/application/repository/chunk.go b/internal/application/repository/chunk.goindex e75fa5c5c..72487b659 100644--- a/internal/application/repository/chunk.go+++ b/internal/application/repository/chunk.go@@ -93,7 +93,7 @@ func (r *chunkRepository) ListPagedChunksByKnowledgeID(// Then query the paginated datadataQuery := r.db.WithContext(ctx).- Select("id, content, knowledge_id, knowledge_base_id, start_at, end_at, chunk_index, is_enabled, chunk_type, parent_chunk_id, image_info, metadata")+ Select("id, content, knowledge_id, knowledge_base_id, start_at, end_at, chunk_index, is_enabled, chunk_type, parent_chunk_id, image_info, metadata, tag_id")dataQuery = dataQuery.Where("tenant_id = ? AND knowledge_id = ? AND chunk_type IN (?)", tenantID, knowledgeID, chunkType)if tagID != "" {dataQuery = dataQuery.Where("tag_id = ?", tagID)@@ -125,6 +125,17 @@ func (r *chunkRepository) UpdateChunk(ctx context.Context, chunk *types.Chunk) ereturn r.db.WithContext(ctx).Save(chunk).Error}+// UpdateChunks updates chunks in batch+func (r *chunkRepository) UpdateChunks(ctx context.Context, chunks []*types.Chunk) error {+ if len(chunks) == 0 {+ return nil+ }+ for _, chunk := range chunks {+ chunk.Content = common.CleanInvalidUTF8(chunk.Content)+ }+ return r.db.WithContext(ctx).Save(chunks).Error+}+// DeleteChunk deletes a chunk by its IDfunc (r *chunkRepository) DeleteChunk(ctx context.Context, tenantID uint, id string) error {return r.db.WithContext(ctx).Where("tenant_id = ? AND id = ?", tenantID, id).Delete(&types.Chunk{}).Errordiff --git a/internal/application/repository/knowledge.go b/internal/application/repository/knowledge.goindex 1818ff128..b1b46389b 100644--- a/internal/application/repository/knowledge.go+++ b/internal/application/repository/knowledge.go@@ -97,6 +97,14 @@ func (r *knowledgeRepository) UpdateKnowledge(ctx context.Context, knowledge *tyreturn err}+// UpdateKnowledgeBatch updates knowledge items in batch+func (r *knowledgeRepository) UpdateKnowledgeBatch(ctx context.Context, knowledgeList []*types.Knowledge) error {+ if len(knowledgeList) == 0 {+ return nil+ }+ return r.db.WithContext(ctx).Save(knowledgeList).Error+}+// DeleteKnowledge deletes knowledgefunc (r *knowledgeRepository) DeleteKnowledge(ctx context.Context, tenantID uint, id string) error {return r.db.WithContext(ctx).Where("tenant_id = ? AND id = ?", tenantID, id).Delete(&types.Knowledge{}).Errordiff --git a/internal/application/repository/retriever/elasticsearch/structs.go b/internal/application/repository/retriever/elasticsearch/structs.goindex b30b8bbce..08e1bcd0b 100644--- a/internal/application/repository/retriever/elasticsearch/structs.go+++ b/internal/application/repository/retriever/elasticsearch/structs.go@@ -16,6 +16,7 @@ type VectorEmbedding struct {KnowledgeID string `json:"knowledge_id" gorm:"column:knowledge_id"` // ID of the knowledge itemKnowledgeBaseID string `json:"knowledge_base_id" gorm:"column:knowledge_base_id"` // ID of the knowledge baseEmbedding []float32 `json:"embedding" gorm:"column:embedding;not null"` // Vector embedding of the content+ IsEnabled bool `json:"is_enabled"` // Whether the chunk is enabled}// VectorEmbeddingWithScore extends VectorEmbedding with similarity score@@ -33,6 +34,7 @@ func ToDBVectorEmbedding(embedding *types.IndexInfo, additionalParams map[stringChunkID: embedding.ChunkID,KnowledgeID: embedding.KnowledgeID,KnowledgeBaseID: embedding.KnowledgeBaseID,+ IsEnabled: true, // Default to enabled}// Add embedding data if available in additionalParamsif additionalParams != nil && slices.Contains(slices.Collect(maps.Keys(additionalParams)), "embedding") {@@ -40,6 +42,14 @@ func ToDBVectorEmbedding(embedding *types.IndexInfo, additionalParams map[stringvector.Embedding = embeddingMap[embedding.SourceID]}}+ // Get is_enabled from additionalParams if available+ if additionalParams != nil {+ if chunkEnabledMap, ok := additionalParams["chunk_enabled"].(map[string]bool); ok {+ if enabled, exists := chunkEnabledMap[embedding.ChunkID]; exists {+ vector.IsEnabled = enabled+ }+ }+ }return vector}diff --git a/internal/application/repository/retriever/elasticsearch/v7/repository.go b/internal/application/repository/retriever/elasticsearch/v7/repository.goindex cfa2bfe53..7c9387301 100644--- a/internal/application/repository/retriever/elasticsearch/v7/repository.go+++ b/internal/application/repository/retriever/elasticsearch/v7/repository.go@@ -330,7 +330,7 @@ func (e *elasticsearchRepository) deleteByFieldList(ctx context.Context, field sif resp.IsError() {errMsg := fmt.Sprintf("failed to delete by query: %s", resp.String())log.Errorf("[ElasticsearchV7] %s", errMsg)- return fmt.Errorf(errMsg)+ return fmt.Errorf("failed to delete by query: %s", resp.String())}// Try to extract deletion count from response@@ -361,6 +361,9 @@ func (e *elasticsearchRepository) getBaseConds(params typesLocal.RetrieveParams)// Build MUST_NOT conditions (negative filters)mustNot := make([]string, 0)+ // Exclude disabled chunks (is_enabled = false)+ // Note: Historical data without is_enabled field will be included (not matching must_not)+ mustNot = append(mustNot, `{"term": {"is_enabled": false}}`)if len(params.ExcludeKnowledgeIDs) > 0 {ids, _ := json.Marshal(params.ExcludeKnowledgeIDs)mustNot = append(mustNot, fmt.Sprintf(`{"terms": {"knowledge_id.keyword": %s}}`, ids))@@ -371,17 +374,17 @@ func (e *elasticsearchRepository) getBaseConds(params typesLocal.RetrieveParams)}// Combine conditions based on presence- switch {- case len(must) == 0 && len(mustNot) == 0:+ if len(must) == 0 && len(mustNot) == 0 {return "{}" // Empty query if no conditions- case len(must) == 0:+ }+ if len(must) == 0 {return fmt.Sprintf(`{"bool": {"must_not": [%s]}}`, strings.Join(mustNot, ","))- case len(mustNot) == 0:+ }+ if len(mustNot) == 0 {return fmt.Sprintf(`{"bool": {"must": [%s]}}`, strings.Join(must, ","))- default:- return fmt.Sprintf(`{"bool": {"must": [%s], "must_not": [%s]}}`,- strings.Join(must, ","), strings.Join(mustNot, ","))}+ return fmt.Sprintf(`{"bool": {"must": [%s], "must_not": [%s]}}`,+ strings.Join(must, ","), strings.Join(mustNot, ","))}func (e *elasticsearchRepository) Retrieve(ctx context.Context,@@ -1028,3 +1031,99 @@ func (e *elasticsearchRepository) saveCopiedIndices(ctx context.Context, indexInlog.Infof("[ElasticsearchV7] Successfully saved %d indices", len(indexInfoList))return nil}++// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch+func (e *elasticsearchRepository) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {+ log := logger.GetLogger(ctx)+ if len(chunkStatusMap) == 0 {+ log.Warnf("[ElasticsearchV7] Chunk status map is empty, skipping update")+ return nil+ }++ log.Infof("[ElasticsearchV7] Batch updating chunk enabled status, count: %d", len(chunkStatusMap))++ // Group chunks by enabled status for batch updates+ enabledChunkIDs := make([]string, 0)+ disabledChunkIDs := make([]string, 0)++ for chunkID, enabled := range chunkStatusMap {+ if enabled {+ enabledChunkIDs = append(enabledChunkIDs, chunkID)+ } else {+ disabledChunkIDs = append(disabledChunkIDs, chunkID)+ }+ }++ // Batch update enabled chunks using update_by_query+ if len(enabledChunkIDs) > 0 {+ query := map[string]interface{}{+ "query": map[string]interface{}{+ "terms": map[string]interface{}{+ "chunk_id.keyword": enabledChunkIDs,+ },+ },+ "script": map[string]interface{}{+ "source": "ctx._source.is_enabled = true",+ "lang": "painless",+ },+ }+ queryJSON, _ := json.Marshal(query)+ res, err := esapi.UpdateByQueryRequest{+ Index: []string{e.index},+ Body: strings.NewReader(string(queryJSON)),+ }.Do(ctx, e.client)+ if err != nil {+ log.Errorf("[ElasticsearchV7] Failed to update enabled chunks: %v", err)+ return err+ }+ defer res.Body.Close()+ if res.IsError() {+ var e map[string]interface{}+ if err := json.NewDecoder(res.Body).Decode(&e); err != nil {+ log.Errorf("[ElasticsearchV7] Error parsing the response body: %v", err)+ } else {+ log.Errorf("[ElasticsearchV7] Error updating enabled chunks: %v", e["error"])+ }+ return fmt.Errorf("elasticsearch update_by_query failed with status: %d", res.StatusCode)+ }+ log.Infof("[ElasticsearchV7] Updated %d chunks to enabled", len(enabledChunkIDs))+ }++ // Batch update disabled chunks using update_by_query+ if len(disabledChunkIDs) > 0 {+ query := map[string]interface{}{+ "query": map[string]interface{}{+ "terms": map[string]interface{}{+ "chunk_id.keyword": disabledChunkIDs,+ },+ },+ "script": map[string]interface{}{+ "source": "ctx._source.is_enabled = false",+ "lang": "painless",+ },+ }+ queryJSON, _ := json.Marshal(query)+ res, err := esapi.UpdateByQueryRequest{+ Index: []string{e.index},+ Body: strings.NewReader(string(queryJSON)),+ }.Do(ctx, e.client)+ if err != nil {+ log.Errorf("[ElasticsearchV7] Failed to update disabled chunks: %v", err)+ return err+ }+ defer res.Body.Close()+ if res.IsError() {+ var e map[string]interface{}+ if err := json.NewDecoder(res.Body).Decode(&e); err != nil {+ log.Errorf("[ElasticsearchV7] Error parsing the response body: %v", err)+ } else {+ log.Errorf("[ElasticsearchV7] Error updating disabled chunks: %v", e["error"])+ }+ return fmt.Errorf("elasticsearch update_by_query failed with status: %d", res.StatusCode)+ }+ log.Infof("[ElasticsearchV7] Updated %d chunks to disabled", len(disabledChunkIDs))+ }++ log.Infof("[ElasticsearchV7] Successfully batch updated chunk enabled status")+ return nil+}diff --git a/internal/application/repository/retriever/elasticsearch/v8/repository.go b/internal/application/repository/retriever/elasticsearch/v8/repository.goindex 17c98835c..493120b88 100644--- a/internal/application/repository/retriever/elasticsearch/v8/repository.go+++ b/internal/application/repository/retriever/elasticsearch/v8/repository.go@@ -14,6 +14,7 @@ import ("github.com/elastic/go-elasticsearch/v8""github.com/elastic/go-elasticsearch/v8/typedapi/core/search""github.com/elastic/go-elasticsearch/v8/typedapi/types"+ "github.com/elastic/go-elasticsearch/v8/typedapi/types/enums/scriptlanguage")// elasticsearchRepository implements the RetrieveEngineRepository interface for Elasticsearch v8@@ -220,6 +221,11 @@ func (e *elasticsearchRepository) getBaseConds(params typesLocal.RetrieveParams)}})}mustNot := make([]types.Query, 0)+ // Exclude disabled chunks (is_enabled = false)+ // Note: Historical data without is_enabled field will be included (not matching must_not)+ mustNot = append(mustNot, types.Query{Term: map[string]types.TermQuery{+ "is_enabled": {Value: false},+ }})if len(params.ExcludeKnowledgeIDs) > 0 {mustNot = append(mustNot, types.Query{Terms: &types.TermsQuery{TermsQuery: map[string]types.TermsQueryField{"knowledge_id.keyword": params.ExcludeKnowledgeIDs},@@ -539,3 +545,81 @@ func (e *elasticsearchRepository) CopyIndices(ctx context.Context,log.Infof("[Elasticsearch] Index copy completed, total copied: %d", totalCopied)return nil}++// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch+func (e *elasticsearchRepository) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {+ log := logger.GetLogger(ctx)+ if len(chunkStatusMap) == 0 {+ log.Warnf("[Elasticsearch] Chunk status map is empty, skipping update")+ return nil+ }++ log.Infof("[Elasticsearch] Batch updating chunk enabled status, count: %d", len(chunkStatusMap))++ // Group chunks by enabled status for batch updates+ enabledChunkIDs := make([]string, 0)+ disabledChunkIDs := make([]string, 0)++ for chunkID, enabled := range chunkStatusMap {+ if enabled {+ enabledChunkIDs = append(enabledChunkIDs, chunkID)+ } else {+ disabledChunkIDs = append(disabledChunkIDs, chunkID)+ }+ }++ // Batch update enabled chunks using update_by_query+ if len(enabledChunkIDs) > 0 {+ query := types.NewQuery()+ query.Bool = &types.BoolQuery{+ Must: []types.Query{+ {Terms: &types.TermsQuery{+ TermsQuery: map[string]types.TermsQueryField{+ "chunk_id.keyword": enabledChunkIDs,+ },+ }},+ },+ }+ source := "ctx._source.is_enabled = true"+ lang := scriptlanguage.Painless+ script := types.Script{+ Source: &source,+ Lang: &lang,+ }+ _, err := e.client.UpdateByQuery(e.index).Query(query).Script(&script).Do(ctx)+ if err != nil {+ log.Errorf("[Elasticsearch] Failed to update enabled chunks: %v", err)+ return err+ }+ log.Infof("[Elasticsearch] Updated %d chunks to enabled", len(enabledChunkIDs))+ }++ // Batch update disabled chunks using update_by_query+ if len(disabledChunkIDs) > 0 {+ query := types.NewQuery()+ query.Bool = &types.BoolQuery{+ Must: []types.Query{+ {Terms: &types.TermsQuery{+ TermsQuery: map[string]types.TermsQueryField{+ "chunk_id.keyword": disabledChunkIDs,+ },+ }},+ },+ }+ source := "ctx._source.is_enabled = false"+ lang := scriptlanguage.Painless+ script := types.Script{+ Source: &source,+ Lang: &lang,+ }+ _, err := e.client.UpdateByQuery(e.index).Query(query).Script(&script).Do(ctx)+ if err != nil {+ log.Errorf("[Elasticsearch] Failed to update disabled chunks: %v", err)+ return err+ }+ log.Infof("[Elasticsearch] Updated %d chunks to disabled", len(disabledChunkIDs))+ }++ log.Infof("[Elasticsearch] Successfully batch updated chunk enabled status")+ return nil+}diff --git a/internal/application/repository/retriever/postgres/repository.go b/internal/application/repository/retriever/postgres/repository.goindex 9d2931786..f6c3f8e0f 100644--- a/internal/application/repository/retriever/postgres/repository.go+++ b/internal/application/repository/retriever/postgres/repository.go@@ -159,6 +159,11 @@ func (g *pgRepository) KeywordsRetrieve(ctx context.Context,SQL: "id @@@ paradedb.match(field => 'content', value => ?, distance => 1)",Vars: []interface{}{params.Query},})+ // Filter by is_enabled = true or NULL (NULL means enabled for historical data)+ conds = append(conds, clause.Expr{+ SQL: "(is_enabled IS NULL OR is_enabled = ?)",+ Vars: []interface{}{true},+ })conds = append(conds, clause.OrderBy{Columns: []clause.OrderByColumn{{Column: clause.Column{Name: "score"}, Desc: true},}})@@ -227,6 +232,11 @@ func (g *pgRepository) VectorRetrieve(ctx context.Context,// <#> Inner product operatordimension := len(params.Embedding)conds = append(conds, clause.Expr{SQL: "dimension = ?", Vars: []interface{}{dimension}})+ // Filter by is_enabled = true or NULL (NULL means enabled for historical data)+ conds = append(conds, clause.Expr{+ SQL: "(is_enabled IS NULL OR is_enabled = ?)",+ Vars: []interface{}{true},+ })conds = append(conds, clause.Expr{SQL: fmt.Sprintf("embedding::halfvec(%d) <=> ?::halfvec < ?", dimension),Vars: []interface{}{pgvector.NewHalfVector(params.Embedding), 1 - params.Threshold},@@ -388,3 +398,52 @@ func (g *pgRepository) CopyIndices(ctx context.Context,logger.GetLogger(ctx).Infof("[Postgres] Index copying completed, total copied: %d", totalCopied)return nil}++// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch+func (g *pgRepository) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {+ if len(chunkStatusMap) == 0 {+ logger.GetLogger(ctx).Warnf("[Postgres] Chunk status map is empty, skipping update")+ return nil+ }++ logger.GetLogger(ctx).Infof("[Postgres] Batch updating chunk enabled status, count: %d", len(chunkStatusMap))++ // Group chunks by enabled status for batch updates+ enabledChunkIDs := make([]string, 0)+ disabledChunkIDs := make([]string, 0)++ for chunkID, enabled := range chunkStatusMap {+ if enabled {+ enabledChunkIDs = append(enabledChunkIDs, chunkID)+ } else {+ disabledChunkIDs = append(disabledChunkIDs, chunkID)+ }+ }++ // Batch update enabled chunks+ if len(enabledChunkIDs) > 0 {+ result := g.db.WithContext(ctx).Model(&pgVector{}).+ Where("chunk_id IN ?", enabledChunkIDs).+ Update("is_enabled", true)+ if result.Error != nil {+ logger.GetLogger(ctx).Errorf("[Postgres] Failed to update enabled chunks: %v", result.Error)+ return result.Error+ }+ logger.GetLogger(ctx).Infof("[Postgres] Updated %d chunks to enabled, rows affected: %d", len(enabledChunkIDs), result.RowsAffected)+ }++ // Batch update disabled chunks+ if len(disabledChunkIDs) > 0 {+ result := g.db.WithContext(ctx).Model(&pgVector{}).+ Where("chunk_id IN ?", disabledChunkIDs).+ Update("is_enabled", false)+ if result.Error != nil {+ logger.GetLogger(ctx).Errorf("[Postgres] Failed to update disabled chunks: %v", result.Error)+ return result.Error+ }+ logger.GetLogger(ctx).Infof("[Postgres] Updated %d chunks to disabled, rows affected: %d", len(disabledChunkIDs), result.RowsAffected)+ }++ logger.GetLogger(ctx).Infof("[Postgres] Successfully batch updated chunk enabled status")+ return nil+}diff --git a/internal/application/repository/retriever/postgres/structs.go b/internal/application/repository/retriever/postgres/structs.goindex 45fbc0ee7..915d43b6a 100644--- a/internal/application/repository/retriever/postgres/structs.go+++ b/internal/application/repository/retriever/postgres/structs.go@@ -24,6 +24,7 @@ type pgVector struct {Content string `json:"content" gorm:"column:content;not null"`Dimension int `json:"dimension" gorm:"column:dimension;not null"`Embedding pgvector.HalfVector `json:"embedding" gorm:"column:embedding;not null"`+ IsEnabled bool `json:"is_enabled" gorm:"column:is_enabled;default:true;index"`}// pgVectorWithScore extends pgVector with similarity score field@@ -39,6 +40,7 @@ type pgVectorWithScore struct {Content string `json:"content" gorm:"column:content;not null"`Dimension int `json:"dimension" gorm:"column:dimension;not null"`Embedding pgvector.HalfVector `json:"embedding" gorm:"column:embedding;not null"`+ IsEnabled bool `json:"is_enabled" gorm:"column:is_enabled;default:true;index"`Score float64 `json:"score" gorm:"column:score"`}@@ -61,6 +63,7 @@ func toDBVectorEmbedding(indexInfo *types.IndexInfo, additionalParams map[stringKnowledgeID: indexInfo.KnowledgeID,KnowledgeBaseID: indexInfo.KnowledgeBaseID,Content: common.CleanInvalidUTF8(indexInfo.Content),+ IsEnabled: true, // Default to enabled}// Add embedding data if available in additionalParamsif additionalParams != nil && slices.Contains(slices.Collect(maps.Keys(additionalParams)), "embedding") {@@ -69,6 +72,14 @@ func toDBVectorEmbedding(indexInfo *types.IndexInfo, additionalParams map[stringpgVector.Dimension = len(pgVector.Embedding.Slice())}}+ // Get is_enabled from additionalParams if available+ if additionalParams != nil {+ if chunkEnabledMap, ok := additionalParams["chunk_enabled"].(map[string]bool); ok {+ if enabled, exists := chunkEnabledMap[indexInfo.ChunkID]; exists {+ pgVector.IsEnabled = enabled+ }+ }+ }return pgVector}diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.goindex 4824e065a..f1072d70c 100644--- a/internal/application/service/agent_service.go+++ b/internal/application/service/agent_service.go@@ -307,7 +307,7 @@ func (s *agentService) getKnowledgeBaseInfos(ctx context.Context, kbIDs []stringpageResult, err := s.knowledgeService.ListFAQEntries(ctx, kbID, &types.Pagination{Page: 1,PageSize: 10,- })+ }, "")if err == nil && pageResult != nil {docCount = int(pageResult.Total)if entries, ok := pageResult.Data.([]*types.FAQEntry); ok {@@ -336,7 +336,7 @@ func (s *agentService) getKnowledgeBaseInfos(ctx context.Context, kbIDs []stringpageResult, err := s.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbID, &types.Pagination{Page: 1,PageSize: 10,- })+ }, "")if err == nil && pageResult != nil {docCount = int(pageResult.Total)diff --git a/internal/application/service/knowledge.go b/internal/application/service/knowledge.goindex 3361d7d17..30dae26d5 100644--- a/internal/application/service/knowledge.go+++ b/internal/application/service/knowledge.go@@ -61,6 +61,7 @@ type knowledgeService struct {docReaderClient *client.ClientchunkService interfaces.ChunkServicechunkRepo interfaces.ChunkRepository+ tagRepo interfaces.KnowledgeTagRepositoryfileSvc interfaces.FileServicemodelService interfaces.ModelServicetask *asynq.Client@@ -81,6 +82,7 @@ func NewKnowledgeService(tenantRepo interfaces.TenantRepository,chunkService interfaces.ChunkService,chunkRepo interfaces.ChunkRepository,+ tagRepo interfaces.KnowledgeTagRepository,fileSvc interfaces.FileService,modelService interfaces.ModelService,task *asynq.Client,@@ -95,6 +97,7 @@ func NewKnowledgeService(docReaderClient: docReaderClient,chunkService: chunkService,chunkRepo: chunkRepo,+ tagRepo: tagRepo,fileSvc: fileSvc,modelService: modelService,task: task,@@ -2120,6 +2123,10 @@ func (s *knowledgeService) UpsertFAQEntries(ctx context.Context,if err != nil {return err}+ isEnabled := true+ if entry.IsEnabled != nil {+ isEnabled = *entry.IsEnabled+ }chunk := &types.Chunk{ID: uuid.New().String(),TenantID: tenantID,@@ -2127,7 +2134,7 @@ func (s *knowledgeService) UpsertFAQEntries(ctx context.Context,KnowledgeBaseID: kb.ID,Content: buildFAQChunkContent(meta, indexMode),ChunkIndex: startIndex + idx + 1,- IsEnabled: true,+ IsEnabled: isEnabled,ChunkType: types.ChunkTypeFAQ,TagID: entry.TagID,}@@ -2191,10 +2198,30 @@ func (s *knowledgeService) UpdateFAQEntry(ctx context.Context,}chunk.Content = buildFAQChunkContent(meta, indexMode)chunk.TagID = payload.TagID+ isEnabledUpdated := false+ if payload.IsEnabled != nil {+ oldEnabled := chunk.IsEnabled+ chunk.IsEnabled = *payload.IsEnabled+ isEnabledUpdated = (oldEnabled != chunk.IsEnabled)+ }chunk.UpdatedAt = time.Now()if err := s.chunkService.UpdateChunk(ctx, chunk); err != nil {return err}++ // Sync is_enabled status to retriever engines if it was updated+ if isEnabledUpdated {+ chunkStatusMap := map[string]bool{chunk.ID: chunk.IsEnabled}+ tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)+ retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.RetrieverEngines.Engines)+ if err != nil {+ return err+ }+ if err := retrieveEngine.BatchUpdateChunkEnabledStatus(ctx, chunkStatusMap); err != nil {+ return err+ }+ }+faqKnowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, chunk.KnowledgeID)if err != nil {return err@@ -2202,6 +2229,312 @@ func (s *knowledgeService) UpdateFAQEntry(ctx context.Context,return s.indexFAQChunks(ctx, kb, faqKnowledge, []*types.Chunk{chunk}, false)}+// UpdateFAQEntryStatus updates enable status for a FAQ entry.+func (s *knowledgeService) UpdateFAQEntryStatus(ctx context.Context,+ kbID string, entryID string, isEnabled bool,+) error {+ kb, err := s.validateFAQKnowledgeBase(ctx, kbID)+ if err != nil {+ return err+ }+ tenantID := ctx.Value(types.TenantIDContextKey).(uint)+ chunk, err := s.chunkRepo.GetChunkByID(ctx, tenantID, entryID)+ if err != nil {+ return err+ }+ if chunk.KnowledgeBaseID != kb.ID || chunk.ChunkType != types.ChunkTypeFAQ {+ return werrors.NewBadRequestError("仅支持更新 FAQ 条目")+ }+ if chunk.IsEnabled == isEnabled {+ return nil+ }+ chunk.IsEnabled = isEnabled+ chunk.UpdatedAt = time.Now()+ if err := s.chunkService.UpdateChunk(ctx, chunk); err != nil {+ return err+ }++ // Sync update to retriever engines+ chunkStatusMap := map[string]bool{chunk.ID: isEnabled}+ tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)+ retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.RetrieverEngines.Engines)+ if err != nil {+ return err+ }+ if err := retrieveEngine.BatchUpdateChunkEnabledStatus(ctx, chunkStatusMap); err != nil {+ return err+ }++ return nil+}++// UpdateFAQEntryStatusBatch updates enable status for FAQ entries in batch.+func (s *knowledgeService) UpdateFAQEntryStatusBatch(ctx context.Context,+ kbID string, updates map[string]bool,+) error {+ if len(updates) == 0 {+ return nil+ }+ kb, err := s.validateFAQKnowledgeBase(ctx, kbID)+ if err != nil {+ return err+ }+ tenantID := ctx.Value(types.TenantIDContextKey).(uint)++ // Get all chunks in batch+ entryIDs := make([]string, 0, len(updates))+ for entryID := range updates {+ entryIDs = append(entryIDs, entryID)+ }+ chunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, entryIDs)+ if err != nil {+ return err+ }++ // Group chunks by enabled status for batch update+ chunkStatusMap := make(map[string]bool)+ for _, chunk := range chunks {+ if chunk.KnowledgeBaseID != kb.ID || chunk.ChunkType != types.ChunkTypeFAQ {+ continue+ }+ isEnabled, exists := updates[chunk.ID]+ if !exists {+ continue+ }+ if chunk.IsEnabled == isEnabled {+ continue+ }+ chunk.IsEnabled = isEnabled+ chunk.UpdatedAt = time.Now()+ if err := s.chunkService.UpdateChunk(ctx, chunk); err != nil {+ return err+ }+ chunkStatusMap[chunk.ID] = isEnabled+ }++ // Sync update to retriever engines+ if len(chunkStatusMap) > 0 {+ tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)+ retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.RetrieverEngines.Engines)+ if err != nil {+ return err+ }+ if err := retrieveEngine.BatchUpdateChunkEnabledStatus(ctx, chunkStatusMap); err != nil {+ return err+ }+ }++ return nil+}++// UpdateKnowledgeTag updates the tag assigned to a knowledge document.+func (s *knowledgeService) UpdateKnowledgeTag(ctx context.Context, knowledgeID string, tagID *string) error {+ tenantID := ctx.Value(types.TenantIDContextKey).(uint)+ knowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, knowledgeID)+ if err != nil {+ return err+ }++ var resolvedTagID string+ if tagID != nil && *tagID != "" {+ tag, err := s.tagRepo.GetByID(ctx, tenantID, *tagID)+ if err != nil {+ return err+ }+ if tag.KnowledgeBaseID != knowledge.KnowledgeBaseID {+ return werrors.NewBadRequestError("标签不属于当前知识库")+ }+ resolvedTagID = tag.ID+ }++ knowledge.TagID = resolvedTagID+ return s.repo.UpdateKnowledge(ctx, knowledge)+}++// UpdateKnowledgeTagBatch updates tags for document knowledge items in batch.+func (s *knowledgeService) UpdateKnowledgeTagBatch(ctx context.Context, updates map[string]*string) error {+ if len(updates) == 0 {+ return nil+ }+ tenantID := ctx.Value(types.TenantIDContextKey).(uint)++ // Get all knowledge items in batch+ knowledgeIDs := make([]string, 0, len(updates))+ for knowledgeID := range updates {+ knowledgeIDs = append(knowledgeIDs, knowledgeID)+ }+ knowledgeList, err := s.repo.GetKnowledgeBatch(ctx, tenantID, knowledgeIDs)+ if err != nil {+ return err+ }++ // Build tag ID map for validation+ tagIDSet := make(map[string]bool)+ for _, tagID := range updates {+ if tagID != nil && *tagID != "" {+ tagIDSet[*tagID] = true+ }+ }++ // Validate all tags in batch+ tagMap := make(map[string]*types.KnowledgeTag)+ if len(tagIDSet) > 0 {+ tagIDs := make([]string, 0, len(tagIDSet))+ for tagID := range tagIDSet {+ tagIDs = append(tagIDs, tagID)+ }+ for _, tagID := range tagIDs {+ tag, err := s.tagRepo.GetByID(ctx, tenantID, tagID)+ if err != nil {+ return err+ }+ tagMap[tagID] = tag+ }+ }++ // Update knowledge items+ knowledgeToUpdate := make([]*types.Knowledge, 0)+ for _, knowledge := range knowledgeList {+ tagID, exists := updates[knowledge.ID]+ if !exists {+ continue+ }++ var resolvedTagID string+ if tagID != nil && *tagID != "" {+ tag, ok := tagMap[*tagID]+ if !ok {+ return werrors.NewBadRequestError(fmt.Sprintf("标签 %s 不存在", *tagID))+ }+ if tag.KnowledgeBaseID != knowledge.KnowledgeBaseID {+ return werrors.NewBadRequestError(fmt.Sprintf("标签 %s 不属于知识库 %s", *tagID, knowledge.KnowledgeBaseID))+ }+ resolvedTagID = tag.ID+ }++ knowledge.TagID = resolvedTagID+ knowledgeToUpdate = append(knowledgeToUpdate, knowledge)+ }++ if len(knowledgeToUpdate) > 0 {+ return s.repo.UpdateKnowledgeBatch(ctx, knowledgeToUpdate)+ }++ return nil+}++// UpdateFAQEntryTag updates the tag assigned to an FAQ entry.+func (s *knowledgeService) UpdateFAQEntryTag(ctx context.Context, kbID string, entryID string, tagID *string) error {+ kb, err := s.validateFAQKnowledgeBase(ctx, kbID)+ if err != nil {+ return err+ }+ tenantID := ctx.Value(types.TenantIDContextKey).(uint)+ chunk, err := s.chunkRepo.GetChunkByID(ctx, tenantID, entryID)+ if err != nil {+ return err+ }+ if chunk.KnowledgeBaseID != kb.ID || chunk.ChunkType != types.ChunkTypeFAQ {+ return werrors.NewBadRequestError("仅支持更新 FAQ 条目标签")+ }++ var resolvedTagID string+ if tagID != nil && *tagID != "" {+ tag, err := s.tagRepo.GetByID(ctx, tenantID, *tagID)+ if err != nil {+ return err+ }+ if tag.KnowledgeBaseID != kb.ID {+ return werrors.NewBadRequestError("标签不属于当前知识库")+ }+ resolvedTagID = tag.ID+ }++ chunk.TagID = resolvedTagID+ chunk.UpdatedAt = time.Now()+ return s.chunkRepo.UpdateChunk(ctx, chunk)+}++// UpdateFAQEntryTagBatch updates tags for FAQ entries in batch.+func (s *knowledgeService) UpdateFAQEntryTagBatch(ctx context.Context, kbID string, updates map[string]*string) error {+ if len(updates) == 0 {+ return nil+ }+ kb, err := s.validateFAQKnowledgeBase(ctx, kbID)+ if err != nil {+ return err+ }+ tenantID := ctx.Value(types.TenantIDContextKey).(uint)++ // Get all chunks in batch+ entryIDs := make([]string, 0, len(updates))+ for entryID := range updates {+ entryIDs = append(entryIDs, entryID)+ }+ chunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, entryIDs)+ if err != nil {+ return err+ }++ // Build tag ID map for validation+ tagIDSet := make(map[string]bool)+ for _, tagID := range updates {+ if tagID != nil && *tagID != "" {+ tagIDSet[*tagID] = true+ }+ }++ // Validate all tags in batch+ tagMap := make(map[string]*types.KnowledgeTag)+ if len(tagIDSet) > 0 {+ tagIDs := make([]string, 0, len(tagIDSet))+ for tagID := range tagIDSet {+ tagIDs = append(tagIDs, tagID)+ }+ for _, tagID := range tagIDs {+ tag, err := s.tagRepo.GetByID(ctx, tenantID, tagID)+ if err != nil {+ return err+ }+ if tag.KnowledgeBaseID != kb.ID {+ return werrors.NewBadRequestError(fmt.Sprintf("标签 %s 不属于当前知识库", tagID))+ }+ tagMap[tagID] = tag+ }+ }++ // Update chunks+ chunksToUpdate := make([]*types.Chunk, 0)+ for _, chunk := range chunks {+ if chunk.KnowledgeBaseID != kb.ID || chunk.ChunkType != types.ChunkTypeFAQ {+ continue+ }+ tagID, exists := updates[chunk.ID]+ if !exists {+ continue+ }++ var resolvedTagID string+ if tagID != nil && *tagID != "" {+ tag, ok := tagMap[*tagID]+ if !ok {+ return werrors.NewBadRequestError(fmt.Sprintf("标签 %s 不存在", *tagID))+ }+ resolvedTagID = tag.ID+ }++ chunk.TagID = resolvedTagID+ chunk.UpdatedAt = time.Now()+ chunksToUpdate = append(chunksToUpdate, chunk)+ }++ if len(chunksToUpdate) > 0 {+ return s.chunkRepo.UpdateChunks(ctx, chunksToUpdate)+ }++ return nil+}+// SearchFAQEntries searches FAQ entries using hybrid search.func (s *knowledgeService) SearchFAQEntries(ctx context.Context,kbID string, req *types.FAQSearchRequest,@@ -2268,6 +2601,9 @@ func (s *knowledgeService) SearchFAQEntries(ctx context.Context,if chunk.ChunkType != types.ChunkTypeFAQ {continue}+ if !chunk.IsEnabled {+ continue+ }entry, err := s.chunkToFAQEntry(chunk, kb)if err != nil {@@ -2408,6 +2744,7 @@ func (s *knowledgeService) chunkToFAQEntry(chunk *types.Chunk, kb *types.KnowledKnowledgeID: chunk.KnowledgeID,KnowledgeBaseID: chunk.KnowledgeBaseID,TagID: chunk.TagID,+ IsEnabled: chunk.IsEnabled,StandardQuestion: meta.StandardQuestion,SimilarQuestions: meta.SimilarQuestions,NegativeQuestions: meta.NegativeQuestions,diff --git a/internal/application/service/retriever/composite.go b/internal/application/service/retriever/composite.goindex 73cdb0bde..d12865d06 100644--- a/internal/application/service/retriever/composite.go+++ b/internal/application/service/retriever/composite.go@@ -93,6 +93,16 @@ func (c *CompositeRetrieveEngine) SupportRetriever(r types.RetrieverType) bool {return false}+// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch+func (c *CompositeRetrieveEngine) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {+ return c.concurrentExecWithError(ctx, func(ctx context.Context, engineInfo *engineInfo) error {+ if err := engineInfo.retrieveEngine.BatchUpdateChunkEnabledStatus(ctx, chunkStatusMap); err != nil {+ return err+ }+ return nil+ })+}+// concurrentRetrieve is a helper function for concurrent processing of retrieval parameters// and collecting resultsfunc concurrentRetrieve(diff --git a/internal/application/service/retriever/keywords_vector_hybrid_indexer.go b/internal/application/service/retriever/keywords_vector_hybrid_indexer.goindex 48358ec60..ff8ecf6ca 100644--- a/internal/application/service/retriever/keywords_vector_hybrid_indexer.go+++ b/internal/application/service/retriever/keywords_vector_hybrid_indexer.go@@ -161,3 +161,8 @@ func (v *KeywordsVectorHybridRetrieveEngineService) CopyIndices(ctx, sourceKnowledgeBaseID, sourceToTargetKBIDMap, sourceToTargetChunkIDMap, targetKnowledgeBaseID, dimension,)}++// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch+func (v *KeywordsVectorHybridRetrieveEngineService) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {+ return v.indexRepository.BatchUpdateChunkEnabledStatus(ctx, chunkStatusMap)+}diff --git a/internal/handler/faq.go b/internal/handler/faq.goindex 0ae0e2483..074bfc82b 100644--- a/internal/handler/faq.go+++ b/internal/handler/faq.go@@ -88,10 +88,56 @@ func (h *FAQHandler) UpdateEntry(c *gin.Context) {})}+// UpdateEntryTagBatch updates tags for FAQ entries in batch.+func (h *FAQHandler) UpdateEntryTagBatch(c *gin.Context) {+ ctx := c.Request.Context()+ var req faqEntryTagBatchRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ logger.Error(ctx, "Failed to bind FAQ entry tag batch payload", err)+ c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))+ return+ }+ if err := h.knowledgeService.UpdateFAQEntryTagBatch(ctx, c.Param("id"), req.Updates); err != nil {+ logger.ErrorWithFields(ctx, err, nil)+ c.Error(err)+ return+ }+ c.JSON(http.StatusOK, gin.H{+ "success": true,+ })+}++// UpdateEntryStatusBatch updates the enable status of FAQ entries in batch.+func (h *FAQHandler) UpdateEntryStatusBatch(c *gin.Context) {+ ctx := c.Request.Context()+ var req faqEntryStatusBatchRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ logger.Error(ctx, "Failed to bind FAQ entry status batch payload", err)+ c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))+ return+ }+ if err := h.knowledgeService.UpdateFAQEntryStatusBatch(ctx, c.Param("id"), req.Updates); err != nil {+ logger.ErrorWithFields(ctx, err, nil)+ c.Error(err)+ return+ }+ c.JSON(http.StatusOK, gin.H{+ "success": true,+ })+}+type faqDeleteRequest struct {IDs []string `json:"ids" binding:"required,min=1,dive,required"`}+type faqEntryStatusBatchRequest struct {+ Updates map[string]bool `json:"updates" binding:"required,min=1"`+}++type faqEntryTagBatchRequest struct {+ Updates map[string]*string `json:"updates" binding:"required,min=1"`+}+// DeleteEntries deletes FAQ entries in batch.func (h *FAQHandler) DeleteEntries(c *gin.Context) {ctx := c.Request.Context()diff --git a/internal/handler/initialization.go b/internal/handler/initialization.goindex 761d84a49..f2d64ef3a 100644--- a/internal/handler/initialization.go+++ b/internal/handler/initialization.go@@ -223,7 +223,7 @@ func (h *InitializationHandler) UpdateKBConfig(c *gin.Context) {kbIdStr, &types.Pagination{Page: 1,PageSize: 1,- })+ }, "")if err == nil && knowledgeList != nil && knowledgeList.Total > 0 {logger.Error(ctx, "Cannot change embedding model when files exist")c.Error(errors.NewBadRequestError("知识库中已有文件,无法修改Embedding模型"))@@ -1129,7 +1129,7 @@ func (h *InitializationHandler) GetCurrentConfigByKB(c *gin.Context) {kbIdStr, &types.Pagination{Page: 1,PageSize: 1,- })+ }, "")hasFiles := falseif err == nil && knowledgeList != nil && knowledgeList.Total > 0 {hasFiles = truediff --git a/internal/handler/knowledge.go b/internal/handler/knowledge.goindex 4c4c19ef8..91e477ef1 100644--- a/internal/handler/knowledge.go+++ b/internal/handler/knowledge.go@@ -509,6 +509,29 @@ func (h *KnowledgeHandler) UpdateManualKnowledge(c *gin.Context) {})}+type knowledgeTagBatchRequest struct {+ Updates map[string]*string `json:"updates" binding:"required,min=1"`+}++// UpdateKnowledgeTagBatch updates tags for knowledge items in batch.+func (h *KnowledgeHandler) UpdateKnowledgeTagBatch(c *gin.Context) {+ ctx := c.Request.Context()+ var req knowledgeTagBatchRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ logger.Error(ctx, "Failed to parse knowledge tag batch request", err)+ c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))+ return+ }+ if err := h.kgService.UpdateKnowledgeTagBatch(ctx, req.Updates); err != nil {+ logger.ErrorWithFields(ctx, err, nil)+ c.Error(err)+ return+ }+ c.JSON(http.StatusOK, gin.H{+ "success": true,+ })+}+// UpdateImageInfo updates a chunk's propertiesfunc (h *KnowledgeHandler) UpdateImageInfo(c *gin.Context) {ctx := c.Request.Context()diff --git a/internal/router/router.go b/internal/router/router.goindex b020861c3..e4ca1d1de 100644--- a/internal/router/router.go+++ b/internal/router/router.go@@ -148,6 +148,8 @@ func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandlk.GET("/:id/download", handler.DownloadKnowledgeFile)// 更新图像分块信息k.PUT("/image/:id/:chunk_id", handler.UpdateImageInfo)+ // 批量更新知识标签+ k.PUT("/tags", handler.UpdateKnowledgeTagBatch)}}@@ -161,6 +163,8 @@ func RegisterFAQRoutes(r *gin.RouterGroup, handler *handler.FAQHandler) {faq.GET("/entries", handler.ListEntries)faq.POST("/entries", handler.UpsertEntries)faq.PUT("/entries/:entry_id", handler.UpdateEntry)+ faq.PUT("/entries/status", handler.UpdateEntryStatusBatch)+ faq.PUT("/entries/tags", handler.UpdateEntryTagBatch)faq.DELETE("/entries", handler.DeleteEntries)faq.POST("/search", handler.SearchFAQ)}diff --git a/internal/types/faq.go b/internal/types/faq.goindex c6e0c712a..6c1fe9ac5 100644--- a/internal/types/faq.go+++ b/internal/types/faq.go@@ -68,6 +68,7 @@ type FAQEntry struct {KnowledgeID string `json:"knowledge_id"`KnowledgeBaseID string `json:"knowledge_base_id"`TagID string `json:"tag_id"`+ IsEnabled bool `json:"is_enabled"`StandardQuestion string `json:"standard_question"`SimilarQuestions []string `json:"similar_questions"`NegativeQuestions []string `json:"negative_questions"`@@ -87,6 +88,7 @@ type FAQEntryPayload struct {NegativeQuestions []string `json:"negative_questions"`Answers []string `json:"answers" binding:"required"`TagID string `json:"tag_id"`+ IsEnabled *bool `json:"is_enabled,omitempty"`}const (diff --git a/internal/types/interfaces/chunk.go b/internal/types/interfaces/chunk.goindex e3ba787ef..ad9665180 100644--- a/internal/types/interfaces/chunk.go+++ b/internal/types/interfaces/chunk.go@@ -29,6 +29,8 @@ type ChunkRepository interface {ListChunkByParentID(ctx context.Context, tenantID uint, parentID string) ([]*types.Chunk, error)// UpdateChunk updates a chunkUpdateChunk(ctx context.Context, chunk *types.Chunk) error+ // UpdateChunks updates chunks in batch+ UpdateChunks(ctx context.Context, chunks []*types.Chunk) error// DeleteChunk deletes a chunkDeleteChunk(ctx context.Context, tenantID uint, id string) error// DeleteChunksByKnowledgeID deletes chunks by knowledge iddiff --git a/internal/types/interfaces/knowledge.go b/internal/types/interfaces/knowledge.goindex a1f6cf196..e81035c5b 100644--- a/internal/types/interfaces/knowledge.go+++ b/internal/types/interfaces/knowledge.go@@ -59,10 +59,16 @@ type KnowledgeService interface {UpsertFAQEntries(ctx context.Context, kbID string, payload *types.FAQBatchUpsertPayload) error// UpdateFAQEntry updates a single FAQ entry.UpdateFAQEntry(ctx context.Context, kbID string, entryID string, payload *types.FAQEntryPayload) error+ // UpdateFAQEntryStatusBatch updates enable status for FAQ entries in batch.+ UpdateFAQEntryStatusBatch(ctx context.Context, kbID string, updates map[string]bool) error// DeleteFAQEntries deletes FAQ entries in batch.DeleteFAQEntries(ctx context.Context, kbID string, entryIDs []string) error// SearchFAQEntries searches FAQ entries using hybrid search.SearchFAQEntries(ctx context.Context, kbID string, req *types.FAQSearchRequest) ([]*types.FAQEntry, error)+ // UpdateKnowledgeTagBatch updates tag for document knowledge items in batch.+ UpdateKnowledgeTagBatch(ctx context.Context, updates map[string]*string) error+ // UpdateFAQEntryTagBatch updates tag for FAQ entries in batch.+ UpdateFAQEntryTagBatch(ctx context.Context, kbID string, updates map[string]*string) error}// KnowledgeRepository defines the interface for knowledge repositories.@@ -76,6 +82,8 @@ type KnowledgeRepository interface {tenantID uint, kbID string, page *types.Pagination, tagID string,) ([]*types.Knowledge, int64, error)UpdateKnowledge(ctx context.Context, knowledge *types.Knowledge) error+ // UpdateKnowledgeBatch updates knowledge items in batch+ UpdateKnowledgeBatch(ctx context.Context, knowledgeList []*types.Knowledge) errorDeleteKnowledge(ctx context.Context, tenantID uint, id string) errorDeleteKnowledgeList(ctx context.Context, tenantID uint, ids []string) errorGetKnowledgeBatch(ctx context.Context, tenantID uint, ids []string) ([]*types.Knowledge, error)diff --git a/internal/types/interfaces/retriever.go b/internal/types/interfaces/retriever.goindex 7969ab79f..41c147b4d 100644--- a/internal/types/interfaces/retriever.go+++ b/internal/types/interfaces/retriever.go@@ -49,6 +49,10 @@ type RetrieveEngineRepository interface {// DeleteByKnowledgeIDList deletes the index info by knowledge id listDeleteByKnowledgeIDList(ctx context.Context, knowledgeIDList []string, dimension int) error+ // BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch+ // chunkStatusMap: map of chunk ID to enabled status (true = enabled, false = disabled)+ BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error+// RetrieveEngine retrieves the engineRetrieveEngine}@@ -104,6 +108,10 @@ type RetrieveEngineService interface {// DeleteByKnowledgeIDList deletes the index info by knowledge id listDeleteByKnowledgeIDList(ctx context.Context, knowledgeIDList []string, dimension int) error+ // BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch+ // chunkStatusMap: map of chunk ID to enabled status (true = enabled, false = disabled)+ BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error+// RetrieveEngine retrieves the engineRetrieveEngine}diff --git a/migrations/versioned/000010_add_embeddings_is_enabled.down.sql b/migrations/versioned/000010_add_embeddings_is_enabled.down.sqlnew file mode 100644index 000000000..46b10ae72--- /dev/null+++ b/migrations/versioned/000010_add_embeddings_is_enabled.down.sql@@ -0,0 +1,14 @@+-- 000010_add_embeddings_is_enabled.down.sql+-- Remove is_enabled column from embeddings table++BEGIN;++-- Drop index+DROP INDEX IF EXISTS idx_embeddings_is_enabled;++-- Remove is_enabled column+ALTER TABLE embeddings+ DROP COLUMN IF EXISTS is_enabled;++COMMIT;+diff --git a/migrations/versioned/000010_add_embeddings_is_enabled.up.sql b/migrations/versioned/000010_add_embeddings_is_enabled.up.sqlnew file mode 100644index 000000000..085e18313--- /dev/null+++ b/migrations/versioned/000010_add_embeddings_is_enabled.up.sql@@ -0,0 +1,15 @@+-- 000010_add_embeddings_is_enabled.up.sql+-- Add is_enabled column to embeddings table++BEGIN;++-- Add is_enabled column to embeddings table+ALTER TABLE embeddings+ ADD COLUMN IF NOT EXISTS is_enabled BOOLEAN DEFAULT TRUE;++-- Create index for is_enabled column+CREATE INDEX IF NOT EXISTS idx_embeddings_is_enabled+ ON embeddings(is_enabled);++COMMIT;+