feat: Enhance FAQ import functionality and UI improvements

- Added support for tracking the status of FAQ import tasks, including progress indicators for ongoing imports.
- Introduced new localization strings for processing tasks and batch operations in multiple languages.
- Updated the FAQ entry manager to display import progress and improved user feedback during the import process.
- Enhanced the KnowledgeBase component to reflect the processing state of knowledge items, improving user experience during document uploads.
- Implemented batch deletion functionality for chunks, streamlining the management of knowledge base content.
This commit is contained in:
wizardchen
2025-11-23 17:32:50 +08:00
parent e853605cea
commit 057cfd9eb0
46 changed files with 3672 additions and 1400 deletions
@@ -45,6 +45,15 @@ let knowledgeIndex = ref(-1)
let knowledgeScroll = ref()
let page = 1;
let pageSize = 35;
// 文档处理进度条状态
const documentProcessingState = reactive({
processingIds: [] as string[],
total: 0,
completed: 0,
failed: 0,
pollingInterval: null as ReturnType<typeof setInterval> | null,
})
const selectedTagId = ref<string>("");
const tagList = ref<any[]>([]);
const tagLoading = ref(false);
@@ -396,6 +405,15 @@ const handleFileUploaded = (event: CustomEvent) => {
// 如果上传的文件属于当前知识库,使用 loadKnowledgeFiles 刷新文件列表
loadKnowledgeFiles(uploadedKbId);
loadTags(uploadedKbId);
// 延迟一下,等待文件列表加载完成后再检查处理状态
setTimeout(() => {
const processingList = cardList.value.filter(item =>
item.parse_status === 'pending' || item.parse_status === 'processing'
)
if (processingList.length > 0) {
updateDocumentProcessingState(processingList)
}
}, 500)
}
};
@@ -416,11 +434,17 @@ onMounted(() => {
window.addEventListener('knowledgeFileUploaded', handleFileUploaded as EventListener);
// 监听URL导入对话框打开事件
window.addEventListener('openURLImportDialog', handleOpenURLImportDialog as EventListener);
// 恢复文档处理状态
if (!isFAQ.value) {
restoreDocumentProcessingState()
}
});
onUnmounted(() => {
window.removeEventListener('knowledgeFileUploaded', handleFileUploaded as EventListener);
window.removeEventListener('openURLImportDialog', handleOpenURLImportDialog as EventListener);
stopDocumentProcessingPolling()
});
watch(() => cardList.value, (newValue) => {
if (isFAQ.value) return;
@@ -435,6 +459,9 @@ watch(() => cardList.value, (newValue) => {
if (analyzeList.length) {
updateStatus(analyzeList)
}
// 更新文档处理进度条状态
updateDocumentProcessingState(analyzeList)
}, { deep: true })
type KnowledgeCard = {
id: string;
@@ -477,6 +504,168 @@ const updateStatus = (analyzeList: KnowledgeCard[]) => {
}, 1500);
};
// 更新文档处理进度条状态
const updateDocumentProcessingState = (processingList: KnowledgeCard[]) => {
const processingIds = processingList.map(item => item.id)
const hasChanged = JSON.stringify(processingIds.sort()) !== JSON.stringify(documentProcessingState.processingIds.sort())
if (hasChanged) {
documentProcessingState.processingIds = processingIds
documentProcessingState.total = processingIds.length
documentProcessingState.completed = 0
documentProcessingState.failed = 0
// 保存到 localStorage
saveProcessingIdsToStorage(processingIds)
// 开始轮询
if (processingIds.length > 0) {
startDocumentProcessingPolling()
} else {
stopDocumentProcessingPolling()
}
}
}
// 开始轮询文档处理状态
const startDocumentProcessingPolling = () => {
stopDocumentProcessingPolling()
if (documentProcessingState.processingIds.length === 0) return
documentProcessingState.pollingInterval = setInterval(() => {
if (documentProcessingState.processingIds.length === 0) {
stopDocumentProcessingPolling()
return
}
let query = ``
documentProcessingState.processingIds.forEach(id => {
query += `ids=${id}&`
})
batchQueryKnowledge(query).then((result: any) => {
if (result.success && result.data) {
const completedIds: string[] = []
const failedIds: string[] = []
;(result.data as KnowledgeCard[]).forEach((item: KnowledgeCard) => {
if (item.parse_status === 'completed') {
completedIds.push(item.id)
documentProcessingState.completed++
} else if (item.parse_status === 'failed') {
failedIds.push(item.id)
documentProcessingState.failed++
}
})
// 从处理列表中移除已完成的文档
documentProcessingState.processingIds = documentProcessingState.processingIds.filter(
id => !completedIds.includes(id) && !failedIds.includes(id)
)
// 如果所有文档都处理完成,停止轮询
if (documentProcessingState.processingIds.length === 0) {
stopDocumentProcessingPolling()
clearProcessingIdsFromStorage()
// 刷新文件列表
if (kbId.value) {
loadKnowledgeFiles(kbId.value)
}
} else {
// 更新 localStorage
saveProcessingIdsToStorage(documentProcessingState.processingIds)
}
}
}).catch((_err) => {
// 错误处理
})
}, 2000)
}
// 停止轮询文档处理状态
const stopDocumentProcessingPolling = () => {
if (documentProcessingState.pollingInterval) {
clearInterval(documentProcessingState.pollingInterval)
documentProcessingState.pollingInterval = null
}
}
// localStorage 相关函数
const getProcessingIdsStorageKey = () => {
return `document_processing_ids_${kbId.value}`
}
const saveProcessingIdsToStorage = (ids: string[]) => {
if (!kbId.value) return
try {
localStorage.setItem(getProcessingIdsStorageKey(), JSON.stringify(ids))
} catch (error) {
console.error('Failed to save processing IDs to localStorage:', error)
}
}
const getProcessingIdsFromStorage = (): string[] => {
if (!kbId.value) return []
try {
const data = localStorage.getItem(getProcessingIdsStorageKey())
return data ? JSON.parse(data) : []
} catch (error) {
console.error('Failed to get processing IDs from localStorage:', error)
return []
}
}
const clearProcessingIdsFromStorage = () => {
if (!kbId.value) return
try {
localStorage.removeItem(getProcessingIdsStorageKey())
} catch (error) {
console.error('Failed to clear processing IDs from localStorage:', error)
}
}
// 恢复文档处理状态(用于刷新后恢复)
const restoreDocumentProcessingState = async () => {
if (!kbId.value || isFAQ.value) return
const savedIds = getProcessingIdsFromStorage()
if (savedIds.length === 0) return
// 检查这些文档是否还在处理中
let query = ``
savedIds.forEach(id => {
query += `ids=${id}&`
})
try {
const result: any = await batchQueryKnowledge(query)
if (result.success && result.data) {
const stillProcessing: string[] = []
;(result.data as KnowledgeCard[]).forEach((item: KnowledgeCard) => {
if (item.parse_status === 'pending' || item.parse_status === 'processing') {
stillProcessing.push(item.id)
}
})
if (stillProcessing.length > 0) {
documentProcessingState.processingIds = stillProcessing
documentProcessingState.total = stillProcessing.length
documentProcessingState.completed = 0
documentProcessingState.failed = 0
saveProcessingIdsToStorage(stillProcessing)
startDocumentProcessingPolling()
} else {
clearProcessingIdsFromStorage()
}
}
} catch (error) {
console.error('Failed to restore document processing state:', error)
clearProcessingIdsFromStorage()
}
}
const closeDoc = () => {
isCardDetails.value = false;
};
@@ -520,6 +709,16 @@ const ensureDocumentKbReady = () => {
return true;
};
// 关闭文档处理进度条
const handleCloseDocumentProgress = () => {
stopDocumentProcessingPolling()
documentProcessingState.processingIds = []
documentProcessingState.total = 0
documentProcessingState.completed = 0
documentProcessingState.failed = 0
clearProcessingIdsFromStorage()
}
const handleDocumentUploadClick = () => {
if (!ensureDocumentKbReady()) return;
uploadInputRef.value?.click();
@@ -818,6 +1017,41 @@ async function createNewSession(value: string): Promise<void> {
<p class="document-subtitle">{{ $t('knowledgeEditor.document.subtitle') }}</p>
</div>
</div>
<!-- 文档处理进度条 -->
<div v-if="!isFAQ && documentProcessingState.processingIds.length > 0" class="document-processing-progress-bar">
<div class="progress-bar-content">
<div class="progress-bar-header">
<t-icon
name="loading"
size="16px"
class="progress-icon icon-loading"
/>
<span class="progress-title">
{{ $t('knowledgeList.processingDocuments', { count: documentProcessingState.processingIds.length }) }}
</span>
<span class="progress-count">
{{ documentProcessingState.completed + documentProcessingState.failed }}/{{ documentProcessingState.total }}
</span>
<t-button
variant="text"
theme="default"
size="small"
class="progress-close-btn"
@click="handleCloseDocumentProgress"
>
<t-icon name="close" size="14px" />
</t-button>
</div>
<t-progress
:percentage="Math.round(((documentProcessingState.completed + documentProcessingState.failed) / documentProcessingState.total) * 100)"
:status="documentProcessingState.failed > 0 ? 'error' : 'active'"
:label="false"
class="progress-bar"
/>
</div>
</div>
<input
ref="uploadInputRef"
type="file"
@@ -1872,6 +2106,76 @@ async function createNewSession(value: string): Promise<void> {
min-height: 100%;
}
.document-processing-progress-bar {
margin-bottom: 16px;
background: #fff;
border: 1px solid #e7ebf0;
border-radius: 8px;
padding: 12px 16px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
.progress-bar-content {
display: flex;
flex-direction: column;
gap: 8px;
}
.progress-bar-header {
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
color: #000000e6;
.progress-icon {
flex-shrink: 0;
&.icon-loading {
animation: rotate 1s linear infinite;
color: #07c05f;
}
}
.progress-title {
font-weight: 500;
flex: 1;
}
.progress-count {
color: #86909c;
font-size: 13px;
}
.progress-close-btn {
flex-shrink: 0;
padding: 4px;
margin-left: 8px;
}
}
.progress-bar {
margin: 0;
width: 100%;
:deep(.t-progress) {
width: 100%;
}
:deep(.t-progress__bar) {
width: 100%;
}
}
}
@keyframes rotate {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
:deep(.del-knowledge) {
padding: 0px !important;
border-radius: 6px !important;
@@ -24,8 +24,10 @@
:class="{
'uninitialized': !isInitialized(kb),
'kb-type-document': (kb.type || 'document') === 'document',
'kb-type-faq': kb.type === 'faq'
'kb-type-faq': kb.type === 'faq',
'highlight-flash': highlightedKbId !== null && highlightedKbId === kb.id
}"
:ref="el => { if (highlightedKbId !== null && highlightedKbId === kb.id && el) highlightedCardRef = el as HTMLElement }"
@click="handleCardClick(kb)"
>
<!-- 卡片头部 -->
@@ -78,6 +80,15 @@
{{ kb.type === 'faq' ? $t('knowledgeEditor.basic.typeFAQ') : $t('knowledgeEditor.basic.typeDocument') }}
({{ kb.type === 'faq' ? (kb.chunk_count || 0) : (kb.knowledge_count || 0) }})
</span>
<t-tooltip
v-if="kb.isProcessing"
:content="kb.type === 'document' && (kb.processing_count || 0) > 0
? $t('knowledgeList.processingDocuments', { count: kb.processing_count || 0 })
: $t('knowledgeList.processing')"
placement="top"
>
<t-icon name="loading" size="14px" class="processing-icon" />
</t-tooltip>
</div>
<div class="feature-badges">
<t-tooltip v-if="kb.extract_config?.enabled" :content="$t('knowledgeList.features.knowledgeGraph')" placement="top">
@@ -144,9 +155,9 @@
</template>
<script setup lang="ts">
import { onMounted, ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { MessagePlugin } from 'tdesign-vue-next'
import { onMounted, ref, computed, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { MessagePlugin, Icon as TIcon } from 'tdesign-vue-next'
import { listKnowledgeBases, deleteKnowledgeBase } from '@/api/knowledge-base'
import { formatStringDate } from '@/utils/index'
import { useUIStore } from '@/stores/ui'
@@ -155,6 +166,7 @@ import Settings from '@/views/settings/Settings.vue'
import { useI18n } from 'vue-i18n'
const router = useRouter()
const route = useRoute()
const uiStore = useUIStore()
const { t } = useI18n()
@@ -172,6 +184,8 @@ interface KB {
cos_config?: { provider?: string; bucket_name?: string };
knowledge_count?: number;
chunk_count?: number;
isProcessing?: boolean; // 是否有正在处理的导入任务
processing_count?: number; // 正在处理的文档数量(仅文档类型)
}
const kbs = ref<KB[]>([])
@@ -179,22 +193,43 @@ const loading = ref(false)
const deleteVisible = ref(false)
const deletingKb = ref<KB | null>(null)
const currentMoreIndex = ref<number>(-1)
const highlightedKbId = ref<string | null>(null)
const highlightedCardRef = ref<HTMLElement | null>(null)
const fetchList = () => {
loading.value = true
listKnowledgeBases().then((res: any) => {
return listKnowledgeBases().then((res: any) => {
const data = res.data || []
// 格式化时间,并初始化 showMore 状态
kbs.value = data.map((kb: KB) => ({
// is_processing 字段由后端返回
kbs.value = data.map((kb: any) => ({
...kb,
updated_at: kb.updated_at ? formatStringDate(new Date(kb.updated_at)) : '',
showMore: false
showMore: false,
isProcessing: kb.is_processing || false,
processing_count: kb.processing_count || 0
}))
}).finally(() => loading.value = false)
}
onMounted(() => {
fetchList()
fetchList().then(() => {
// 检查路由参数中是否有需要高亮的知识库ID
const highlightKbId = route.query.highlightKbId as string
if (highlightKbId) {
triggerHighlightFlash(highlightKbId)
// 清除 URL 中的查询参数
router.replace({ query: {} })
}
})
})
// 监听路由变化,处理从其他页面跳转过来的高亮需求
watch(() => route.query.highlightKbId, (newKbId) => {
if (newKbId && typeof newKbId === 'string' && kbs.value.length > 0) {
triggerHighlightFlash(newKbId)
router.replace({ query: {} })
}
})
const openMore = (index: number) => {
@@ -270,7 +305,32 @@ const goSettings = (id: string) => {
// 知识库编辑器成功回调(创建或编辑成功)
const handleKBEditorSuccess = (kbId: string) => {
console.log('[KnowledgeBaseList] knowledge operation success:', kbId)
fetchList()
fetchList().then(() => {
// 如果是从路由参数中获取的高亮ID,触发闪烁效果
if (route.query.highlightKbId === kbId) {
triggerHighlightFlash(kbId)
// 清除 URL 中的查询参数
router.replace({ query: {} })
}
})
}
// 触发高亮闪烁效果
const triggerHighlightFlash = (kbId: string) => {
highlightedKbId.value = kbId
nextTick(() => {
if (highlightedCardRef.value) {
// 滚动到高亮的卡片
highlightedCardRef.value.scrollIntoView({
behavior: 'smooth',
block: 'center'
})
}
// 3秒后清除高亮
setTimeout(() => {
highlightedKbId.value = null
}, 3000)
})
}
</script>
@@ -533,6 +593,19 @@ const handleKBEditorSuccess = (kbId: string) => {
color: #0052d9;
border: 1px solid rgba(0, 82, 217, 0.2);
}
.processing-icon {
animation: spin 1s linear infinite;
margin-left: 4px;
}
&.document .processing-icon {
color: #059669;
}
&.faq .processing-icon {
color: #0052d9;
}
}
.feature-badges {
@@ -569,6 +642,40 @@ const handleKBEditorSuccess = (kbId: string) => {
background: rgba(255, 152, 0, 0.15);
}
}
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@keyframes highlightFlash {
0% {
border-color: #07c05f;
box-shadow: 0 0 0 0 rgba(7, 192, 95, 0.4);
transform: scale(1);
}
50% {
border-color: #07c05f;
box-shadow: 0 0 0 8px rgba(7, 192, 95, 0);
transform: scale(1.02);
}
100% {
border-color: #07c05f;
box-shadow: 0 0 0 0 rgba(7, 192, 95, 0);
transform: scale(1);
}
}
.kb-card.highlight-flash {
animation: highlightFlash 0.6s ease-in-out 3;
border-color: #07c05f !important;
box-shadow: 0 0 12px rgba(7, 192, 95, 0.3) !important;
}
.card-time {
File diff suppressed because it is too large Load Diff