WeKnora/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue

1855 lines
64 KiB
Vue
Raw Normal View History

<template>
<Teleport to="body">
<Transition name="modal">
<div v-if="visible" class="settings-overlay" @click.self="handleClose">
<div class="settings-modal">
<!-- 关闭按钮 -->
<button class="close-btn" @click="handleClose" :aria-label="$t('general.close')">
<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor">
<path d="M15 5L5 15M5 5L15 15" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
</svg>
</button>
<div class="settings-container">
<!-- 左侧导航 -->
<div class="settings-sidebar">
<div class="sidebar-header">
<h2 class="sidebar-title">{{ mode === 'create' ? $t('knowledgeEditor.titleCreate') : $t('knowledgeEditor.titleEdit') }}</h2>
</div>
<div class="settings-nav" data-guide="kb-editor-sidebar">
<div
v-for="(item, index) in navItems"
:key="index"
:class="['nav-item', { 'active': currentSection === item.key }]"
:data-guide="`kb-editor-nav-${item.key}`"
@click="currentSection = item.key"
>
<t-icon :name="item.icon" class="nav-icon" />
<span class="nav-label">{{ item.label }}</span>
<span v-if="item.badge" class="nav-badge">{{ item.badge }}</span>
</div>
</div>
</div>
<!-- 右侧内容区域 -->
<div class="settings-content">
<div class="content-wrapper">
<!-- 基本信息 -->
<div v-show="currentSection === 'basic'" class="section">
<div v-if="formData" class="section-content">
<div class="section-header">
<h3 class="section-title">{{ $t('knowledgeEditor.basic.title') }}</h3>
<p class="section-desc">{{ $t('knowledgeEditor.basic.description') }}</p>
</div>
<div class="section-body">
<div v-if="mode === 'edit' && props.kbId" class="form-item">
<label class="form-label">{{ $t('knowledgeEditor.basic.kbId') }}</label>
<p class="form-tip">{{ $t('knowledgeEditor.basic.kbIdDesc') }}</p>
<div class="kb-id-field">
<code class="kb-id-value" :title="props.kbId">{{ props.kbId }}</code>
<t-tooltip :content="$t('common.copy')" placement="top">
<t-button theme="default" size="small" variant="text" class="kb-id-copy"
@click="copyKbId">
<t-icon name="file-copy" />
</t-button>
</t-tooltip>
</div>
</div>
<div class="form-item">
<label class="form-label required">{{ $t('knowledgeEditor.basic.typeLabel') }}</label>
<t-radio-group
v-model="formData.type"
:disabled="mode === 'edit'"
data-guide="kb-create-type"
>
<t-radio-button value="document">{{ $t('knowledgeEditor.basic.typeDocument') }}</t-radio-button>
<t-radio-button value="faq">{{ $t('knowledgeEditor.basic.typeFAQ') }}</t-radio-button>
</t-radio-group>
<p class="form-tip">{{ $t('knowledgeEditor.basic.typeDescription') }}</p>
</div>
<!-- 索引策略 (紧跟类型选择) -->
<div v-if="!isFAQ" class="form-item">
<label class="form-label required">{{ $t('knowledgeEditor.indexing.title') }}</label>
<p class="form-tip">{{ $t('knowledgeEditor.indexing.description') }}</p>
<div class="indexing-checks" :class="{ 'is-locked': isIndexingLocked }"
data-guide="kb-create-indexing">
<div
class="indexing-check-item"
:class="{ 'is-checked': formData.indexingStrategy.vectorEnabled, 'is-disabled': isIndexingLocked }"
@click="toggleVectorIndexing"
>
<t-checkbox
:checked="formData.indexingStrategy.vectorEnabled"
:disabled="isIndexingLocked"
class="indexing-check-box"
>{{ $t('knowledgeEditor.indexing.searchTitle') }}</t-checkbox>
<p class="indexing-check-desc">{{ $t('knowledgeEditor.indexing.searchDesc') }}</p>
</div>
<div
class="indexing-check-item"
:class="{ 'is-checked': formData.indexingStrategy.wikiEnabled, 'is-disabled': isIndexingLocked }"
@click="toggleWikiIndexing"
>
<t-checkbox
:checked="formData.indexingStrategy.wikiEnabled"
:disabled="isIndexingLocked"
class="indexing-check-box"
>
<span class="indexing-check-title">
{{ $t('knowledgeEditor.indexing.wikiTitle') }}
<span class="indexing-new-badge">NEW</span>
</span>
</t-checkbox>
<p class="indexing-check-desc">{{ $t('knowledgeEditor.indexing.wikiDesc') }}</p>
</div>
</div>
<p v-if="isIndexingLocked" class="form-tip locked-tip">
{{ $t('knowledgeEditor.indexing.lockedTip') }}
</p>
</div>
<!-- Wiki 提取粒度 (仅当 Wiki 启用时显示) -->
<div v-if="!isFAQ && formData.indexingStrategy.wikiEnabled" class="form-item">
<label class="form-label">{{ $t('knowledgeEditor.wiki.extractionGranularityLabel') }}</label>
<p class="form-tip">{{ $t('knowledgeEditor.wiki.extractionGranularityTip') }}</p>
<t-radio-group
:value="resolvedGranularity"
class="granularity-radio-group"
@change="handleGranularityChange"
>
<t-radio-button value="focused">
{{ $t('knowledgeEditor.wiki.granularityFocused') }}
</t-radio-button>
<t-radio-button value="standard">
{{ $t('knowledgeEditor.wiki.granularityStandard') }}
</t-radio-button>
<t-radio-button value="exhaustive">
{{ $t('knowledgeEditor.wiki.granularityExhaustive') }}
</t-radio-button>
</t-radio-group>
<p class="form-tip granularity-hint">{{ granularityHint }}</p>
</div>
<div class="form-item" data-guide="kb-create-name">
<label class="form-label required">{{ $t('knowledgeEditor.basic.nameLabel') }}</label>
<t-input
v-model="formData.name"
:placeholder="$t('knowledgeEditor.basic.namePlaceholder')"
:maxlength="50"
/>
</div>
<div class="form-item">
<label class="form-label">{{ $t('knowledgeEditor.basic.descriptionLabel') }}</label>
<t-textarea
v-model="formData.description"
:placeholder="$t('knowledgeEditor.basic.descriptionPlaceholder')"
:maxlength="200"
:autosize="{ minRows: 3, maxRows: 6 }"
/>
</div>
<!-- Wiki 合成模型移至模型配置页 -->
</div>
</div>
</div>
<!-- 模型配置 -->
<div v-show="currentSection === 'models'" class="section">
<KBModelConfig
ref="modelConfigRef"
v-if="formData"
:config="formData.modelConfig"
:has-files="hasFiles"
:wiki-enabled="formData.indexingStrategy?.wikiEnabled"
:rag-enabled="formData.indexingStrategy?.vectorEnabled || formData.indexingStrategy?.keywordEnabled"
:all-models="allModels"
@update:config="handleModelConfigUpdate"
/>
</div>
feat: expose KB ↔ vector store binding in list, editor, and detail UI Backend ------- ListKnowledgeBases now enriches each row with the resolved vector_store metadata (name / source / engine_type / status) via a new buildKBListResponse helper. Store views are batch-resolved once per request through BatchResolveStoreView so an N-KB list costs one vector-store service call rather than N — closing the N+1 limitation flagged in #1372's known-limitations section. Cross-tenant shared KBs continue to render via SharedStoreDisplay so the owning tenant's store inventory cannot be correlated across rows; the underlying vector_store_id UUID is stripped from those responses. Resolver failures degrade gracefully: bound KBs render as unavailable instead of breaking the list. Test coverage pins the env / bound / shared distinction, the batch-call-count invariant, and the graceful-failure path. Frontend -------- KB editor modal gains a new "Vector Store" section. Create mode shows a dropdown that combines the system default (env store) and the tenant's configured user stores, fetched once at mount via the existing listVectorStores API. Edit mode shows the bound store read-only via a new VectorStoreBadge component with an explicit immutability hint — matching the backend's `<-:create` GORM tag and the service-layer UpdateKnowledgeBaseRequest DTO that already omit the field. KB list cards surface a small engine-type badge for own-tenant bound KBs, and a warning badge when the bound store is unavailable. Env-bound and shared KBs render no badge (visual noise control). KB detail header shows the bound store via the same VectorStoreBadge component; shared KBs fall through to the badge's internal "shared" branch with no name / engine / id rendered. The KB editor's create-time error handler translates the typed ErrVectorStoreBindingInvalid (2200) and ErrVectorStoreUnavailable (2201) into localized messages and jumps the user back to the VectorStore section so they can pick a different store or fall back to the system default. The KB row type gains five optional fields (vector_store_id / name / engine_type / source / status). i18n: 18 new keys added to en-US, ko-KR, zh-CN; ru-RU receives English placeholders pending translation (consistent with prior PRs in this locale). Part of #993 (Phase 2: Per-KB VectorStore Binding). Phase 2 roadmap item: PR 5 (KB binding UI + list-response enrichment). Depends on #994, #1310, #1372, #1386 (all backend in the Phase 2 series).
2026-05-18 14:50:09 +00:00
<!-- VectorStore 绑定 -->
<div v-show="currentSection === 'vectorStore'" class="section">
<KBVectorStoreSettings
v-if="formData"
:mode="mode"
:vector-store-id="formData.vectorStoreId"
:bound-source="formData.vectorStoreInfo?.source"
:bound-name="formData.vectorStoreInfo?.name"
:bound-engine-type="formData.vectorStoreInfo?.engineType"
:bound-status="formData.vectorStoreInfo?.status"
@update:vector-store-id="handleVectorStoreIdUpdate"
/>
</div>
<!-- FAQ 配置 -->
<div v-if="isFAQ && formData" v-show="currentSection === 'faq'" class="section">
<div class="section-content">
<div class="section-header">
<h3 class="section-title">{{ $t('knowledgeEditor.faq.title') }}</h3>
<p class="section-desc">{{ $t('knowledgeEditor.faq.description') }}</p>
</div>
<div class="section-body">
<div class="form-item">
<label class="form-label required">{{ $t('knowledgeEditor.faq.indexModeLabel') }}</label>
<t-radio-group
v-model="formData.faqConfig.indexMode"
>
<t-radio-button value="question_only">{{ $t('knowledgeEditor.faq.modes.questionOnly') }}</t-radio-button>
<t-radio-button value="question_answer">{{ $t('knowledgeEditor.faq.modes.questionAnswer') }}</t-radio-button>
</t-radio-group>
<p class="form-tip">{{ $t('knowledgeEditor.faq.indexModeDescription') }}</p>
</div>
<div class="form-item">
<label class="form-label required">{{ $t('knowledgeEditor.faq.questionIndexModeLabel') }}</label>
<t-radio-group
v-model="formData.faqConfig.questionIndexMode"
>
<t-radio-button value="combined">{{ $t('knowledgeEditor.faq.modes.combined') }}</t-radio-button>
<t-radio-button value="separate">{{ $t('knowledgeEditor.faq.modes.separate') }}</t-radio-button>
</t-radio-group>
<p class="form-tip">{{ $t('knowledgeEditor.faq.questionIndexModeDescription') }}</p>
</div>
<div class="faq-guide">
<p>{{ $t('knowledgeEditor.faq.entryGuide') }}</p>
</div>
</div>
</div>
</div>
<!-- 解析引擎 -->
<div v-if="!isFAQ && formData && currentSection === 'parser'" class="section">
<KBParserSettings
:parser-engine-rules="formData.chunkingConfig.parserEngineRules"
@update:parser-engine-rules="handleParserEngineRulesUpdate"
/>
</div>
<!-- 存储引擎 -->
<div v-if="!isFAQ && formData && currentSection === 'storage'" class="section">
<KBStorageSettings
:storage-provider="formData.storageProvider"
:has-files="mode === 'edit' && hasFiles"
@update:storage-provider="handleStorageProviderUpdate"
/>
</div>
<!-- 分块设置 -->
<div v-if="!isFAQ" v-show="currentSection === 'chunking'" class="section">
<KBChunkingSettings
v-if="formData"
:config="formData.chunkingConfig"
@update:config="handleChunkingConfigUpdate"
/>
</div>
<!-- 多模态配置 -->
<div v-if="!isFAQ" v-show="currentSection === 'multimodal'" class="section">
<div v-if="formData" class="kb-multimodal-settings">
<div class="section-header">
<h2>{{ $t('knowledgeEditor.multimodal.title') }}</h2>
<p class="section-description">{{ $t('knowledgeEditor.multimodal.description') }}</p>
</div>
<div class="settings-group">
<!-- 多模态开关 -->
<div class="setting-row" data-guide="kb-create-multimodal-toggle">
<div class="setting-info">
<label>{{ $t('knowledgeEditor.advanced.multimodal.label') }}</label>
<p class="desc">{{ $t('knowledgeEditor.advanced.multimodal.description') }}</p>
</div>
<div class="setting-control">
<t-switch
v-model="formData.multimodalConfig.enabled"
@change="handleMultimodalToggle"
size="medium"
/>
</div>
</div>
<!-- VLLM 模型选择(多模态启用时) -->
<div v-if="formData.multimodalConfig.enabled" class="setting-row"
data-guide="kb-create-multimodal-vllm">
<div class="setting-info">
<label>{{ $t('knowledgeEditor.advanced.multimodal.vllmLabel') }} <span class="required">*</span></label>
<p class="desc">{{ $t('knowledgeEditor.advanced.multimodal.vllmDescription') }}</p>
</div>
<div class="setting-control">
<ModelSelector
model-type="VLLM"
:selected-model-id="formData.multimodalConfig.vllmModelId"
:all-models="allModels"
@update:selected-model-id="handleMultimodalVLLMChange"
@add-model="handleAddVLLMModel"
:placeholder="$t('knowledgeEditor.advanced.multimodal.vllmPlaceholder')"
/>
</div>
</div>
</div>
</div>
</div>
feat: Implement comprehensive wiki feature for knowledge bases This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes: **Backend Changes:** - Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log) - Database schema: wiki_pages table with full migration support - WikiPageService: CRUD operations and page management - WikiPageRepository: GORM-based persistence layer - Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents * Summary page generation using LLM * Entity and concept extraction in a single LLM call * Synthesis opportunity detection * Index page rebuilding * Log page maintenance - Wiki boost feature: Enhance chat retrieval with wiki context - Wiki linting: Maintenance and validation utilities - Agent wiki tools: Enable agents to query and interact with wiki pages - Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks - Language support: Reuse existing middleware language infrastructure for LLM prompts **Frontend Changes:** - Wiki browser UI: View all wiki pages with filtering and search - Wiki API client: Knowledge base wiki management endpoints - Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model) - i18n updates: Support for English, Korean, Russian, and Chinese interfaces **Configuration:** - Container DI: Wire up all wiki services - Router: Register wiki API endpoints - Task handling: Support async wiki ingest tasks **Testing:** - Unit tests for wiki page types - Service layer tests - Endpoint tests for wiki operations - Integration tests with LLM mocking **Documentation:** - Language refactoring analysis and guides - Implementation completion reports - Quick reference guides for developers **Key Features:** ✅ LLM-powered wiki page generation from documents ✅ Multi-language support (9+ languages) ✅ Automatic extraction of entities and concepts ✅ Synthesis opportunity detection ✅ Index and log page maintenance ✅ Progressive wiki building across multiple documents ✅ Agent-based wiki interaction ✅ Chat retrieval enhancement with wiki context ✅ Full frontend UI for wiki browsing Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
<!-- 音频处理(ASR)设置 -->
<div v-if="!isFAQ" v-show="currentSection === 'asr'" class="section">
<div v-if="formData" class="kb-multimodal-settings">
<div class="section-header">
<h2>{{ $t('knowledgeEditor.asr.title') }}</h2>
<p class="section-description">{{ $t('knowledgeEditor.asr.description') }}</p>
</div>
<div class="settings-group">
<!-- ASR 开关 -->
<div class="setting-row">
<div class="setting-info">
<label>{{ $t('knowledgeEditor.asr.label') }}</label>
<p class="desc">{{ $t('knowledgeEditor.asr.desc') }}</p>
</div>
<div class="setting-control">
<t-switch
v-model="formData.asrConfig.enabled"
size="medium"
/>
</div>
</div>
<!-- ASR 模型选择 -->
<div v-if="formData.asrConfig.enabled" class="setting-row">
<div class="setting-info">
<label>{{ $t('knowledgeEditor.asr.modelLabel') }} <span class="required">*</span></label>
<p class="desc">{{ $t('knowledgeEditor.asr.modelDescription') }}</p>
</div>
<div class="setting-control">
<ModelSelector
model-type="ASR"
:selected-model-id="formData.asrConfig.modelId"
:all-models="allModels"
@update:selected-model-id="(val: string) => { if (formData) formData.asrConfig.modelId = val }"
@add-model="handleAddASRModel"
:placeholder="$t('knowledgeEditor.asr.modelPlaceholder')"
/>
</div>
</div>
</div>
</div>
</div>
<!-- 知识图谱 -->
<div v-if="!isFAQ && currentSection === 'graph'" class="section">
<GraphSettings
v-if="formData"
:graph-extract="formData.nodeExtractConfig"
:model-id="formData.modelConfig.llmModelId"
:all-models="allModels"
@update:graphExtract="handleNodeExtractUpdate"
/>
</div>
<!-- 高级设置 -->
<div v-if="!isFAQ" v-show="currentSection === 'advanced'" class="section">
<KBAdvancedSettings
ref="advancedSettingsRef"
v-if="formData"
:question-generation="formData.questionGenerationConfig"
:rag-enabled="formData.indexingStrategy?.vectorEnabled || formData.indexingStrategy?.keywordEnabled"
:all-models="allModels"
@update:question-generation="handleQuestionGenerationUpdate"
/>
</div>
<!-- 数据源管理(仅编辑模式) -->
<div v-if="mode === 'edit' && kbId && currentSection === 'datasource'" class="section">
<DataSourceSettings :kb-id="kbId" @count="dsCount = $event" />
</div>
<!-- 共享设置(仅编辑模式) -->
<div v-if="mode === 'edit' && kbId && currentSection === 'share'" class="section">
<KBShareSettings :kb-id="kbId" :can-share="canShareKB" />
</div>
</div>
<!-- 保存按钮 -->
<div class="settings-footer">
<t-button theme="default" variant="outline" @click="handleClose">
{{ $t('common.cancel') }}
</t-button>
<t-button theme="primary" data-guide="kb-create-submit" @click="handleSubmit" :loading="saving">
{{ mode === 'create' ? $t('knowledgeEditor.buttons.create') : $t('knowledgeEditor.buttons.save') }}
</t-button>
</div>
</div>
</div>
</div>
</div>
</Transition>
</Teleport>
<KbCreateContextualGuide :when="visible && mode === 'create'" :is-faq="isFAQ"
:needs-embedding="kbCreateNeedsEmbedding" />
</template>
<script setup lang="ts">
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import KbCreateContextualGuide from '@/components/KbCreateContextualGuide.vue'
import { KB_EDITOR_FOCUS_SECTION_EVENT, markContextualGuideDone } from '@/config/contextualGuides'
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
import { createKnowledgeBase, getKnowledgeBaseById, listKnowledgeFiles, updateKnowledgeBase, rebuildKBIndex } from '@/api/knowledge-base'
import { updateKBConfig, type KBModelConfigRequest } from '@/api/initialization'
import { type ModelConfig } from '@/api/model'
import { useChatResourcesStore } from '@/stores/chatResources'
import { useEditorResourcesStore } from '@/stores/editorResources'
import { useUIStore } from '@/stores/ui'
import { useAuthStore } from '@/stores/auth'
import KBModelConfig from './settings/KBModelConfig.vue'
import KBParserSettings from './settings/KBParserSettings.vue'
import KBStorageSettings from './settings/KBStorageSettings.vue'
import KBChunkingSettings from './settings/KBChunkingSettings.vue'
feat: expose KB ↔ vector store binding in list, editor, and detail UI Backend ------- ListKnowledgeBases now enriches each row with the resolved vector_store metadata (name / source / engine_type / status) via a new buildKBListResponse helper. Store views are batch-resolved once per request through BatchResolveStoreView so an N-KB list costs one vector-store service call rather than N — closing the N+1 limitation flagged in #1372's known-limitations section. Cross-tenant shared KBs continue to render via SharedStoreDisplay so the owning tenant's store inventory cannot be correlated across rows; the underlying vector_store_id UUID is stripped from those responses. Resolver failures degrade gracefully: bound KBs render as unavailable instead of breaking the list. Test coverage pins the env / bound / shared distinction, the batch-call-count invariant, and the graceful-failure path. Frontend -------- KB editor modal gains a new "Vector Store" section. Create mode shows a dropdown that combines the system default (env store) and the tenant's configured user stores, fetched once at mount via the existing listVectorStores API. Edit mode shows the bound store read-only via a new VectorStoreBadge component with an explicit immutability hint — matching the backend's `<-:create` GORM tag and the service-layer UpdateKnowledgeBaseRequest DTO that already omit the field. KB list cards surface a small engine-type badge for own-tenant bound KBs, and a warning badge when the bound store is unavailable. Env-bound and shared KBs render no badge (visual noise control). KB detail header shows the bound store via the same VectorStoreBadge component; shared KBs fall through to the badge's internal "shared" branch with no name / engine / id rendered. The KB editor's create-time error handler translates the typed ErrVectorStoreBindingInvalid (2200) and ErrVectorStoreUnavailable (2201) into localized messages and jumps the user back to the VectorStore section so they can pick a different store or fall back to the system default. The KB row type gains five optional fields (vector_store_id / name / engine_type / source / status). i18n: 18 new keys added to en-US, ko-KR, zh-CN; ru-RU receives English placeholders pending translation (consistent with prior PRs in this locale). Part of #993 (Phase 2: Per-KB VectorStore Binding). Phase 2 roadmap item: PR 5 (KB binding UI + list-response enrichment). Depends on #994, #1310, #1372, #1386 (all backend in the Phase 2 series).
2026-05-18 14:50:09 +00:00
import KBVectorStoreSettings from './settings/KBVectorStoreSettings.vue'
import KBAdvancedSettings from './settings/KBAdvancedSettings.vue'
import ModelSelector from '@/components/ModelSelector.vue'
import GraphSettings from './settings/GraphSettings.vue'
import KBShareSettings from './settings/KBShareSettings.vue'
import DataSourceSettings from './settings/DataSourceSettings.vue'
import { useI18n } from 'vue-i18n'
const uiStore = useUIStore()
const authStore = useAuthStore()
const chatResources = useChatResourcesStore()
const editorResources = useEditorResourcesStore()
const { t } = useI18n()
// Props
const props = defineProps<{
visible: boolean
mode: 'create' | 'edit'
kbId?: string
initialType?: 'document' | 'faq'
}>()
// Emits
const emit = defineEmits<{
(e: 'update:visible', value: boolean): void
(e: 'success', kbId: string): void
}>()
const copyKbId = async () => {
const id = props.kbId
if (!id) return
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(id)
} else {
const textarea = document.createElement('textarea')
textarea.value = id
textarea.setAttribute('readonly', '')
textarea.style.position = 'fixed'
textarea.style.opacity = '0'
document.body.appendChild(textarea)
textarea.select()
document.execCommand('copy')
document.body.removeChild(textarea)
}
MessagePlugin.success(t('common.copied'))
} catch {
MessagePlugin.error(t('common.copyFailed'))
}
}
const currentSection = ref<string>('basic')
const onKbEditorFocusSection = (event: Event) => {
const section = (event as CustomEvent<{ section?: string }>).detail?.section
if (section) {
currentSection.value = section
}
}
onMounted(() => {
window.addEventListener(KB_EDITOR_FOCUS_SECTION_EVENT, onKbEditorFocusSection)
})
onBeforeUnmount(() => {
window.removeEventListener(KB_EDITOR_FOCUS_SECTION_EVENT, onKbEditorFocusSection)
})
const saving = ref(false)
const loading = ref(false)
const allModels = ref<any[]>([])
const hasFiles = ref(false)
const initialStorageProvider = ref<string>('')
/** Tenant-wide default from Settings → Storage engine (used when creating a KB). */
const tenantDefaultStorageProvider = ref('local')
const initialIndexingStrategy = ref<any>(null)
const dsCount = ref(0)
feat: expose KB ↔ vector store binding in list, editor, and detail UI Backend ------- ListKnowledgeBases now enriches each row with the resolved vector_store metadata (name / source / engine_type / status) via a new buildKBListResponse helper. Store views are batch-resolved once per request through BatchResolveStoreView so an N-KB list costs one vector-store service call rather than N — closing the N+1 limitation flagged in #1372's known-limitations section. Cross-tenant shared KBs continue to render via SharedStoreDisplay so the owning tenant's store inventory cannot be correlated across rows; the underlying vector_store_id UUID is stripped from those responses. Resolver failures degrade gracefully: bound KBs render as unavailable instead of breaking the list. Test coverage pins the env / bound / shared distinction, the batch-call-count invariant, and the graceful-failure path. Frontend -------- KB editor modal gains a new "Vector Store" section. Create mode shows a dropdown that combines the system default (env store) and the tenant's configured user stores, fetched once at mount via the existing listVectorStores API. Edit mode shows the bound store read-only via a new VectorStoreBadge component with an explicit immutability hint — matching the backend's `<-:create` GORM tag and the service-layer UpdateKnowledgeBaseRequest DTO that already omit the field. KB list cards surface a small engine-type badge for own-tenant bound KBs, and a warning badge when the bound store is unavailable. Env-bound and shared KBs render no badge (visual noise control). KB detail header shows the bound store via the same VectorStoreBadge component; shared KBs fall through to the badge's internal "shared" branch with no name / engine / id rendered. The KB editor's create-time error handler translates the typed ErrVectorStoreBindingInvalid (2200) and ErrVectorStoreUnavailable (2201) into localized messages and jumps the user back to the VectorStore section so they can pick a different store or fall back to the system default. The KB row type gains five optional fields (vector_store_id / name / engine_type / source / status). i18n: 18 new keys added to en-US, ko-KR, zh-CN; ru-RU receives English placeholders pending translation (consistent with prior PRs in this locale). Part of #993 (Phase 2: Per-KB VectorStore Binding). Phase 2 roadmap item: PR 5 (KB binding UI + list-response enrichment). Depends on #994, #1310, #1372, #1386 (all backend in the Phase 2 series).
2026-05-18 14:50:09 +00:00
// Identifier of the user who created this KB. Empty for older rows
// that predate per-KB ownership tracking; those KBs have no "owner" and
// only tenant Admin+ can mutate their share settings.
const kbCreatorId = ref<string>('')
// Backend gate for /knowledge-bases/:id/shares (POST/PUT/DELETE) is
// g.OwnedKBOrAdmin(): only the KB creator or tenant Admin+ may mutate
// shares. Org-admins on a shared KB do NOT pass this guard, so they
// would only see 403s if we let them try. Mirror the matrix here so
// the buttons disappear instead of failing.
const canShareKB = computed(() => {
if (!props.kbId) return false
const userId = authStore.user?.id || ''
if (kbCreatorId.value && userId && kbCreatorId.value === userId) return true
return authStore.hasRole('admin')
})
// 用户是否在分块设置中手动改过任何值。一旦为 true,就不再根据索引策略自动调整默认分块参数。
const chunkingDirty = ref(false)
// 仅 Wiki 索引模式下的分块预设:更大 chunk、无 overlap、关闭父子分块。
// 该预设只在「创建模式」下、且用户尚未手动调整分块参数时生效,避免覆盖既有 KB 的配置。
const WIKI_ONLY_CHUNKING_PRESET = {
chunkSize: 2048,
chunkOverlap: 0,
enableParentChild: false,
} as const
docs(chunking): align overlap default + sharpen UI/source/repo docs Three documentation passes around the adaptive chunking work: UI - Frontend ChunkOverlap default consolidated to 80 (was 100), matching chunker.DefaultChunkOverlap on the backend. Both DEFAULT_CHUNKING_PRESET and initFormData updated. The KB-load fallback also uses 80 when a loaded KB has no chunk_overlap stored. - All four locales (en-US, zh-CN, ko-KR, ru-RU) get rewritten chunking setting descriptions: each now states the validated range, the default, and the situations where you'd deviate (FAQ vs narrative, embedder token limits, language-specific corpora). Source code - splitter.go: DefaultChunkSize / DefaultChunkOverlap constants get a longer block-comment explaining the per-language token math and the use-case sweet spots, plus the migration note on what the old inconsistent defaults were. - KBChunkingSettings.vue: new comment block above ChunkingConfig documents the slider min/max for each setting, why those bounds exist, and the recommended TokenLimit values per embedding model. Repo docs - New docs/CHUNKING.md: end-to-end guide covering why chunking matters, the adaptive 3-tier architecture, per-setting reference with ranges and sweet spots, parent-child explanation, the token-limit table per embedder (OpenAI / Voyage / Cohere / BGE / MiniLM / Jina), 7 use-case presets, the debug panel workflow, the API surface, and known trade-offs (recursive strategy hidden from UI, no auto-reindex on strategy switch, OCR limitations). - CHANGELOG.md gets a new [Unreleased] section consolidating all the adaptive-chunking work shipped on this branch: 5 features, 8 improvements, 6 fixes, 1 docs entry. The entry references docs/CHUNKING.md for deeper explanation. https://claude.ai/code/session_01XADhx6mtu2ZYW3DE9Lun6k
2026-05-03 11:57:03 +00:00
// Non-Wiki-only fallback. Mirrors chunker.DefaultChunkSize and
// DefaultChunkOverlap on the backend so a freshly created KB uses
// the same numbers whether the editor sets them or the splitter
// falls back to its package defaults.
const DEFAULT_CHUNKING_PRESET = {
chunkSize: 512,
docs(chunking): align overlap default + sharpen UI/source/repo docs Three documentation passes around the adaptive chunking work: UI - Frontend ChunkOverlap default consolidated to 80 (was 100), matching chunker.DefaultChunkOverlap on the backend. Both DEFAULT_CHUNKING_PRESET and initFormData updated. The KB-load fallback also uses 80 when a loaded KB has no chunk_overlap stored. - All four locales (en-US, zh-CN, ko-KR, ru-RU) get rewritten chunking setting descriptions: each now states the validated range, the default, and the situations where you'd deviate (FAQ vs narrative, embedder token limits, language-specific corpora). Source code - splitter.go: DefaultChunkSize / DefaultChunkOverlap constants get a longer block-comment explaining the per-language token math and the use-case sweet spots, plus the migration note on what the old inconsistent defaults were. - KBChunkingSettings.vue: new comment block above ChunkingConfig documents the slider min/max for each setting, why those bounds exist, and the recommended TokenLimit values per embedding model. Repo docs - New docs/CHUNKING.md: end-to-end guide covering why chunking matters, the adaptive 3-tier architecture, per-setting reference with ranges and sweet spots, parent-child explanation, the token-limit table per embedder (OpenAI / Voyage / Cohere / BGE / MiniLM / Jina), 7 use-case presets, the debug panel workflow, the API surface, and known trade-offs (recursive strategy hidden from UI, no auto-reindex on strategy switch, OCR limitations). - CHANGELOG.md gets a new [Unreleased] section consolidating all the adaptive-chunking work shipped on this branch: 5 features, 8 improvements, 6 fixes, 1 docs entry. The entry references docs/CHUNKING.md for deeper explanation. https://claude.ai/code/session_01XADhx6mtu2ZYW3DE9Lun6k
2026-05-03 11:57:03 +00:00
chunkOverlap: 80,
enableParentChild: true,
} as const
const navItems = computed(() => {
const items: { key: string; icon: string; label: string; badge?: number }[] = [
{ key: 'basic', icon: 'info-circle', label: t('knowledgeEditor.sidebar.basic') },
feat: expose KB ↔ vector store binding in list, editor, and detail UI Backend ------- ListKnowledgeBases now enriches each row with the resolved vector_store metadata (name / source / engine_type / status) via a new buildKBListResponse helper. Store views are batch-resolved once per request through BatchResolveStoreView so an N-KB list costs one vector-store service call rather than N — closing the N+1 limitation flagged in #1372's known-limitations section. Cross-tenant shared KBs continue to render via SharedStoreDisplay so the owning tenant's store inventory cannot be correlated across rows; the underlying vector_store_id UUID is stripped from those responses. Resolver failures degrade gracefully: bound KBs render as unavailable instead of breaking the list. Test coverage pins the env / bound / shared distinction, the batch-call-count invariant, and the graceful-failure path. Frontend -------- KB editor modal gains a new "Vector Store" section. Create mode shows a dropdown that combines the system default (env store) and the tenant's configured user stores, fetched once at mount via the existing listVectorStores API. Edit mode shows the bound store read-only via a new VectorStoreBadge component with an explicit immutability hint — matching the backend's `<-:create` GORM tag and the service-layer UpdateKnowledgeBaseRequest DTO that already omit the field. KB list cards surface a small engine-type badge for own-tenant bound KBs, and a warning badge when the bound store is unavailable. Env-bound and shared KBs render no badge (visual noise control). KB detail header shows the bound store via the same VectorStoreBadge component; shared KBs fall through to the badge's internal "shared" branch with no name / engine / id rendered. The KB editor's create-time error handler translates the typed ErrVectorStoreBindingInvalid (2200) and ErrVectorStoreUnavailable (2201) into localized messages and jumps the user back to the VectorStore section so they can pick a different store or fall back to the system default. The KB row type gains five optional fields (vector_store_id / name / engine_type / source / status). i18n: 18 new keys added to en-US, ko-KR, zh-CN; ru-RU receives English placeholders pending translation (consistent with prior PRs in this locale). Part of #993 (Phase 2: Per-KB VectorStore Binding). Phase 2 roadmap item: PR 5 (KB binding UI + list-response enrichment). Depends on #994, #1310, #1372, #1386 (all backend in the Phase 2 series).
2026-05-18 14:50:09 +00:00
{ key: 'models', icon: 'control-platform', label: t('knowledgeEditor.sidebar.models') },
// VectorStore binding section — present in both create and edit
// modes. Create mode shows a dropdown; edit mode shows the bound
// store read-only with an immutability hint.
{ key: 'vectorStore', icon: 'data-base', label: t('knowledgeEditor.sidebar.vectorStore') }
]
if (formData.value?.type === 'faq') {
items.push({ key: 'faq', icon: 'help-circle', label: t('knowledgeEditor.sidebar.faq') })
} else {
items.push(
{ key: 'parser', icon: 'file-search', label: t('settings.parserEngine') },
{ key: 'multimodal', icon: 'image', label: t('knowledgeEditor.sidebar.multimodal') },
{ key: 'asr', icon: 'sound', label: t('knowledgeEditor.sidebar.asr') },
{ key: 'storage', icon: 'cloud', label: t('knowledgeEditor.sidebar.storage') },
{ key: 'chunking', icon: 'file-copy', label: t('knowledgeEditor.sidebar.chunking') },
{ key: 'graph', icon: 'chart-bubble', label: t('knowledgeEditor.sidebar.graph') },
{ key: 'advanced', icon: 'setting', label: t('knowledgeEditor.sidebar.advanced') }
)
if (props.mode === 'edit' && props.kbId) {
items.push({ key: 'datasource', icon: 'cloud-download', label: t('knowledgeEditor.sidebar.datasource'), badge: dsCount.value || undefined })
}
}
if (props.mode === 'edit' && props.kbId && !authStore.isLiteMode) {
items.push({ key: 'share', icon: 'share', label: t('knowledgeEditor.sidebar.share') })
}
return items
})
// 模型配置引用
const modelConfigRef = ref<InstanceType<typeof KBModelConfig>>()
const advancedSettingsRef = ref<InstanceType<typeof KBAdvancedSettings>>()
// 表单数据
const formData = ref<any>(null)
const isFAQ = computed(() => formData.value?.type === 'faq')
const kbCreateNeedsEmbedding = computed(() => {
if (!formData.value || formData.value.type === 'faq') return false
const s = formData.value.indexingStrategy
return Boolean(s?.vectorEnabled || s?.keywordEnabled)
})
const applyDefaultModelsIfEmpty = () => {
if (!formData.value || props.mode !== 'create') return
const pick = (type: ModelConfig['type']) => {
const list = allModels.value.filter((m) => m.type === type)
return list.find((m) => m.is_default) || list[0]
}
const chat = pick('KnowledgeQA')
const embedding = pick('Embedding')
if (!formData.value.modelConfig.llmModelId && chat?.id) {
formData.value.modelConfig.llmModelId = chat.id
}
if (!formData.value.modelConfig.embeddingModelId && embedding?.id) {
formData.value.modelConfig.embeddingModelId = embedding.id
}
}
watch(
() => formData.value?.type,
(newType, oldType) => {
if (!formData.value) return
if (newType === 'faq') {
if (!formData.value.faqConfig) {
formData.value.faqConfig = { indexMode: 'question_only', questionIndexMode: 'separate' }
}
if (!['basic', 'models', 'faq'].includes(currentSection.value)) {
currentSection.value = 'faq'
}
} else if (oldType === 'faq' && currentSection.value === 'faq') {
currentSection.value = 'basic'
}
}
)
// 初始化表单数据
const initFormData = (type: 'document' | 'faq' = 'document') => {
return {
type,
name: '',
description: '',
faqConfig: {
indexMode: 'question_only',
questionIndexMode: 'separate'
},
modelConfig: {
llmModelId: '',
embeddingModelId: '',
wikiSynthesisModelId: '',
},
chunkingConfig: {
chunkSize: 512,
docs(chunking): align overlap default + sharpen UI/source/repo docs Three documentation passes around the adaptive chunking work: UI - Frontend ChunkOverlap default consolidated to 80 (was 100), matching chunker.DefaultChunkOverlap on the backend. Both DEFAULT_CHUNKING_PRESET and initFormData updated. The KB-load fallback also uses 80 when a loaded KB has no chunk_overlap stored. - All four locales (en-US, zh-CN, ko-KR, ru-RU) get rewritten chunking setting descriptions: each now states the validated range, the default, and the situations where you'd deviate (FAQ vs narrative, embedder token limits, language-specific corpora). Source code - splitter.go: DefaultChunkSize / DefaultChunkOverlap constants get a longer block-comment explaining the per-language token math and the use-case sweet spots, plus the migration note on what the old inconsistent defaults were. - KBChunkingSettings.vue: new comment block above ChunkingConfig documents the slider min/max for each setting, why those bounds exist, and the recommended TokenLimit values per embedding model. Repo docs - New docs/CHUNKING.md: end-to-end guide covering why chunking matters, the adaptive 3-tier architecture, per-setting reference with ranges and sweet spots, parent-child explanation, the token-limit table per embedder (OpenAI / Voyage / Cohere / BGE / MiniLM / Jina), 7 use-case presets, the debug panel workflow, the API surface, and known trade-offs (recursive strategy hidden from UI, no auto-reindex on strategy switch, OCR limitations). - CHANGELOG.md gets a new [Unreleased] section consolidating all the adaptive-chunking work shipped on this branch: 5 features, 8 improvements, 6 fixes, 1 docs entry. The entry references docs/CHUNKING.md for deeper explanation. https://claude.ai/code/session_01XADhx6mtu2ZYW3DE9Lun6k
2026-05-03 11:57:03 +00:00
// 80 ≈ 15% of chunkSize — community-recommended sweet spot.
// Aligned with chunker.DefaultChunkOverlap on the backend.
chunkOverlap: 80,
separators: ['\n\n', '\n', '。', '!', '?', ';', ';'],
parserEngineRules: undefined as any,
enableParentChild: true,
parentChunkSize: 4096,
feat(frontend): expose chunking strategy in KB editor Surfaces the adaptive 3-tier chunking controls in the existing "Chunking" section of the KB editor modal. Users can now pick a strategy from a dropdown without crafting JSON for the API: - Automatic (recommended) → backend profiler picks the tier - Markdown-optimized → forces heading-aware splitting - Smart structure detection → forces heuristic boundary detection - Classic → original recursive splitter (legacy) The fifth backend value `recursive` is intentionally hidden from the UI — it's functionally near `legacy` and would dilute the choice. Advanced options (collapsible, disabled when strategy=legacy): - TokenLimit (0–8192 approx tokens; 0 = char-based budget) - Languages multi-select (DE/EN/ZH; empty = auto-detect) Behaviour: - New KBs default to strategy="auto" - Existing KBs without the field render with empty strategy and keep classic behavior on save unless the user actively picks one - Overlap warning when overlap >= chunkSize/2 Wired through: - KBChunkingSettings.vue: strategy select + advanced collapsible + ChunkingConfig interface extended - KnowledgeBaseEditorModal.vue: form-state defaults, kb-load mapping, buildSubmitData (chunking_config) + updateKBConfig (documentSplitting) pass strategy/token_limit/languages - api/initialization/index.ts: types extended - i18n: en-US / zh-CN / ko-KR / ru-RU all carry strategy + advanced keys (6 keys each) https://claude.ai/code/session_01XADhx6mtu2ZYW3DE9Lun6k
2026-05-02 20:40:07 +00:00
childChunkSize: 384,
// New KBs default to the adaptive auto-strategy. User can change in the UI.
strategy: 'auto' as string,
tokenLimit: 0,
languages: [] as string[]
},
storageProvider: '' as string,
multimodalConfig: {
enabled: false,
vllmModelId: ''
},
asrConfig: {
enabled: false,
modelId: '',
language: ''
},
nodeExtractConfig: {
enabled: false,
text: '',
tags: [] as string[],
nodes: [] as Array<{
name: string
attributes: string[]
}>,
relations: [] as Array<{
node1: string
node2: string
type: string
}>
},
questionGenerationConfig: {
enabled: true,
questionCount: 3
},
feat: Implement comprehensive wiki feature for knowledge bases This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes: **Backend Changes:** - Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log) - Database schema: wiki_pages table with full migration support - WikiPageService: CRUD operations and page management - WikiPageRepository: GORM-based persistence layer - Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents * Summary page generation using LLM * Entity and concept extraction in a single LLM call * Synthesis opportunity detection * Index page rebuilding * Log page maintenance - Wiki boost feature: Enhance chat retrieval with wiki context - Wiki linting: Maintenance and validation utilities - Agent wiki tools: Enable agents to query and interact with wiki pages - Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks - Language support: Reuse existing middleware language infrastructure for LLM prompts **Frontend Changes:** - Wiki browser UI: View all wiki pages with filtering and search - Wiki API client: Knowledge base wiki management endpoints - Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model) - i18n updates: Support for English, Korean, Russian, and Chinese interfaces **Configuration:** - Container DI: Wire up all wiki services - Router: Register wiki API endpoints - Task handling: Support async wiki ingest tasks **Testing:** - Unit tests for wiki page types - Service layer tests - Endpoint tests for wiki operations - Integration tests with LLM mocking **Documentation:** - Language refactoring analysis and guides - Implementation completion reports - Quick reference guides for developers **Key Features:** ✅ LLM-powered wiki page generation from documents ✅ Multi-language support (9+ languages) ✅ Automatic extraction of entities and concepts ✅ Synthesis opportunity detection ✅ Index and log page maintenance ✅ Progressive wiki building across multiple documents ✅ Agent-based wiki interaction ✅ Chat retrieval enhancement with wiki context ✅ Full frontend UI for wiki browsing Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
wikiConfig: {
synthesisModelId: '',
maxPagesPerIngest: 0,
extractionGranularity: 'standard' as 'focused' | 'standard' | 'exhaustive',
feat: Implement comprehensive wiki feature for knowledge bases This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes: **Backend Changes:** - Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log) - Database schema: wiki_pages table with full migration support - WikiPageService: CRUD operations and page management - WikiPageRepository: GORM-based persistence layer - Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents * Summary page generation using LLM * Entity and concept extraction in a single LLM call * Synthesis opportunity detection * Index page rebuilding * Log page maintenance - Wiki boost feature: Enhance chat retrieval with wiki context - Wiki linting: Maintenance and validation utilities - Agent wiki tools: Enable agents to query and interact with wiki pages - Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks - Language support: Reuse existing middleware language infrastructure for LLM prompts **Frontend Changes:** - Wiki browser UI: View all wiki pages with filtering and search - Wiki API client: Knowledge base wiki management endpoints - Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model) - i18n updates: Support for English, Korean, Russian, and Chinese interfaces **Configuration:** - Container DI: Wire up all wiki services - Router: Register wiki API endpoints - Task handling: Support async wiki ingest tasks **Testing:** - Unit tests for wiki page types - Service layer tests - Endpoint tests for wiki operations - Integration tests with LLM mocking **Documentation:** - Language refactoring analysis and guides - Implementation completion reports - Quick reference guides for developers **Key Features:** ✅ LLM-powered wiki page generation from documents ✅ Multi-language support (9+ languages) ✅ Automatic extraction of entities and concepts ✅ Synthesis opportunity detection ✅ Index and log page maintenance ✅ Progressive wiki building across multiple documents ✅ Agent-based wiki interaction ✅ Chat retrieval enhancement with wiki context ✅ Full frontend UI for wiki browsing Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
},
indexingStrategy: {
vectorEnabled: true,
keywordEnabled: true,
wikiEnabled: false,
graphEnabled: false,
},
feat: expose KB ↔ vector store binding in list, editor, and detail UI Backend ------- ListKnowledgeBases now enriches each row with the resolved vector_store metadata (name / source / engine_type / status) via a new buildKBListResponse helper. Store views are batch-resolved once per request through BatchResolveStoreView so an N-KB list costs one vector-store service call rather than N — closing the N+1 limitation flagged in #1372's known-limitations section. Cross-tenant shared KBs continue to render via SharedStoreDisplay so the owning tenant's store inventory cannot be correlated across rows; the underlying vector_store_id UUID is stripped from those responses. Resolver failures degrade gracefully: bound KBs render as unavailable instead of breaking the list. Test coverage pins the env / bound / shared distinction, the batch-call-count invariant, and the graceful-failure path. Frontend -------- KB editor modal gains a new "Vector Store" section. Create mode shows a dropdown that combines the system default (env store) and the tenant's configured user stores, fetched once at mount via the existing listVectorStores API. Edit mode shows the bound store read-only via a new VectorStoreBadge component with an explicit immutability hint — matching the backend's `<-:create` GORM tag and the service-layer UpdateKnowledgeBaseRequest DTO that already omit the field. KB list cards surface a small engine-type badge for own-tenant bound KBs, and a warning badge when the bound store is unavailable. Env-bound and shared KBs render no badge (visual noise control). KB detail header shows the bound store via the same VectorStoreBadge component; shared KBs fall through to the badge's internal "shared" branch with no name / engine / id rendered. The KB editor's create-time error handler translates the typed ErrVectorStoreBindingInvalid (2200) and ErrVectorStoreUnavailable (2201) into localized messages and jumps the user back to the VectorStore section so they can pick a different store or fall back to the system default. The KB row type gains five optional fields (vector_store_id / name / engine_type / source / status). i18n: 18 new keys added to en-US, ko-KR, zh-CN; ru-RU receives English placeholders pending translation (consistent with prior PRs in this locale). Part of #993 (Phase 2: Per-KB VectorStore Binding). Phase 2 roadmap item: PR 5 (KB binding UI + list-response enrichment). Depends on #994, #1310, #1372, #1386 (all backend in the Phase 2 series).
2026-05-18 14:50:09 +00:00
// Vector-store binding. Empty string means "use the env-configured
// store"; create mode defaults to that, edit mode loads the
// existing binding from the KB response below.
vectorStoreId: '' as string,
vectorStoreInfo: {
source: undefined as string | undefined,
name: undefined as string | undefined,
engineType: undefined as string | undefined,
status: undefined as string | undefined,
},
}
}
// 加载所有模型
const loadAllModels = async (force = false) => {
try {
await chatResources.ensureModels(force)
allModels.value = chatResources.allModels || []
} catch (error) {
console.error('Failed to load model list:', error)
MessagePlugin.error(t('knowledgeEditor.messages.loadModelsFailed'))
allModels.value = []
}
}
// 加载知识库数据(编辑模式)
const loadKBData = async () => {
if (props.mode !== 'edit' || !props.kbId) return
loading.value = true
try {
const [kbInfo, filesResult] = await Promise.all([
getKnowledgeBaseById(props.kbId),
listKnowledgeFiles(props.kbId, { page: 1, page_size: 1 })
])
if (!kbInfo || !kbInfo.data) {
throw new Error(t('knowledgeEditor.messages.notFound'))
}
const kb = kbInfo.data
hasFiles.value = (filesResult as any)?.total > 0
kbCreatorId.value = (kb as any).creator_id || ''
// 设置表单数据
const kbType = (kb.type as 'document' | 'faq') || 'document'
formData.value = {
type: kbType,
name: kb.name || '',
description: kb.description || '',
faqConfig: {
indexMode: kb.faq_config?.index_mode || 'question_only',
questionIndexMode: kb.faq_config?.question_index_mode || 'separate'
},
modelConfig: {
llmModelId: kb.summary_model_id || '',
embeddingModelId: kb.embedding_model_id || '',
wikiSynthesisModelId: kb.wiki_config?.synthesis_model_id || ''
},
chunkingConfig: {
chunkSize: kb.chunking_config?.chunk_size || 512,
docs(chunking): align overlap default + sharpen UI/source/repo docs Three documentation passes around the adaptive chunking work: UI - Frontend ChunkOverlap default consolidated to 80 (was 100), matching chunker.DefaultChunkOverlap on the backend. Both DEFAULT_CHUNKING_PRESET and initFormData updated. The KB-load fallback also uses 80 when a loaded KB has no chunk_overlap stored. - All four locales (en-US, zh-CN, ko-KR, ru-RU) get rewritten chunking setting descriptions: each now states the validated range, the default, and the situations where you'd deviate (FAQ vs narrative, embedder token limits, language-specific corpora). Source code - splitter.go: DefaultChunkSize / DefaultChunkOverlap constants get a longer block-comment explaining the per-language token math and the use-case sweet spots, plus the migration note on what the old inconsistent defaults were. - KBChunkingSettings.vue: new comment block above ChunkingConfig documents the slider min/max for each setting, why those bounds exist, and the recommended TokenLimit values per embedding model. Repo docs - New docs/CHUNKING.md: end-to-end guide covering why chunking matters, the adaptive 3-tier architecture, per-setting reference with ranges and sweet spots, parent-child explanation, the token-limit table per embedder (OpenAI / Voyage / Cohere / BGE / MiniLM / Jina), 7 use-case presets, the debug panel workflow, the API surface, and known trade-offs (recursive strategy hidden from UI, no auto-reindex on strategy switch, OCR limitations). - CHANGELOG.md gets a new [Unreleased] section consolidating all the adaptive-chunking work shipped on this branch: 5 features, 8 improvements, 6 fixes, 1 docs entry. The entry references docs/CHUNKING.md for deeper explanation. https://claude.ai/code/session_01XADhx6mtu2ZYW3DE9Lun6k
2026-05-03 11:57:03 +00:00
// Fallback only used when the loaded KB has no chunk_overlap stored.
// Aligned with chunker.DefaultChunkOverlap on the backend.
chunkOverlap: kb.chunking_config?.chunk_overlap || 80,
separators: kb.chunking_config?.separators || ['\n\n', '\n', '。', '!', '?', ';', ';'],
parserEngineRules: kb.chunking_config?.parser_engine_rules || undefined,
enableParentChild: kb.chunking_config?.enable_parent_child || false,
parentChunkSize: kb.chunking_config?.parent_chunk_size || 4096,
feat(frontend): expose chunking strategy in KB editor Surfaces the adaptive 3-tier chunking controls in the existing "Chunking" section of the KB editor modal. Users can now pick a strategy from a dropdown without crafting JSON for the API: - Automatic (recommended) → backend profiler picks the tier - Markdown-optimized → forces heading-aware splitting - Smart structure detection → forces heuristic boundary detection - Classic → original recursive splitter (legacy) The fifth backend value `recursive` is intentionally hidden from the UI — it's functionally near `legacy` and would dilute the choice. Advanced options (collapsible, disabled when strategy=legacy): - TokenLimit (0–8192 approx tokens; 0 = char-based budget) - Languages multi-select (DE/EN/ZH; empty = auto-detect) Behaviour: - New KBs default to strategy="auto" - Existing KBs without the field render with empty strategy and keep classic behavior on save unless the user actively picks one - Overlap warning when overlap >= chunkSize/2 Wired through: - KBChunkingSettings.vue: strategy select + advanced collapsible + ChunkingConfig interface extended - KnowledgeBaseEditorModal.vue: form-state defaults, kb-load mapping, buildSubmitData (chunking_config) + updateKBConfig (documentSplitting) pass strategy/token_limit/languages - api/initialization/index.ts: types extended - i18n: en-US / zh-CN / ko-KR / ru-RU all carry strategy + advanced keys (6 keys each) https://claude.ai/code/session_01XADhx6mtu2ZYW3DE9Lun6k
2026-05-02 20:40:07 +00:00
childChunkSize: kb.chunking_config?.child_chunk_size || 384,
// Existing KBs without strategy field render as empty (= legacy behavior).
// The user has to actively pick a value to opt in to the new tiers.
strategy: kb.chunking_config?.strategy || '',
tokenLimit: kb.chunking_config?.token_limit || 0,
languages: kb.chunking_config?.languages || []
},
storageProvider: (kb.storage_provider_config?.provider || kb.storage_config?.provider || 'local') as string,
multimodalConfig: {
enabled: !!kb.vlm_config?.enabled,
vllmModelId: kb.vlm_config?.model_id || ''
},
asrConfig: {
enabled: !!kb.asr_config?.enabled,
modelId: kb.asr_config?.model_id || '',
language: kb.asr_config?.language || ''
},
nodeExtractConfig: {
enabled: kb.extract_config?.enabled || false,
text: kb.extract_config?.text || '',
tags: kb.extract_config?.tags || [],
nodes: (kb.extract_config?.nodes || []).map((node: any) => ({
name: node.name,
attributes: node.attributes || []
})),
relations: kb.extract_config?.relations || []
},
questionGenerationConfig: {
enabled: kb.question_generation_config?.enabled || false,
questionCount: kb.question_generation_config?.question_count || 3
},
feat: Implement comprehensive wiki feature for knowledge bases This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes: **Backend Changes:** - Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log) - Database schema: wiki_pages table with full migration support - WikiPageService: CRUD operations and page management - WikiPageRepository: GORM-based persistence layer - Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents * Summary page generation using LLM * Entity and concept extraction in a single LLM call * Synthesis opportunity detection * Index page rebuilding * Log page maintenance - Wiki boost feature: Enhance chat retrieval with wiki context - Wiki linting: Maintenance and validation utilities - Agent wiki tools: Enable agents to query and interact with wiki pages - Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks - Language support: Reuse existing middleware language infrastructure for LLM prompts **Frontend Changes:** - Wiki browser UI: View all wiki pages with filtering and search - Wiki API client: Knowledge base wiki management endpoints - Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model) - i18n updates: Support for English, Korean, Russian, and Chinese interfaces **Configuration:** - Container DI: Wire up all wiki services - Router: Register wiki API endpoints - Task handling: Support async wiki ingest tasks **Testing:** - Unit tests for wiki page types - Service layer tests - Endpoint tests for wiki operations - Integration tests with LLM mocking **Documentation:** - Language refactoring analysis and guides - Implementation completion reports - Quick reference guides for developers **Key Features:** ✅ LLM-powered wiki page generation from documents ✅ Multi-language support (9+ languages) ✅ Automatic extraction of entities and concepts ✅ Synthesis opportunity detection ✅ Index and log page maintenance ✅ Progressive wiki building across multiple documents ✅ Agent-based wiki interaction ✅ Chat retrieval enhancement with wiki context ✅ Full frontend UI for wiki browsing Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
wikiConfig: {
synthesisModelId: kb.wiki_config?.synthesis_model_id || '',
maxPagesPerIngest: kb.wiki_config?.max_pages_per_ingest || 0,
extractionGranularity: (
kb.wiki_config?.extraction_granularity === 'focused' ||
kb.wiki_config?.extraction_granularity === 'exhaustive'
? kb.wiki_config.extraction_granularity
: 'standard'
) as 'focused' | 'standard' | 'exhaustive',
feat: Implement comprehensive wiki feature for knowledge bases This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes: **Backend Changes:** - Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log) - Database schema: wiki_pages table with full migration support - WikiPageService: CRUD operations and page management - WikiPageRepository: GORM-based persistence layer - Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents * Summary page generation using LLM * Entity and concept extraction in a single LLM call * Synthesis opportunity detection * Index page rebuilding * Log page maintenance - Wiki boost feature: Enhance chat retrieval with wiki context - Wiki linting: Maintenance and validation utilities - Agent wiki tools: Enable agents to query and interact with wiki pages - Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks - Language support: Reuse existing middleware language infrastructure for LLM prompts **Frontend Changes:** - Wiki browser UI: View all wiki pages with filtering and search - Wiki API client: Knowledge base wiki management endpoints - Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model) - i18n updates: Support for English, Korean, Russian, and Chinese interfaces **Configuration:** - Container DI: Wire up all wiki services - Router: Register wiki API endpoints - Task handling: Support async wiki ingest tasks **Testing:** - Unit tests for wiki page types - Service layer tests - Endpoint tests for wiki operations - Integration tests with LLM mocking **Documentation:** - Language refactoring analysis and guides - Implementation completion reports - Quick reference guides for developers **Key Features:** ✅ LLM-powered wiki page generation from documents ✅ Multi-language support (9+ languages) ✅ Automatic extraction of entities and concepts ✅ Synthesis opportunity detection ✅ Index and log page maintenance ✅ Progressive wiki building across multiple documents ✅ Agent-based wiki interaction ✅ Chat retrieval enhancement with wiki context ✅ Full frontend UI for wiki browsing Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
},
indexingStrategy: {
vectorEnabled: kb.indexing_strategy?.vector_enabled ?? true,
keywordEnabled: kb.indexing_strategy?.keyword_enabled ?? true,
wikiEnabled: kb.indexing_strategy?.wiki_enabled ?? false,
graphEnabled: kb.indexing_strategy?.graph_enabled ?? false,
},
feat: expose KB ↔ vector store binding in list, editor, and detail UI Backend ------- ListKnowledgeBases now enriches each row with the resolved vector_store metadata (name / source / engine_type / status) via a new buildKBListResponse helper. Store views are batch-resolved once per request through BatchResolveStoreView so an N-KB list costs one vector-store service call rather than N — closing the N+1 limitation flagged in #1372's known-limitations section. Cross-tenant shared KBs continue to render via SharedStoreDisplay so the owning tenant's store inventory cannot be correlated across rows; the underlying vector_store_id UUID is stripped from those responses. Resolver failures degrade gracefully: bound KBs render as unavailable instead of breaking the list. Test coverage pins the env / bound / shared distinction, the batch-call-count invariant, and the graceful-failure path. Frontend -------- KB editor modal gains a new "Vector Store" section. Create mode shows a dropdown that combines the system default (env store) and the tenant's configured user stores, fetched once at mount via the existing listVectorStores API. Edit mode shows the bound store read-only via a new VectorStoreBadge component with an explicit immutability hint — matching the backend's `<-:create` GORM tag and the service-layer UpdateKnowledgeBaseRequest DTO that already omit the field. KB list cards surface a small engine-type badge for own-tenant bound KBs, and a warning badge when the bound store is unavailable. Env-bound and shared KBs render no badge (visual noise control). KB detail header shows the bound store via the same VectorStoreBadge component; shared KBs fall through to the badge's internal "shared" branch with no name / engine / id rendered. The KB editor's create-time error handler translates the typed ErrVectorStoreBindingInvalid (2200) and ErrVectorStoreUnavailable (2201) into localized messages and jumps the user back to the VectorStore section so they can pick a different store or fall back to the system default. The KB row type gains five optional fields (vector_store_id / name / engine_type / source / status). i18n: 18 new keys added to en-US, ko-KR, zh-CN; ru-RU receives English placeholders pending translation (consistent with prior PRs in this locale). Part of #993 (Phase 2: Per-KB VectorStore Binding). Phase 2 roadmap item: PR 5 (KB binding UI + list-response enrichment). Depends on #994, #1310, #1372, #1386 (all backend in the Phase 2 series).
2026-05-18 14:50:09 +00:00
// Vector-store binding. vectorStoreId is editor-only state; it
// is only included in the create request, never the update
// request, because the binding is immutable after creation.
// vectorStoreInfo carries the read-only display fields that the
// edit view renders below; they come straight from the KB
// response.
vectorStoreId: '',
vectorStoreInfo: {
source: kb.vector_store_source,
name: kb.vector_store_name,
engineType: kb.vector_store_engine_type,
status: kb.vector_store_status,
},
}
initialStorageProvider.value = formData.value.storageProvider
initialIndexingStrategy.value = { ...formData.value.indexingStrategy }
} catch (error) {
console.error('Failed to load knowledge base data:', error)
MessagePlugin.error(t('knowledgeEditor.messages.loadDataFailed'))
handleClose()
} finally {
loading.value = false
}
}
// 处理配置更新
const handleModelConfigUpdate = (config: any) => {
if (formData.value) {
formData.value.modelConfig = { ...config }
}
}
// 粒度选择器:从 formData.wikiConfig 读出并规范化,未知值回退到 'standard',
// 与后端 WikiExtractionGranularity.Normalize() 的契约保持一致。
const resolvedGranularity = computed<'focused' | 'standard' | 'exhaustive'>(() => {
const g = formData.value?.wikiConfig?.extractionGranularity
if (g === 'focused' || g === 'standard' || g === 'exhaustive') {
return g
}
return 'standard'
})
const granularityHint = computed<string>(() => {
switch (resolvedGranularity.value) {
case 'focused':
return t('knowledgeEditor.wiki.granularityFocusedHint')
case 'exhaustive':
return t('knowledgeEditor.wiki.granularityExhaustiveHint')
default:
return t('knowledgeEditor.wiki.granularityStandardHint')
}
})
const handleGranularityChange = (value: string | number | boolean) => {
if (!formData.value) return
const next: 'focused' | 'standard' | 'exhaustive' =
value === 'focused' || value === 'exhaustive'
? (value as 'focused' | 'exhaustive')
: 'standard'
formData.value.wikiConfig = {
...formData.value.wikiConfig,
extractionGranularity: next,
}
}
const isIndexingLocked = computed(() => props.mode === 'edit' && hasFiles.value)
const toggleVectorIndexing = () => {
if (!formData.value) return
if (isIndexingLocked.value) return
const next = !formData.value.indexingStrategy.vectorEnabled
formData.value.indexingStrategy.vectorEnabled = next
formData.value.indexingStrategy.keywordEnabled = next
}
const toggleWikiIndexing = () => {
if (!formData.value) return
if (isIndexingLocked.value) return
formData.value.indexingStrategy.wikiEnabled = !formData.value.indexingStrategy.wikiEnabled
}
const handleChunkingConfigUpdate = (config: any) => {
if (formData.value) {
formData.value.chunkingConfig = { ...config }
// 用户已经手动触达分块设置,后续索引策略切换不再覆盖这些值
chunkingDirty.value = true
}
}
// 判断当前是否为「仅 Wiki 索引」:只开了 Wiki,关了向量/关键词检索
const isWikiOnlyStrategy = computed(() => {
const s = formData.value?.indexingStrategy
if (!s) return false
return !!s.wikiEnabled && !s.vectorEnabled && !s.keywordEnabled
})
// 仅在创建模式、用户未改过分块设置时,随索引策略自动应用/撤销 Wiki-only 预设。
// 编辑模式严格保持后端已有配置不变,避免误改。
watch(isWikiOnlyStrategy, (wikiOnly) => {
if (props.mode !== 'create') return
if (!formData.value) return
if (chunkingDirty.value) return
const preset = wikiOnly ? WIKI_ONLY_CHUNKING_PRESET : DEFAULT_CHUNKING_PRESET
formData.value.chunkingConfig = {
...formData.value.chunkingConfig,
...preset,
}
})
const handleParserEngineRulesUpdate = (rules: any[]) => {
if (formData.value) {
formData.value.chunkingConfig.parserEngineRules = rules?.length ? rules : undefined
}
}
const handleMultimodalToggle = () => {
if (formData.value && !formData.value.multimodalConfig.enabled) {
formData.value.multimodalConfig.vllmModelId = ''
}
}
const handleMultimodalVLLMChange = (modelId: string) => {
if (formData.value) {
formData.value.multimodalConfig.vllmModelId = modelId
}
}
const handleAddVLLMModel = () => {
uiStore.openSettings('models', 'vllm')
}
const handleAddASRModel = () => {
uiStore.openSettings('models', 'asr')
}
const handleAddWikiModel = () => {
uiStore.openSettings('models', 'knowledgeqa')
}
const handleStorageProviderUpdate = (value: string) => {
if (formData.value) {
formData.value.storageProvider = value || tenantDefaultStorageProvider.value || 'local'
}
}
async function loadTenantDefaultStorageProvider(force = false) {
try {
await editorResources.ensureStorageEngine(force)
tenantDefaultStorageProvider.value = editorResources.storageConfig?.default_provider || 'local'
} catch {
tenantDefaultStorageProvider.value = 'local'
}
}
/** Resolved storage provider for create payload (never silently default to local before tenant config loads). */
function resolvedStorageProvider(): string {
const explicit = formData.value?.storageProvider?.trim()
if (explicit) return explicit
return tenantDefaultStorageProvider.value || 'local'
}
feat: expose KB ↔ vector store binding in list, editor, and detail UI Backend ------- ListKnowledgeBases now enriches each row with the resolved vector_store metadata (name / source / engine_type / status) via a new buildKBListResponse helper. Store views are batch-resolved once per request through BatchResolveStoreView so an N-KB list costs one vector-store service call rather than N — closing the N+1 limitation flagged in #1372's known-limitations section. Cross-tenant shared KBs continue to render via SharedStoreDisplay so the owning tenant's store inventory cannot be correlated across rows; the underlying vector_store_id UUID is stripped from those responses. Resolver failures degrade gracefully: bound KBs render as unavailable instead of breaking the list. Test coverage pins the env / bound / shared distinction, the batch-call-count invariant, and the graceful-failure path. Frontend -------- KB editor modal gains a new "Vector Store" section. Create mode shows a dropdown that combines the system default (env store) and the tenant's configured user stores, fetched once at mount via the existing listVectorStores API. Edit mode shows the bound store read-only via a new VectorStoreBadge component with an explicit immutability hint — matching the backend's `<-:create` GORM tag and the service-layer UpdateKnowledgeBaseRequest DTO that already omit the field. KB list cards surface a small engine-type badge for own-tenant bound KBs, and a warning badge when the bound store is unavailable. Env-bound and shared KBs render no badge (visual noise control). KB detail header shows the bound store via the same VectorStoreBadge component; shared KBs fall through to the badge's internal "shared" branch with no name / engine / id rendered. The KB editor's create-time error handler translates the typed ErrVectorStoreBindingInvalid (2200) and ErrVectorStoreUnavailable (2201) into localized messages and jumps the user back to the VectorStore section so they can pick a different store or fall back to the system default. The KB row type gains five optional fields (vector_store_id / name / engine_type / source / status). i18n: 18 new keys added to en-US, ko-KR, zh-CN; ru-RU receives English placeholders pending translation (consistent with prior PRs in this locale). Part of #993 (Phase 2: Per-KB VectorStore Binding). Phase 2 roadmap item: PR 5 (KB binding UI + list-response enrichment). Depends on #994, #1310, #1372, #1386 (all backend in the Phase 2 series).
2026-05-18 14:50:09 +00:00
const handleVectorStoreIdUpdate = (id: string) => {
if (formData.value) {
// Empty string here means "use system default" (env-store fallback).
// The create-payload assembly below converts this back to `omit` so
// the backend stores NULL — keeping the wire shape identical to
// pre-Phase-2 clients.
formData.value.vectorStoreId = id || ''
}
}
const handleQuestionGenerationUpdate = (config: any) => {
if (formData.value) {
formData.value.questionGenerationConfig = { ...config }
}
}
const handleNodeExtractUpdate = (config: any) => {
if (formData.value) {
formData.value.nodeExtractConfig = { ...config }
}
}
// 验证表单
const validateForm = (): boolean => {
if (!formData.value) return false
// 验证基本信息
if (!formData.value.name || !formData.value.name.trim()) {
MessagePlugin.warning(t('knowledgeEditor.messages.nameRequired'))
currentSection.value = 'basic'
return false
}
// 验证索引策略 — 文档类型至少需要开启一种
if (formData.value.type !== 'faq') {
const s = formData.value.indexingStrategy
if (s && !s.vectorEnabled && !s.keywordEnabled && !s.wikiEnabled && !s.graphEnabled) {
MessagePlugin.warning(t('knowledgeEditor.indexing.atLeastOne'))
currentSection.value = 'basic'
return false
}
}
// 验证模型配置 - embedding 模型仅在检索索引启用时必须
const needsEmbedding = formData.value.indexingStrategy?.vectorEnabled || formData.value.indexingStrategy?.keywordEnabled
if (needsEmbedding && !formData.value.modelConfig.embeddingModelId) {
MessagePlugin.warning(t('knowledgeEditor.indexing.embeddingRequired'))
currentSection.value = 'models'
return false
}
if (!formData.value.modelConfig.llmModelId) {
MessagePlugin.warning(t('knowledgeEditor.messages.summaryRequired'))
currentSection.value = 'models'
return false
}
// 验证多模态配置(如果启用)
if (formData.value.multimodalConfig.enabled && !formData.value.multimodalConfig.vllmModelId) {
MessagePlugin.warning(t('knowledgeEditor.messages.multimodalInvalid'))
currentSection.value = 'multimodal'
return false
}
if (formData.value.type === 'faq' && !formData.value.faqConfig?.indexMode) {
MessagePlugin.warning(t('knowledgeEditor.messages.indexModeRequired'))
currentSection.value = 'faq'
return false
}
return true
}
// 构建提交数据
const buildSubmitData = () => {
if (!formData.value) return null
const data: any = {
name: formData.value.name,
description: formData.value.description,
type: formData.value.type,
chunking_config: {
chunk_size: formData.value.chunkingConfig.chunkSize,
chunk_overlap: formData.value.chunkingConfig.chunkOverlap,
separators: formData.value.chunkingConfig.separators,
enable_parent_child: formData.value.chunkingConfig.enableParentChild,
parent_chunk_size: formData.value.chunkingConfig.parentChunkSize,
child_chunk_size: formData.value.chunkingConfig.childChunkSize,
fix(chunker): QA audit — pointer DTOs, profile reuse, stats correctness Resolves the issues surfaced by the post-Phase-3 self-review. High severity - Strategy / TokenLimit / Languages can now be reset. The KB-config handler uses pointer DTOs so the absence of a field in the payload means "no change" while an explicit empty string / 0 / [] clears the value. The frontend now sends the fields unconditionally so the user can revert to defaults via the clear icon — previously these fields were write-once. - DocProfile is no longer computed twice in the preview endpoint. Diagnostics carries the profile that drove tier selection (when auto-strategy ran); the handler only re-profiles for explicit strategies that bypass the profiler. - Chunk-size stats (avg / min / max / stddev) are now computed over the FULL chunk set before the response is truncated to previewMaxChunks. Avoids systematically misleading metrics for large documents. - SplitWithDiagnostics defaults SelectedTier to TierLegacy so an empty-text request never leaves the diag with a blank tier string. Medium severity - Split() reverts to its own loop instead of delegating to SplitWithDiagnostics. Diagnostics struct allocation is reserved for callers that actually want the trace (preview endpoint). Matters in SplitParentChild where Split runs once per parent. - Preview endpoint runs the splitter on a goroutine wrapped in a 5s context.WithTimeout. CJK input at the 256k-rune ceiling could otherwise tie up the worker for several seconds. Low severity - KBChunkingSettings emits arrays via spread copies so parent-side mutation cannot drift the form's reactive state. - KBChunkingDebug font-family includes a monospace fallback so the chunk content stays monospaced even when the TDesign CSS variable is missing. Documentation - DocProfile JSON shape is now annotated as part of the public preview API; field renames would be breaking. https://claude.ai/code/session_01XADhx6mtu2ZYW3DE9Lun6k
2026-05-03 07:01:20 +00:00
// Adaptive chunking fields are always sent (empty/zero values
// included) so the user can clear them — backend uses pointer DTOs
// to distinguish "not in payload" from "explicitly empty".
strategy: formData.value.chunkingConfig.strategy ?? '',
token_limit: formData.value.chunkingConfig.tokenLimit ?? 0,
languages: formData.value.chunkingConfig.languages ?? [],
...(formData.value.chunkingConfig.parserEngineRules?.length
? { parser_engine_rules: formData.value.chunkingConfig.parserEngineRules }
: {})
},
embedding_model_id: formData.value.modelConfig.embeddingModelId,
summary_model_id: formData.value.modelConfig.llmModelId
}
feat: expose KB ↔ vector store binding in list, editor, and detail UI Backend ------- ListKnowledgeBases now enriches each row with the resolved vector_store metadata (name / source / engine_type / status) via a new buildKBListResponse helper. Store views are batch-resolved once per request through BatchResolveStoreView so an N-KB list costs one vector-store service call rather than N — closing the N+1 limitation flagged in #1372's known-limitations section. Cross-tenant shared KBs continue to render via SharedStoreDisplay so the owning tenant's store inventory cannot be correlated across rows; the underlying vector_store_id UUID is stripped from those responses. Resolver failures degrade gracefully: bound KBs render as unavailable instead of breaking the list. Test coverage pins the env / bound / shared distinction, the batch-call-count invariant, and the graceful-failure path. Frontend -------- KB editor modal gains a new "Vector Store" section. Create mode shows a dropdown that combines the system default (env store) and the tenant's configured user stores, fetched once at mount via the existing listVectorStores API. Edit mode shows the bound store read-only via a new VectorStoreBadge component with an explicit immutability hint — matching the backend's `<-:create` GORM tag and the service-layer UpdateKnowledgeBaseRequest DTO that already omit the field. KB list cards surface a small engine-type badge for own-tenant bound KBs, and a warning badge when the bound store is unavailable. Env-bound and shared KBs render no badge (visual noise control). KB detail header shows the bound store via the same VectorStoreBadge component; shared KBs fall through to the badge's internal "shared" branch with no name / engine / id rendered. The KB editor's create-time error handler translates the typed ErrVectorStoreBindingInvalid (2200) and ErrVectorStoreUnavailable (2201) into localized messages and jumps the user back to the VectorStore section so they can pick a different store or fall back to the system default. The KB row type gains five optional fields (vector_store_id / name / engine_type / source / status). i18n: 18 new keys added to en-US, ko-KR, zh-CN; ru-RU receives English placeholders pending translation (consistent with prior PRs in this locale). Part of #993 (Phase 2: Per-KB VectorStore Binding). Phase 2 roadmap item: PR 5 (KB binding UI + list-response enrichment). Depends on #994, #1310, #1372, #1386 (all backend in the Phase 2 series).
2026-05-18 14:50:09 +00:00
// Vector-store binding. Only attach the field when the user actively
// selected a non-default store. The server treats an empty string as
// NULL, but keeping the field absent on the wire matches what a
// client that doesn't know about this binding would send — which
// makes A/B response diffs easier to read.
if (formData.value.vectorStoreId) {
data.vector_store_id = formData.value.vectorStoreId
}
// 添加多模态配置
data.vlm_config = {
enabled: formData.value.multimodalConfig.enabled,
model_id: formData.value.multimodalConfig.enabled
? (formData.value.multimodalConfig.vllmModelId || '')
: ''
}
// 添加ASR语音识别配置
data.asr_config = {
enabled: formData.value.asrConfig?.enabled || false,
model_id: formData.value.asrConfig?.enabled
? (formData.value.asrConfig?.modelId || '')
: '',
language: formData.value.asrConfig?.language || ''
}
// 存储引擎:仅传 provider,参数从全局设置读取
// Write to storage_provider_config (authoritative) + storage_config (legacy dual-write)
const storageProvider = resolvedStorageProvider()
data.storage_provider_config = {
provider: storageProvider
}
data.storage_config = {
provider: storageProvider
}
// 添加知识图谱配置 — now synced via indexingStrategy.graphEnabled
// extract_config is sent below along with indexing_strategy
// 添加问题生成配置
if (formData.value.questionGenerationConfig?.enabled) {
data.question_generation_config = {
enabled: true,
question_count: formData.value.questionGenerationConfig.questionCount || 3
}
}
if (formData.value.type === 'faq') {
data.faq_config = {
index_mode: formData.value.faqConfig?.indexMode || 'question_only',
question_index_mode: formData.value.faqConfig?.questionIndexMode || 'separate'
}
}
// Wiki enablement is carried solely by indexing_strategy.wiki_enabled.
// wiki_config only holds wiki-specific tunables.
if (formData.value.type !== 'faq') {
feat: Implement comprehensive wiki feature for knowledge bases This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes: **Backend Changes:** - Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log) - Database schema: wiki_pages table with full migration support - WikiPageService: CRUD operations and page management - WikiPageRepository: GORM-based persistence layer - Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents * Summary page generation using LLM * Entity and concept extraction in a single LLM call * Synthesis opportunity detection * Index page rebuilding * Log page maintenance - Wiki boost feature: Enhance chat retrieval with wiki context - Wiki linting: Maintenance and validation utilities - Agent wiki tools: Enable agents to query and interact with wiki pages - Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks - Language support: Reuse existing middleware language infrastructure for LLM prompts **Frontend Changes:** - Wiki browser UI: View all wiki pages with filtering and search - Wiki API client: Knowledge base wiki management endpoints - Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model) - i18n updates: Support for English, Korean, Russian, and Chinese interfaces **Configuration:** - Container DI: Wire up all wiki services - Router: Register wiki API endpoints - Task handling: Support async wiki ingest tasks **Testing:** - Unit tests for wiki page types - Service layer tests - Endpoint tests for wiki operations - Integration tests with LLM mocking **Documentation:** - Language refactoring analysis and guides - Implementation completion reports - Quick reference guides for developers **Key Features:** ✅ LLM-powered wiki page generation from documents ✅ Multi-language support (9+ languages) ✅ Automatic extraction of entities and concepts ✅ Synthesis opportunity detection ✅ Index and log page maintenance ✅ Progressive wiki building across multiple documents ✅ Agent-based wiki interaction ✅ Chat retrieval enhancement with wiki context ✅ Full frontend UI for wiki browsing Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
data.wiki_config = {
synthesis_model_id: formData.value.modelConfig?.wikiSynthesisModelId || '',
feat: Implement comprehensive wiki feature for knowledge bases This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes: **Backend Changes:** - Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log) - Database schema: wiki_pages table with full migration support - WikiPageService: CRUD operations and page management - WikiPageRepository: GORM-based persistence layer - Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents * Summary page generation using LLM * Entity and concept extraction in a single LLM call * Synthesis opportunity detection * Index page rebuilding * Log page maintenance - Wiki boost feature: Enhance chat retrieval with wiki context - Wiki linting: Maintenance and validation utilities - Agent wiki tools: Enable agents to query and interact with wiki pages - Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks - Language support: Reuse existing middleware language infrastructure for LLM prompts **Frontend Changes:** - Wiki browser UI: View all wiki pages with filtering and search - Wiki API client: Knowledge base wiki management endpoints - Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model) - i18n updates: Support for English, Korean, Russian, and Chinese interfaces **Configuration:** - Container DI: Wire up all wiki services - Router: Register wiki API endpoints - Task handling: Support async wiki ingest tasks **Testing:** - Unit tests for wiki page types - Service layer tests - Endpoint tests for wiki operations - Integration tests with LLM mocking **Documentation:** - Language refactoring analysis and guides - Implementation completion reports - Quick reference guides for developers **Key Features:** ✅ LLM-powered wiki page generation from documents ✅ Multi-language support (9+ languages) ✅ Automatic extraction of entities and concepts ✅ Synthesis opportunity detection ✅ Index and log page maintenance ✅ Progressive wiki building across multiple documents ✅ Agent-based wiki interaction ✅ Chat retrieval enhancement with wiki context ✅ Full frontend UI for wiki browsing Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
max_pages_per_ingest: formData.value.wikiConfig?.maxPagesPerIngest || 0,
extraction_granularity: formData.value.wikiConfig?.extractionGranularity || 'standard',
feat: Implement comprehensive wiki feature for knowledge bases This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes: **Backend Changes:** - Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log) - Database schema: wiki_pages table with full migration support - WikiPageService: CRUD operations and page management - WikiPageRepository: GORM-based persistence layer - Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents * Summary page generation using LLM * Entity and concept extraction in a single LLM call * Synthesis opportunity detection * Index page rebuilding * Log page maintenance - Wiki boost feature: Enhance chat retrieval with wiki context - Wiki linting: Maintenance and validation utilities - Agent wiki tools: Enable agents to query and interact with wiki pages - Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks - Language support: Reuse existing middleware language infrastructure for LLM prompts **Frontend Changes:** - Wiki browser UI: View all wiki pages with filtering and search - Wiki API client: Knowledge base wiki management endpoints - Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model) - i18n updates: Support for English, Korean, Russian, and Chinese interfaces **Configuration:** - Container DI: Wire up all wiki services - Router: Register wiki API endpoints - Task handling: Support async wiki ingest tasks **Testing:** - Unit tests for wiki page types - Service layer tests - Endpoint tests for wiki operations - Integration tests with LLM mocking **Documentation:** - Language refactoring analysis and guides - Implementation completion reports - Quick reference guides for developers **Key Features:** ✅ LLM-powered wiki page generation from documents ✅ Multi-language support (9+ languages) ✅ Automatic extraction of entities and concepts ✅ Synthesis opportunity detection ✅ Index and log page maintenance ✅ Progressive wiki building across multiple documents ✅ Agent-based wiki interaction ✅ Chat retrieval enhancement with wiki context ✅ Full frontend UI for wiki browsing Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
}
}
// Send indexing strategy
if (formData.value.type !== 'faq') {
data.indexing_strategy = {
vector_enabled: formData.value.indexingStrategy?.vectorEnabled ?? true,
keyword_enabled: formData.value.indexingStrategy?.keywordEnabled ?? true,
wiki_enabled: formData.value.indexingStrategy?.wikiEnabled ?? false,
graph_enabled: formData.value.indexingStrategy?.graphEnabled ?? false,
}
}
// Always persist extract_config so the toggle state from GraphSettings is saved,
// regardless of whether the graph indexing strategy is currently enabled.
if (formData.value.nodeExtractConfig) {
data.extract_config = {
enabled: !!formData.value.nodeExtractConfig.enabled,
text: formData.value.nodeExtractConfig.text || '',
tags: formData.value.nodeExtractConfig.tags || [],
nodes: formData.value.nodeExtractConfig.nodes || [],
relations: formData.value.nodeExtractConfig.relations || []
}
}
return data
}
// 提交表单
const handleSubmit = async () => {
if (!validateForm()) {
return
}
// 编辑模式下,若已有文件且存储引擎发生了变化,弹窗确认
if (
props.mode === 'edit' &&
hasFiles.value &&
formData.value &&
initialStorageProvider.value &&
formData.value.storageProvider !== initialStorageProvider.value
) {
const dialog = DialogPlugin.confirm({
header: t('common.confirm'),
body: t('knowledgeEditor.messages.storageChangeConfirm'),
confirmBtn: t('common.confirm'),
cancelBtn: t('common.cancel'),
onConfirm: () => {
dialog.destroy()
doSubmit()
},
onCancel: () => {
dialog.destroy()
},
})
return
}
doSubmit()
}
const doSubmit = async () => {
saving.value = true
try {
const data = buildSubmitData()
if (!data) {
throw new Error(t('knowledgeEditor.messages.buildDataFailed'))
}
if (props.mode === 'create') {
// 创建模式:一次性创建知识库及所有配置
const result: any = await createKnowledgeBase(data)
if (!result.success || !result.data?.id) {
throw new Error(result.message || t('knowledgeEditor.messages.createFailed'))
}
MessagePlugin.success(t('knowledgeEditor.messages.createSuccess'))
markContextualGuideDone('kbCreate')
emit('success', result.data.id)
} else {
// 编辑模式:分别更新基本信息和配置
if (!props.kbId) {
throw new Error(t('knowledgeEditor.messages.missingId'))
}
feat: Implement comprehensive wiki feature for knowledge bases This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes: **Backend Changes:** - Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log) - Database schema: wiki_pages table with full migration support - WikiPageService: CRUD operations and page management - WikiPageRepository: GORM-based persistence layer - Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents * Summary page generation using LLM * Entity and concept extraction in a single LLM call * Synthesis opportunity detection * Index page rebuilding * Log page maintenance - Wiki boost feature: Enhance chat retrieval with wiki context - Wiki linting: Maintenance and validation utilities - Agent wiki tools: Enable agents to query and interact with wiki pages - Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks - Language support: Reuse existing middleware language infrastructure for LLM prompts **Frontend Changes:** - Wiki browser UI: View all wiki pages with filtering and search - Wiki API client: Knowledge base wiki management endpoints - Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model) - i18n updates: Support for English, Korean, Russian, and Chinese interfaces **Configuration:** - Container DI: Wire up all wiki services - Router: Register wiki API endpoints - Task handling: Support async wiki ingest tasks **Testing:** - Unit tests for wiki page types - Service layer tests - Endpoint tests for wiki operations - Integration tests with LLM mocking **Documentation:** - Language refactoring analysis and guides - Implementation completion reports - Quick reference guides for developers **Key Features:** ✅ LLM-powered wiki page generation from documents ✅ Multi-language support (9+ languages) ✅ Automatic extraction of entities and concepts ✅ Synthesis opportunity detection ✅ Index and log page maintenance ✅ Progressive wiki building across multiple documents ✅ Agent-based wiki interaction ✅ Chat retrieval enhancement with wiki context ✅ Full frontend UI for wiki browsing Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
// 1. 更新基本信息(名称、描述)和 FAQ/Wiki 配置
const updateConfig: any = {}
if (formData.value.type === 'faq' && formData.value.faqConfig) {
updateConfig.faq_config = {
index_mode: formData.value.faqConfig.indexMode || 'question_only',
question_index_mode: formData.value.faqConfig.questionIndexMode || 'separate'
}
}
if (formData.value.wikiConfig && formData.value.type !== 'faq') {
feat: Implement comprehensive wiki feature for knowledge bases This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes: **Backend Changes:** - Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log) - Database schema: wiki_pages table with full migration support - WikiPageService: CRUD operations and page management - WikiPageRepository: GORM-based persistence layer - Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents * Summary page generation using LLM * Entity and concept extraction in a single LLM call * Synthesis opportunity detection * Index page rebuilding * Log page maintenance - Wiki boost feature: Enhance chat retrieval with wiki context - Wiki linting: Maintenance and validation utilities - Agent wiki tools: Enable agents to query and interact with wiki pages - Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks - Language support: Reuse existing middleware language infrastructure for LLM prompts **Frontend Changes:** - Wiki browser UI: View all wiki pages with filtering and search - Wiki API client: Knowledge base wiki management endpoints - Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model) - i18n updates: Support for English, Korean, Russian, and Chinese interfaces **Configuration:** - Container DI: Wire up all wiki services - Router: Register wiki API endpoints - Task handling: Support async wiki ingest tasks **Testing:** - Unit tests for wiki page types - Service layer tests - Endpoint tests for wiki operations - Integration tests with LLM mocking **Documentation:** - Language refactoring analysis and guides - Implementation completion reports - Quick reference guides for developers **Key Features:** ✅ LLM-powered wiki page generation from documents ✅ Multi-language support (9+ languages) ✅ Automatic extraction of entities and concepts ✅ Synthesis opportunity detection ✅ Index and log page maintenance ✅ Progressive wiki building across multiple documents ✅ Agent-based wiki interaction ✅ Chat retrieval enhancement with wiki context ✅ Full frontend UI for wiki browsing Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
updateConfig.wiki_config = {
synthesis_model_id: formData.value.modelConfig?.wikiSynthesisModelId || '',
feat: Implement comprehensive wiki feature for knowledge bases This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes: **Backend Changes:** - Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log) - Database schema: wiki_pages table with full migration support - WikiPageService: CRUD operations and page management - WikiPageRepository: GORM-based persistence layer - Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents * Summary page generation using LLM * Entity and concept extraction in a single LLM call * Synthesis opportunity detection * Index page rebuilding * Log page maintenance - Wiki boost feature: Enhance chat retrieval with wiki context - Wiki linting: Maintenance and validation utilities - Agent wiki tools: Enable agents to query and interact with wiki pages - Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks - Language support: Reuse existing middleware language infrastructure for LLM prompts **Frontend Changes:** - Wiki browser UI: View all wiki pages with filtering and search - Wiki API client: Knowledge base wiki management endpoints - Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model) - i18n updates: Support for English, Korean, Russian, and Chinese interfaces **Configuration:** - Container DI: Wire up all wiki services - Router: Register wiki API endpoints - Task handling: Support async wiki ingest tasks **Testing:** - Unit tests for wiki page types - Service layer tests - Endpoint tests for wiki operations - Integration tests with LLM mocking **Documentation:** - Language refactoring analysis and guides - Implementation completion reports - Quick reference guides for developers **Key Features:** ✅ LLM-powered wiki page generation from documents ✅ Multi-language support (9+ languages) ✅ Automatic extraction of entities and concepts ✅ Synthesis opportunity detection ✅ Index and log page maintenance ✅ Progressive wiki building across multiple documents ✅ Agent-based wiki interaction ✅ Chat retrieval enhancement with wiki context ✅ Full frontend UI for wiki browsing Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
max_pages_per_ingest: formData.value.wikiConfig.maxPagesPerIngest || 0,
extraction_granularity: formData.value.wikiConfig.extractionGranularity || 'standard',
feat: Implement comprehensive wiki feature for knowledge bases This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes: **Backend Changes:** - Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log) - Database schema: wiki_pages table with full migration support - WikiPageService: CRUD operations and page management - WikiPageRepository: GORM-based persistence layer - Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents * Summary page generation using LLM * Entity and concept extraction in a single LLM call * Synthesis opportunity detection * Index page rebuilding * Log page maintenance - Wiki boost feature: Enhance chat retrieval with wiki context - Wiki linting: Maintenance and validation utilities - Agent wiki tools: Enable agents to query and interact with wiki pages - Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks - Language support: Reuse existing middleware language infrastructure for LLM prompts **Frontend Changes:** - Wiki browser UI: View all wiki pages with filtering and search - Wiki API client: Knowledge base wiki management endpoints - Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model) - i18n updates: Support for English, Korean, Russian, and Chinese interfaces **Configuration:** - Container DI: Wire up all wiki services - Router: Register wiki API endpoints - Task handling: Support async wiki ingest tasks **Testing:** - Unit tests for wiki page types - Service layer tests - Endpoint tests for wiki operations - Integration tests with LLM mocking **Documentation:** - Language refactoring analysis and guides - Implementation completion reports - Quick reference guides for developers **Key Features:** ✅ LLM-powered wiki page generation from documents ✅ Multi-language support (9+ languages) ✅ Automatic extraction of entities and concepts ✅ Synthesis opportunity detection ✅ Index and log page maintenance ✅ Progressive wiki building across multiple documents ✅ Agent-based wiki interaction ✅ Chat retrieval enhancement with wiki context ✅ Full frontend UI for wiki browsing Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
}
}
if (formData.value.type !== 'faq') {
updateConfig.indexing_strategy = {
vector_enabled: formData.value.indexingStrategy?.vectorEnabled ?? true,
keyword_enabled: formData.value.indexingStrategy?.keywordEnabled ?? true,
wiki_enabled: formData.value.indexingStrategy?.wikiEnabled ?? false,
graph_enabled: formData.value.indexingStrategy?.graphEnabled ?? false,
}
}
await updateKnowledgeBase(props.kbId, {
name: data.name,
description: data.description,
config: updateConfig
})
// 2. 更新完整配置(模型、分块、多模态、存储引擎、知识图谱等)
const config: KBModelConfigRequest = {
llmModelId: data.summary_model_id,
embeddingModelId: data.embedding_model_id,
vlm_config: data.vlm_config,
asr_config: data.asr_config,
documentSplitting: {
chunkSize: data.chunking_config.chunk_size,
chunkOverlap: data.chunking_config.chunk_overlap,
separators: data.chunking_config.separators,
parserEngineRules: data.chunking_config.parser_engine_rules || undefined,
enableParentChild: data.chunking_config.enable_parent_child || false,
parentChunkSize: data.chunking_config.parent_chunk_size || 4096,
feat(frontend): expose chunking strategy in KB editor Surfaces the adaptive 3-tier chunking controls in the existing "Chunking" section of the KB editor modal. Users can now pick a strategy from a dropdown without crafting JSON for the API: - Automatic (recommended) → backend profiler picks the tier - Markdown-optimized → forces heading-aware splitting - Smart structure detection → forces heuristic boundary detection - Classic → original recursive splitter (legacy) The fifth backend value `recursive` is intentionally hidden from the UI — it's functionally near `legacy` and would dilute the choice. Advanced options (collapsible, disabled when strategy=legacy): - TokenLimit (0–8192 approx tokens; 0 = char-based budget) - Languages multi-select (DE/EN/ZH; empty = auto-detect) Behaviour: - New KBs default to strategy="auto" - Existing KBs without the field render with empty strategy and keep classic behavior on save unless the user actively picks one - Overlap warning when overlap >= chunkSize/2 Wired through: - KBChunkingSettings.vue: strategy select + advanced collapsible + ChunkingConfig interface extended - KnowledgeBaseEditorModal.vue: form-state defaults, kb-load mapping, buildSubmitData (chunking_config) + updateKBConfig (documentSplitting) pass strategy/token_limit/languages - api/initialization/index.ts: types extended - i18n: en-US / zh-CN / ko-KR / ru-RU all carry strategy + advanced keys (6 keys each) https://claude.ai/code/session_01XADhx6mtu2ZYW3DE9Lun6k
2026-05-02 20:40:07 +00:00
childChunkSize: data.chunking_config.child_chunk_size || 384,
fix(chunker): QA audit — pointer DTOs, profile reuse, stats correctness Resolves the issues surfaced by the post-Phase-3 self-review. High severity - Strategy / TokenLimit / Languages can now be reset. The KB-config handler uses pointer DTOs so the absence of a field in the payload means "no change" while an explicit empty string / 0 / [] clears the value. The frontend now sends the fields unconditionally so the user can revert to defaults via the clear icon — previously these fields were write-once. - DocProfile is no longer computed twice in the preview endpoint. Diagnostics carries the profile that drove tier selection (when auto-strategy ran); the handler only re-profiles for explicit strategies that bypass the profiler. - Chunk-size stats (avg / min / max / stddev) are now computed over the FULL chunk set before the response is truncated to previewMaxChunks. Avoids systematically misleading metrics for large documents. - SplitWithDiagnostics defaults SelectedTier to TierLegacy so an empty-text request never leaves the diag with a blank tier string. Medium severity - Split() reverts to its own loop instead of delegating to SplitWithDiagnostics. Diagnostics struct allocation is reserved for callers that actually want the trace (preview endpoint). Matters in SplitParentChild where Split runs once per parent. - Preview endpoint runs the splitter on a goroutine wrapped in a 5s context.WithTimeout. CJK input at the 256k-rune ceiling could otherwise tie up the worker for several seconds. Low severity - KBChunkingSettings emits arrays via spread copies so parent-side mutation cannot drift the form's reactive state. - KBChunkingDebug font-family includes a monospace fallback so the chunk content stays monospaced even when the TDesign CSS variable is missing. Documentation - DocProfile JSON shape is now annotated as part of the public preview API; field renames would be breaking. https://claude.ai/code/session_01XADhx6mtu2ZYW3DE9Lun6k
2026-05-03 07:01:20 +00:00
// Always send strategy / tokenLimit / languages — backend treats
// empty/0/[] as a valid clear, so we must include them in the
// payload to let users reset back to defaults.
strategy: formData.value?.chunkingConfig.strategy ?? '',
tokenLimit: formData.value?.chunkingConfig.tokenLimit ?? 0,
languages: formData.value?.chunkingConfig.languages ?? []
},
multimodal: {
enabled: !!data.vlm_config?.enabled
},
storageProvider: data.storage_provider_config?.provider || data.storage_config?.provider || 'local',
nodeExtract: {
enabled: data.extract_config?.enabled || false,
text: data.extract_config?.text || '',
tags: data.extract_config?.tags || [],
nodes: data.extract_config?.nodes || [],
relations: data.extract_config?.relations || []
},
questionGeneration: {
enabled: data.question_generation_config?.enabled || false,
questionCount: data.question_generation_config?.question_count || 3
}
}
await updateKBConfig(props.kbId, config)
MessagePlugin.success(t('knowledgeEditor.messages.updateSuccess'))
// Check if indexing strategy changed and offer rebuild
if (hasFiles.value && initialIndexingStrategy.value && formData.value) {
const curr = formData.value.indexingStrategy
const prev = initialIndexingStrategy.value
const strategyChanged = (
curr.vectorEnabled !== prev.vectorEnabled ||
curr.keywordEnabled !== prev.keywordEnabled ||
curr.wikiEnabled !== prev.wikiEnabled ||
curr.graphEnabled !== prev.graphEnabled
)
if (strategyChanged) {
const dialog = DialogPlugin.confirm({
header: t('knowledgeEditor.indexing.rebuildConfirmTitle'),
body: t('knowledgeEditor.indexing.rebuildConfirmBody', { count: '...' }),
confirmBtn: t('common.confirm'),
cancelBtn: t('common.cancel'),
onConfirm: async () => {
dialog.destroy()
try {
const result: any = await rebuildKBIndex(props.kbId!)
const count = result?.data?.document_count ?? 0
MessagePlugin.success(t('knowledgeEditor.indexing.rebuildSuccess', { count }))
} catch (e) {
console.error('Rebuild index failed:', e)
}
},
onCancel: () => {
dialog.destroy()
MessagePlugin.info(t('knowledgeEditor.indexing.rebuildSkip'))
},
})
}
}
emit('success', props.kbId)
}
handleClose()
} catch (error: any) {
console.error('Knowledge base operation failed:', error)
feat: expose KB ↔ vector store binding in list, editor, and detail UI Backend ------- ListKnowledgeBases now enriches each row with the resolved vector_store metadata (name / source / engine_type / status) via a new buildKBListResponse helper. Store views are batch-resolved once per request through BatchResolveStoreView so an N-KB list costs one vector-store service call rather than N — closing the N+1 limitation flagged in #1372's known-limitations section. Cross-tenant shared KBs continue to render via SharedStoreDisplay so the owning tenant's store inventory cannot be correlated across rows; the underlying vector_store_id UUID is stripped from those responses. Resolver failures degrade gracefully: bound KBs render as unavailable instead of breaking the list. Test coverage pins the env / bound / shared distinction, the batch-call-count invariant, and the graceful-failure path. Frontend -------- KB editor modal gains a new "Vector Store" section. Create mode shows a dropdown that combines the system default (env store) and the tenant's configured user stores, fetched once at mount via the existing listVectorStores API. Edit mode shows the bound store read-only via a new VectorStoreBadge component with an explicit immutability hint — matching the backend's `<-:create` GORM tag and the service-layer UpdateKnowledgeBaseRequest DTO that already omit the field. KB list cards surface a small engine-type badge for own-tenant bound KBs, and a warning badge when the bound store is unavailable. Env-bound and shared KBs render no badge (visual noise control). KB detail header shows the bound store via the same VectorStoreBadge component; shared KBs fall through to the badge's internal "shared" branch with no name / engine / id rendered. The KB editor's create-time error handler translates the typed ErrVectorStoreBindingInvalid (2200) and ErrVectorStoreUnavailable (2201) into localized messages and jumps the user back to the VectorStore section so they can pick a different store or fall back to the system default. The KB row type gains five optional fields (vector_store_id / name / engine_type / source / status). i18n: 18 new keys added to en-US, ko-KR, zh-CN; ru-RU receives English placeholders pending translation (consistent with prior PRs in this locale). Part of #993 (Phase 2: Per-KB VectorStore Binding). Phase 2 roadmap item: PR 5 (KB binding UI + list-response enrichment). Depends on #994, #1310, #1372, #1386 (all backend in the Phase 2 series).
2026-05-18 14:50:09 +00:00
// Vector-store-binding error codes from the server. Both indicate
// the selected store cannot be used: 2200 is "the binding itself
// is invalid" (e.g. unknown id, foreign tenant), 2201 is "the
// store is currently unreachable". For either, swap in a localized
// message and jump the user back to the Vector Store section so
// they can pick a different store or fall back to the system
// default.
const code = error?.response?.data?.error?.code ?? error?.code
if (code === 2200) {
MessagePlugin.error(t('knowledgeEditor.errors.vectorStoreBindingInvalid'))
currentSection.value = 'vectorStore'
} else if (code === 2201) {
MessagePlugin.error(t('knowledgeEditor.errors.vectorStoreUnavailable'))
currentSection.value = 'vectorStore'
} else {
MessagePlugin.error(error?.message || t('common.operationFailed'))
}
} finally {
saving.value = false
}
}
// 重置所有状态
const resetState = () => {
currentSection.value = 'basic'
formData.value = null
hasFiles.value = false
initialStorageProvider.value = ''
tenantDefaultStorageProvider.value = 'local'
initialIndexingStrategy.value = null
saving.value = false
loading.value = false
chunkingDirty.value = false
kbCreatorId.value = ''
}
// 关闭弹窗
const handleClose = () => {
emit('update:visible', false)
setTimeout(() => {
resetState()
}, 300)
}
// 监听弹窗打开/关闭
watch(() => props.visible, async (newVal) => {
if (newVal) {
// 打开弹窗时,先重置状态
resetState()
// 检查是否有初始 section,如果有则跳转
if (uiStore.kbEditorInitialSection) {
currentSection.value = uiStore.kbEditorInitialSection
}
// 加载模型列表与租户默认存储引擎(创建 KB 时即使用,不依赖是否打开「存储引擎」Tab)
await Promise.all([loadAllModels(), loadTenantDefaultStorageProvider()])
// 根据模式加载数据
if (props.mode === 'edit' && props.kbId) {
await loadKBData()
} else {
// 创建模式:初始化空表单,并预填租户默认存储引擎
formData.value = initFormData(props.initialType || 'document')
formData.value.storageProvider = tenantDefaultStorageProvider.value
hasFiles.value = false
applyDefaultModelsIfEmpty()
}
} else {
// 关闭弹窗时,延迟重置状态(等待动画结束)
setTimeout(() => {
resetState()
currentSection.value = 'basic' // 重置为默认 section
}, 300)
}
})
// 监听全局设置弹窗关闭后刷新模型列表
watch(
() => uiStore.showSettingsModal,
async (visible, previous) => {
if (!visible && previous && props.visible) {
await loadAllModels(true)
}
}
)
</script>
<style scoped lang="less">
// 复用创建知识库的样式
.settings-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
backdrop-filter: blur(4px);
}
.settings-modal {
position: relative;
width: 90vw;
max-width: 1000px;
height: 85vh;
max-height: 750px;
background: var(--td-bg-color-container);
border-radius: 12px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
display: flex;
flex-direction: column;
overflow: hidden;
}
.close-btn {
position: absolute;
top: 20px;
right: 20px;
width: 32px;
height: 32px;
border: none;
background: var(--td-bg-color-secondarycontainer);
border-radius: 6px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
color: var(--td-text-color-secondary);
transition: all 0.2s ease;
z-index: 10;
&:hover {
background: var(--td-bg-color-secondarycontainer);
color: var(--td-text-color-primary);
}
}
.settings-container {
display: flex;
height: 100%;
overflow: hidden;
}
.settings-sidebar {
width: 200px;
background: var(--td-bg-color-settings-modal);
border-right: 1px solid var(--td-component-stroke);
display: flex;
flex-direction: column;
flex-shrink: 0;
}
.sidebar-header {
padding: 24px 20px;
border-bottom: 1px solid var(--td-component-stroke);
}
.sidebar-title {
margin: 0;
font-family: var(--app-font-family);
font-size: 18px;
font-weight: 600;
color: var(--td-text-color-primary);
}
.settings-nav {
flex: 1;
padding: 12px 8px;
overflow-y: auto;
}
.nav-item {
display: flex;
align-items: center;
padding: 10px 12px;
margin-bottom: 4px;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s ease;
font-family: var(--app-font-family);
font-size: 14px;
color: var(--td-text-color-secondary);
&:hover {
background: var(--td-bg-color-secondarycontainer-hover);
color: var(--td-text-color-primary);
}
&.active {
background: var(--td-brand-color-light);
color: var(--td-brand-color);
font-weight: 500;
}
}
.nav-icon {
margin-right: 8px;
font-size: 18px;
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
}
.nav-label {
flex: 1;
}
.nav-badge {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 18px;
height: 18px;
padding: 0 5px;
border-radius: 9px;
font-size: 11px;
font-weight: 600;
background: var(--td-bg-color-component);
color: var(--td-text-color-secondary);
line-height: 1;
flex-shrink: 0;
}
.nav-item.active .nav-badge {
background: var(--td-brand-color);
color: #fff;
}
.settings-content {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
}
.content-wrapper {
flex: 1;
overflow-y: auto;
padding: 24px 32px;
}
.section {
margin-bottom: 32px;
&:last-child {
margin-bottom: 0;
}
}
.section-content {
.section-header {
margin-bottom: 20px;
}
.section-title {
margin: 0 0 8px 0;
font-family: var(--app-font-family);
font-size: 20px;
font-weight: 600;
color: var(--td-text-color-primary);
}
.section-desc {
margin: 0;
font-family: var(--app-font-family);
font-size: 14px;
color: var(--td-text-color-placeholder);
line-height: 22px;
}
.section-body {
background: var(--td-bg-color-container);
}
}
.form-item {
margin-bottom: 16px;
&:last-child {
margin-bottom: 0;
}
}
.form-label {
display: block;
margin-bottom: 8px;
font-family: var(--app-font-family);
font-size: 15px;
font-weight: 500;
color: var(--td-text-color-primary);
&.required::after {
content: '*';
color: var(--td-error-color);
margin-left: 4px;
}
}
.form-tip {
margin-top: 6px;
font-size: 12px;
color: var(--td-text-color-placeholder);
}
.kb-id-field {
display: flex;
align-items: center;
gap: 4px;
width: 100%;
max-width: 480px;
margin-top: 8px;
padding: 6px 8px 6px 12px;
background: var(--td-bg-color-secondarycontainer);
border: 1px solid var(--td-component-stroke);
border-radius: 6px;
.kb-id-value {
flex: 1;
min-width: 0;
margin: 0;
padding: 0;
background: none;
border: none;
font-family: var(--app-font-family-mono);
font-size: 13px;
line-height: 1.5;
color: var(--td-text-color-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.kb-id-copy {
flex-shrink: 0;
color: var(--td-text-color-secondary);
&:hover {
color: var(--td-brand-color);
}
}
}
.granularity-radio-group {
margin-top: 4px;
}
.granularity-hint {
margin-top: 8px;
line-height: 1.6;
color: var(--td-text-color-secondary);
white-space: normal;
word-break: break-word;
}
.indexing-checks {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
gap: 12px;
margin-top: 10px;
}
.indexing-check-item {
display: flex;
flex-direction: column;
gap: 6px;
padding: 12px 14px;
border: 1px solid var(--td-component-stroke);
border-radius: 8px;
background: var(--td-bg-color-container);
cursor: pointer;
user-select: none;
transition: border-color 0.2s ease, background 0.2s ease;
&:hover {
border-color: var(--td-brand-color);
}
&.is-checked {
border-color: var(--td-brand-color);
background: var(--td-brand-color-light);
}
&.is-disabled {
cursor: not-allowed;
opacity: 0.7;
&:hover {
border-color: var(--td-component-stroke);
}
&.is-checked:hover {
border-color: var(--td-brand-color);
}
}
:deep(.t-checkbox__label) {
font-weight: 500;
color: var(--td-text-color-primary);
}
}
.locked-tip {
color: var(--td-warning-color);
margin-top: 8px;
}
// 禁用内部 checkbox 自身的点击事件,统一由卡片处理
.indexing-check-box {
pointer-events: none;
}
.indexing-check-title {
display: inline-flex;
align-items: center;
gap: 6px;
}
.indexing-new-badge {
display: inline-flex;
align-items: center;
padding: 0 6px;
height: 16px;
border-radius: 3px;
font-size: 10px;
font-weight: 600;
line-height: 1;
letter-spacing: 0.4px;
color: var(--td-brand-color);
background: var(--td-brand-color-light);
}
.indexing-check-desc {
margin: 0;
padding-left: 24px;
font-size: 12px;
line-height: 18px;
color: var(--td-text-color-placeholder);
}
.faq-guide {
margin-top: 20px;
padding: 12px 16px;
border-radius: 8px;
background: var(--td-bg-color-secondarycontainer);
color: var(--td-text-color-secondary);
font-size: 13px;
line-height: 20px;
}
.settings-footer {
padding: 16px 32px;
border-top: 1px solid var(--td-component-stroke);
display: flex;
justify-content: flex-end;
gap: 12px;
flex-shrink: 0;
}
// 过渡动画
.modal-enter-active,
.modal-leave-active {
transition: all 0.3s ease;
}
.modal-enter-from,
.modal-leave-to {
opacity: 0;
.settings-modal {
transform: scale(0.95);
}
}
// 多模态配置内联样式(与子组件 KBStorageSettings/KBAdvancedSettings 一致)
.kb-multimodal-settings {
width: 100%;
.section-header {
margin-bottom: 32px;
h2 {
font-size: 20px;
font-weight: 600;
color: var(--td-text-color-primary);
margin: 0 0 8px 0;
}
.section-description {
font-size: 14px;
color: var(--td-text-color-secondary);
margin: 0;
line-height: 1.5;
}
}
.settings-group {
display: flex;
flex-direction: column;
}
.setting-row {
display: flex;
align-items: flex-start;
justify-content: space-between;
padding: 20px 0;
border-bottom: 1px solid var(--td-component-stroke);
&:last-child {
border-bottom: none;
}
}
.setting-info {
flex: 1;
max-width: 65%;
padding-right: 24px;
label {
font-size: 15px;
font-weight: 500;
color: var(--td-text-color-primary);
display: block;
margin-bottom: 4px;
}
.desc {
font-size: 13px;
color: var(--td-text-color-secondary);
margin: 0;
line-height: 1.5;
}
}
.setting-control {
flex-shrink: 0;
min-width: 280px;
display: flex;
justify-content: flex-end;
align-items: center;
}
.required {
color: var(--td-error-color);
margin-left: 2px;
font-weight: 500;
}
}
</style>