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).
This commit is contained in:
ochan.kwon
2026-05-18 23:50:09 +09:00
committed by lyingbug
parent 0f57bf3ff8
commit 8b7d00b260
15 changed files with 1165 additions and 12 deletions
+37
View File
@@ -20,6 +20,38 @@ export function listKnowledgeBases(params?: {
return get(qs ? `/api/v1/knowledge-bases?${qs}` : '/api/v1/knowledge-bases');
}
// Read-only vector-store binding metadata enriched onto every KB
// response (list, create, get, update, pin). Source carries where the
// binding points; status reports whether that target is currently
// reachable by the server.
//
// - source 'env' → KB uses the tenant's env-configured store
// (RETRIEVE_DRIVER). vector_store_id is null and
// vector_store_name is the localized "System
// default" label; vector_store_engine_type still
// reports the underlying engine (e.g. "postgres").
// - source 'user' → KB is bound to a tenant-owned VectorStore.
// vector_store_id / name / engine_type are real.
// - source 'shared' → KB belongs to a different tenant and is
// readable via cross-organization sharing. The
// server strips vector_store_id and engine_type
// to avoid leaking the owner tenant's store
// inventory; only this source marker arrives.
// - status 'unavailable' → the binding cannot be reached right now
// (deleted row, registry miss, transient infra
// failure). Operators recover via the global
// Vector Stores settings page.
export type VectorStoreSource = 'env' | 'user' | 'shared' | 'unavailable';
export type VectorStoreStatus = 'available' | 'unavailable';
export interface KnowledgeBaseStoreView {
vector_store_id?: string | null;
vector_store_name?: string;
vector_store_engine_type?: string;
vector_store_source?: VectorStoreSource;
vector_store_status?: VectorStoreStatus;
}
export function createKnowledgeBase(data: {
name: string;
description?: string;
@@ -27,6 +59,11 @@ export function createKnowledgeBase(data: {
chunking_config?: any;
embedding_model_id?: string;
summary_model_id?: string;
// Opt-in binding to a specific tenant-owned VectorStore. Omit (or
// send undefined / empty string) to fall back to the env-configured
// store. Immutable after creation — UpdateKnowledgeBase intentionally
// does not accept this field.
vector_store_id?: string;
vlm_config?: {
enabled: boolean;
model_id?: string;
@@ -0,0 +1,114 @@
<template>
<span :class="['vs-badge', `vs-badge-${effectiveSource}`, isUnavailable && 'vs-badge-warn']">
<t-icon :name="iconName" class="vs-badge-icon" />
<span class="vs-badge-name">{{ displayName }}</span>
<span
v-if="engineType && (effectiveSource === 'user' || effectiveSource === 'env')"
class="vs-badge-engine"
>
({{ engineType }})
</span>
<t-tag
v-if="isUnavailable"
theme="danger"
variant="light"
size="small"
class="vs-badge-warn-tag"
>
{{ $t('vectorStoreBadge.unavailable') }}
</t-tag>
</span>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import type { VectorStoreSource, VectorStoreStatus } from '@/api/knowledge-base'
const props = defineProps<{
source?: VectorStoreSource
name?: string
engineType?: string
status?: VectorStoreStatus
}>()
const { t } = useI18n()
// When backend omits the source (e.g. legacy KB row from a cached list
// endpoint that does not enrich), treat it as env so the badge renders
// gracefully instead of going blank.
const effectiveSource = computed<VectorStoreSource>(() => props.source || 'env')
const isUnavailable = computed(
() => props.status === 'unavailable' || effectiveSource.value === 'unavailable',
)
const iconName = computed(() => {
switch (effectiveSource.value) {
case 'env':
case 'user':
// Both env- and user-bound KBs sit on top of a vector store; the
// distinction is purely organizational (configured at process
// start vs. created in the UI), so they share the same icon.
return 'data-base'
case 'shared':
return 'share'
case 'unavailable':
default:
return 'help-circle'
}
})
const displayName = computed(() => {
if (effectiveSource.value === 'env') return t('vectorStoreBadge.systemDefault')
if (effectiveSource.value === 'shared') return t('vectorStoreBadge.sharedFromOrg')
return props.name || t('vectorStoreBadge.unknownStore')
})
</script>
<style scoped>
.vs-badge {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 2px 8px;
border-radius: 4px;
font-size: 12px;
line-height: 1.4;
background: var(--td-bg-color-component, #f5f7fa);
color: var(--td-text-color-primary, #1d2129);
}
.vs-badge-env {
background: var(--td-brand-color-1, #ecf2fe);
color: var(--td-brand-color-7, #0052d9);
}
.vs-badge-user {
background: var(--td-success-color-1, #e8f8f2);
color: var(--td-success-color-7, #00754a);
}
.vs-badge-shared {
background: var(--td-warning-color-1, #fff1e9);
color: var(--td-warning-color-7, #b85b00);
}
.vs-badge-warn {
background: var(--td-error-color-1, #fde9e6);
color: var(--td-error-color-7, #b32700);
}
.vs-badge-icon {
font-size: 14px;
}
.vs-badge-engine {
opacity: 0.7;
font-size: 11px;
}
.vs-badge-warn-tag {
margin-left: 4px;
}
</style>
+30
View File
@@ -1708,6 +1708,7 @@ export default {
sidebar: {
basic: 'Basic Information',
models: 'Model Configuration',
vectorStore: 'Vector Store',
chunking: 'Chunking Settings',
storage: 'Storage Engine',
advanced: 'Advanced Settings',
@@ -1720,6 +1721,12 @@ export default {
share: 'Sharing',
indexing: 'Indexing Strategy',
},
errors: {
vectorStoreBindingInvalid:
'The selected vector store cannot be used. Choose a different store or use the system default.',
vectorStoreUnavailable:
'The selected vector store is currently unavailable. Check its connection configuration in Settings → Vector Stores.',
},
basic: {
title: 'Basic Information',
description: 'Configure the knowledge base name and description',
@@ -3737,7 +3744,30 @@ export default {
think: 'Deep Thinking',
todoWrite: 'Make Plan',
},
vectorStoreBadge: {
systemDefault: 'System default',
sharedFromOrg: 'Shared from another organization',
unknownStore: 'Unknown store',
unavailable: 'Unavailable',
},
kbSettings: {
vectorStore: {
title: 'Vector Store',
description:
'Choose which vector store this knowledge base writes to. The binding is permanent — to move an existing KB to a different store, create a new KB and re-index.',
loading: 'Loading vector stores...',
engineLabel: 'Vector store',
engineDesc:
'Pick a store from the global Vector Stores configuration, or leave as System default to use the tenant-wide RETRIEVE_DRIVER engine.',
boundLabel: 'Bound vector store',
systemDefault: 'System default',
immutableHint:
'Cannot be changed after creation. To migrate later, create a new KB bound to the desired store and re-index.',
immutableEdit: 'Vector store binding cannot be changed after creation.',
unavailableHint:
'The bound vector store is currently unavailable; check its connection configuration in Settings → Vector Stores.',
goGlobalSettings: 'Go to Vector Store Settings',
},
storage: {
title: 'Storage Engine',
description: 'Select the file storage engine. This affects how uploaded documents and images within documents are stored. Parameters are configured in global settings.',
+30
View File
@@ -2375,6 +2375,7 @@ export default {
sidebar: {
basic: "기본 정보",
models: "모델 설정",
vectorStore: "벡터 스토어",
chunking: "청크 설정",
advanced: "고급 설정",
faq: "FAQ 설정",
@@ -2387,6 +2388,12 @@ export default {
datasource: "데이터 소스",
indexing: "인덱싱 전략",
},
errors: {
vectorStoreBindingInvalid:
"선택한 벡터 스토어를 사용할 수 없습니다. 다른 스토어를 선택하거나 시스템 기본값을 사용하세요.",
vectorStoreUnavailable:
"선택한 벡터 스토어가 현재 사용할 수 없는 상태입니다. 설정 → 벡터 스토어에서 연결 상태를 확인하세요.",
},
basic: {
title: "기본 정보",
description: "지식베이스의 이름과 설명 정보 설정",
@@ -3800,7 +3807,30 @@ export default {
think: '깊이 생각하기',
todoWrite: '계획 수립',
},
vectorStoreBadge: {
systemDefault: "시스템 기본값",
sharedFromOrg: "다른 조직에서 공유됨",
unknownStore: "알 수 없는 스토어",
unavailable: "사용 불가",
},
kbSettings: {
vectorStore: {
title: "벡터 스토어",
description:
"이 지식베이스가 사용할 벡터 스토어를 선택합니다. 생성 후에는 변경할 수 없습니다. 다른 스토어로 옮기려면 새 KB를 만들고 다시 인덱싱하세요.",
loading: "벡터 스토어 목록을 불러오는 중...",
engineLabel: "벡터 스토어",
engineDesc:
"전역 벡터 스토어 설정에서 등록한 스토어를 선택하거나, '시스템 기본값'을 유지하면 테넌트의 RETRIEVE_DRIVER 엔진을 사용합니다.",
boundLabel: "바인딩된 벡터 스토어",
systemDefault: "시스템 기본값",
immutableHint:
"생성 후 변경할 수 없습니다. 다른 스토어로 옮기려면 원하는 스토어에 바인딩된 새 KB를 만들고 다시 인덱싱하세요.",
immutableEdit: "벡터 스토어 바인딩은 생성 후 변경할 수 없습니다.",
unavailableHint:
"바인딩된 벡터 스토어가 현재 사용할 수 없는 상태입니다. 설정 → 벡터 스토어에서 연결 상태를 확인하세요.",
goGlobalSettings: "벡터 스토어 설정으로 이동",
},
storage: {
title: '스토리지 엔진',
description: '파일 스토리지 엔진을 선택합니다. 문서 업로드 및 문서 내 이미지 저장 방식에 영향을 미칩니다. 파라미터는 전역 설정에서 구성합니다.',
+30
View File
@@ -1963,6 +1963,7 @@ export default {
sidebar: {
basic: 'Основная информация',
models: 'Конфигурация моделей',
vectorStore: 'Vector Store',
chunking: 'Настройки разбиения',
advanced: 'Дополнительные настройки',
faq: 'FAQ настройки',
@@ -1975,6 +1976,12 @@ export default {
share: 'Sharing',
indexing: 'Стратегия индексации',
},
errors: {
vectorStoreBindingInvalid:
'The selected vector store cannot be used. Choose a different store or use the system default.',
vectorStoreUnavailable:
'The selected vector store is currently unavailable. Check its connection configuration in Settings → Vector Stores.',
},
basic: {
title: 'Основная информация',
description: 'Укажите название и описание базы знаний',
@@ -3375,7 +3382,30 @@ export default {
think: 'Глубокое размышление',
todoWrite: 'Составить план'
},
vectorStoreBadge: {
systemDefault: 'System default',
sharedFromOrg: 'Shared from another organization',
unknownStore: 'Unknown store',
unavailable: 'Unavailable',
},
kbSettings: {
vectorStore: {
title: 'Vector Store',
description:
'Choose which vector store this knowledge base writes to. The binding is permanent — to move an existing KB to a different store, create a new KB and re-index.',
loading: 'Loading vector stores...',
engineLabel: 'Vector store',
engineDesc:
'Pick a store from the global Vector Stores configuration, or leave as System default to use the tenant-wide RETRIEVE_DRIVER engine.',
boundLabel: 'Bound vector store',
systemDefault: 'System default',
immutableHint:
'Cannot be changed after creation. To migrate later, create a new KB bound to the desired store and re-index.',
immutableEdit: 'Vector store binding cannot be changed after creation.',
unavailableHint:
'The bound vector store is currently unavailable; check its connection configuration in Settings → Vector Stores.',
goGlobalSettings: 'Go to Vector Store Settings',
},
storage: {
title: 'Хранилище',
description: 'Выберите хранилище файлов. Это влияет на способ хранения загруженных документов и изображений в документах. Параметры настраиваются в глобальных настройках.',
+30
View File
@@ -2350,6 +2350,7 @@ export default {
sidebar: {
basic: "基本信息",
models: "模型配置",
vectorStore: "向量存储",
chunking: "分块设置",
storage: "存储引擎",
advanced: "高级设置",
@@ -2362,6 +2363,12 @@ export default {
share: "共享管理",
indexing: "索引策略",
},
errors: {
vectorStoreBindingInvalid:
"无法使用所选向量存储。请选择其他存储或使用系统默认值。",
vectorStoreUnavailable:
"所选向量存储当前不可用。请在设置 → 向量存储中检查其连接配置。",
},
basic: {
title: "基本信息",
description: "设置知识库的名称和描述信息",
@@ -3732,7 +3739,30 @@ export default {
think: "深度思考",
todoWrite: "制定计划",
},
vectorStoreBadge: {
systemDefault: "系统默认",
sharedFromOrg: "来自其他组织的共享",
unknownStore: "未知存储",
unavailable: "不可用",
},
kbSettings: {
vectorStore: {
title: "向量存储",
description:
"选择此知识库要写入的向量存储。绑定不可更改 — 如需将现有 KB 迁移到其他存储,请创建新 KB 并重新索引。",
loading: "正在加载向量存储列表...",
engineLabel: "向量存储",
engineDesc:
"从全局向量存储配置中选择,或保持系统默认以使用租户的 RETRIEVE_DRIVER 引擎。",
boundLabel: "已绑定的向量存储",
systemDefault: "系统默认",
immutableHint:
"创建后不可更改。如需迁移,请创建一个绑定到目标存储的新 KB 并重新索引。",
immutableEdit: "向量存储绑定在创建后无法更改。",
unavailableHint:
"绑定的向量存储当前不可用,请在设置 → 向量存储中检查其连接配置。",
goGlobalSettings: "前往向量存储设置",
},
storage: {
title: "存储引擎",
description: "选择文件存储引擎,影响文档上传存储和文档中图片的存储方式。参数在全局设置中配置。",
@@ -5,6 +5,7 @@ import DocContent from "@/components/doc-content.vue";
import useKnowledgeBase from '@/hooks/useKnowledgeBase';
import { useRoute, useRouter } from 'vue-router';
import EmptyKnowledge from '@/components/empty-knowledge.vue';
import VectorStoreBadge from '@/components/VectorStoreBadge.vue';
import { getSessionsList, createSessions, generateSessionsTitle } from "@/api/chat/index";
import { useMenuStore } from '@/stores/menu';
import { useUIStore } from '@/stores/ui';
@@ -2058,6 +2059,19 @@ async function createNewSession(value: string): Promise<void> {
</template>
</span>
</t-tooltip>
<!-- Bound vector store indicator. Cross-tenant shared KBs
render via the badge's internal "shared" branch with
no name or engine type, matching the server-side
response that strips those fields for non-owners. -->
<template v-if="kbInfo && (kbInfo as any)?.vector_store_source">
<span class="kb-access-meta-sep">·</span>
<VectorStoreBadge
:source="(kbInfo as any).vector_store_source"
:name="(kbInfo as any).vector_store_name"
:engine-type="(kbInfo as any).vector_store_engine_type"
:status="(kbInfo as any).vector_store_status"
/>
</template>
</div>
<t-tooltip v-if="canManage" :content="$t('knowledgeBase.settings')" placement="top">
<button type="button" class="kb-settings-button" :disabled="!kbId" @click="handleOpenKBSettings">
@@ -152,6 +152,20 @@
/>
</div>
<!-- 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">
@@ -365,6 +379,7 @@ import KBModelConfig from './settings/KBModelConfig.vue'
import KBParserSettings from './settings/KBParserSettings.vue'
import KBStorageSettings from './settings/KBStorageSettings.vue'
import KBChunkingSettings from './settings/KBChunkingSettings.vue'
import KBVectorStoreSettings from './settings/KBVectorStoreSettings.vue'
import KBAdvancedSettings from './settings/KBAdvancedSettings.vue'
import ModelSelector from '@/components/ModelSelector.vue'
import GraphSettings from './settings/GraphSettings.vue'
@@ -398,8 +413,9 @@ const hasFiles = ref(false)
const initialStorageProvider = ref<string>('')
const initialIndexingStrategy = ref<any>(null)
const dsCount = ref(0)
// KB.creator_id (added in PR 5). Empty for legacy KBs — those fall back
// to "no owner", so only tenant Admin+ can mutate share settings.
// 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
@@ -437,7 +453,11 @@ const DEFAULT_CHUNKING_PRESET = {
const navItems = computed(() => {
const items: { key: string; icon: string; label: string; badge?: number }[] = [
{ key: 'basic', icon: 'info-circle', label: t('knowledgeEditor.sidebar.basic') },
{ key: 'models', icon: 'control-platform', label: t('knowledgeEditor.sidebar.models') }
{ 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') })
@@ -555,6 +575,16 @@ const initFormData = (type: 'document' | 'faq' = 'document') => {
wikiEnabled: false,
graphEnabled: false,
},
// 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,
},
}
}
@@ -661,6 +691,19 @@ const loadKBData = async () => {
wikiEnabled: kb.indexing_strategy?.wiki_enabled ?? false,
graphEnabled: kb.indexing_strategy?.graph_enabled ?? false,
},
// 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 }
@@ -793,6 +836,16 @@ const handleStorageProviderUpdate = (value: string) => {
}
}
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 }
@@ -886,6 +939,15 @@ const buildSubmitData = () => {
summary_model_id: formData.value.modelConfig.llmModelId
}
// 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,
@@ -1130,7 +1192,23 @@ const doSubmit = async () => {
handleClose()
} catch (error: any) {
console.error('Knowledge base operation failed:', error)
MessagePlugin.error(error?.message || t('common.operationFailed'))
// 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
}
@@ -277,6 +277,32 @@
<t-icon name="share" size="14px" />
</div>
</t-tooltip>
<!-- Vector-store badge: shows the underlying engine
type (e.g. "postgres", "qdrant") for any KB whose
binding is currently reachable. Cross-tenant
shared KBs are filtered out upstream (their
engine_type is stripped from the response).
Unreachable bindings surface a red warning so
operators can self-recover from the badge alone. -->
<t-tooltip
v-if="kb.vector_store_engine_type && kb.vector_store_status === 'available'"
:content="kb.vector_store_name || ''"
placement="top"
>
<div class="feature-badge store">
<t-icon name="data-base" size="14px" />
<span class="badge-count">{{ kb.vector_store_engine_type }}</span>
</div>
</t-tooltip>
<t-tooltip
v-else-if="kb.vector_store_status === 'unavailable'"
:content="$t('kbSettings.vectorStore.unavailableHint')"
placement="top"
>
<div class="feature-badge store-warn">
<t-icon name="error-circle" size="14px" />
</div>
</t-tooltip>
</div>
</div>
<div v-if="!authStore.isLiteMode" class="bottom-right">
@@ -502,6 +528,29 @@
<t-icon name="share" size="14px" />
</div>
</t-tooltip>
<!-- Vector-store badge: identical rendering rule to
the badge in the other card variant above; kept
in sync so users see the same engine indicator
regardless of which filter scope they browse. -->
<t-tooltip
v-if="kb.vector_store_engine_type && kb.vector_store_status === 'available'"
:content="kb.vector_store_name || ''"
placement="top"
>
<div class="feature-badge store">
<t-icon name="data-base" size="14px" />
<span class="badge-count">{{ kb.vector_store_engine_type }}</span>
</div>
</t-tooltip>
<t-tooltip
v-else-if="kb.vector_store_status === 'unavailable'"
:content="$t('kbSettings.vectorStore.unavailableHint')"
placement="top"
>
<div class="feature-badge store-warn">
<t-icon name="error-circle" size="14px" />
</div>
</t-tooltip>
</div>
</div>
<div v-if="!authStore.isLiteMode" class="bottom-right">
@@ -843,6 +892,17 @@ interface KB {
creator_id?: string;
// creator_name 由后端 list 接口回填,仅用于卡片右下角来源徽章的 tooltip。
creator_name?: string;
// Resolved vector-store binding metadata, populated by the list and
// detail endpoints. Fields are optional so callers that don't request
// (or that receive a stripped cross-tenant response) still type-check.
// vector_store_engine_type is the canonical render trigger — env-bound
// and user-bound KBs both carry it; shared KBs and unreachable
// bindings leave it unset.
vector_store_id?: string | null;
vector_store_name?: string;
vector_store_engine_type?: string;
vector_store_source?: 'env' | 'user' | 'shared' | 'unavailable';
vector_store_status?: 'available' | 'unavailable';
}
const kbs = ref<KB[]>([])
@@ -2631,6 +2691,37 @@ const handleUploadFinishedEvent = (event: Event) => {
}
}
/* Vector-store engine badge. Shares the green palette used by the
document/FAQ "type" badges so the card-bottom feature row reads as
one consistent visual group. The badge-count slot carries the
engine name (e.g. "qdrant"), so the badge uses the same
variable-width treatment as the type badges. */
&.store {
background: rgba(7, 192, 95, 0.08);
color: var(--td-brand-color-active);
width: auto;
padding: 0 6px;
gap: 3px;
&:hover {
background: rgba(7, 192, 95, 0.12);
}
.badge-count {
font-size: 11px;
font-weight: 500;
}
}
&.store-warn {
background: rgba(229, 57, 53, 0.08);
color: var(--td-error-color);
&:hover {
background: rgba(229, 57, 53, 0.14);
}
}
&.role-admin {
background: rgba(7, 192, 95, 0.1);
color: var(--td-brand-color-active);
@@ -0,0 +1,268 @@
<template>
<div class="kb-vector-store-settings">
<div class="section-header">
<h2>{{ $t('kbSettings.vectorStore.title') }}</h2>
<p class="section-description">{{ $t('kbSettings.vectorStore.description') }}</p>
</div>
<!-- CREATE mode: dropdown -->
<div v-if="props.mode === 'create'" class="settings-group">
<div v-if="loading" class="loading-inline">
<t-loading size="small" />
<span>{{ $t('kbSettings.vectorStore.loading') }}</span>
</div>
<div v-else class="setting-row">
<div class="setting-info">
<label>{{ $t('kbSettings.vectorStore.engineLabel') }}</label>
<p class="desc">{{ $t('kbSettings.vectorStore.engineDesc') }}</p>
</div>
<div class="setting-control">
<t-select
v-model="localVectorStoreId"
size="medium"
:placeholder="$t('kbSettings.vectorStore.systemDefault')"
:clearable="true"
style="width: 100%; min-width: 240px;"
@change="handleChange"
>
<t-option :value="''" :label="$t('kbSettings.vectorStore.systemDefault')">
<span class="select-option">
<span>{{ $t('kbSettings.vectorStore.systemDefault') }}</span>
<t-tag
v-if="envEngineType"
theme="primary"
variant="light"
size="small"
>
{{ envEngineType }}
</t-tag>
</span>
</t-option>
<t-option
v-for="s in userStores"
:key="s.id"
:value="s.id || ''"
:label="s.name"
>
<span class="select-option">
<span>{{ s.name }}</span>
<t-tag theme="success" variant="light" size="small">
{{ s.engine_type }}
</t-tag>
</span>
</t-option>
</t-select>
<p class="option-hint">{{ $t('kbSettings.vectorStore.immutableHint') }}</p>
<a
href="javascript:void(0)"
class="go-settings"
@click.prevent="goToVectorStoreSettings"
>
{{ $t('kbSettings.vectorStore.goGlobalSettings') }}
</a>
</div>
</div>
</div>
<!-- EDIT mode: read-only display -->
<div v-else class="settings-group">
<div class="setting-row">
<div class="setting-info">
<label>{{ $t('kbSettings.vectorStore.boundLabel') }}</label>
<p class="desc">{{ $t('kbSettings.vectorStore.immutableEdit') }}</p>
</div>
<div class="setting-control">
<VectorStoreBadge
:source="props.boundSource"
:name="props.boundName"
:engine-type="props.boundEngineType"
:status="props.boundStatus"
/>
<p
v-if="props.boundStatus === 'unavailable'"
class="option-hint change-warning"
>
{{ $t('kbSettings.vectorStore.unavailableHint') }}
</p>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { useUIStore } from '@/stores/ui'
import { listVectorStores, type VectorStoreEntity } from '@/api/vector-store'
import type { VectorStoreSource, VectorStoreStatus } from '@/api/knowledge-base'
import VectorStoreBadge from '@/components/VectorStoreBadge.vue'
const props = defineProps<{
mode: 'create' | 'edit'
// create mode — current selection (empty string for env-default)
vectorStoreId?: string
// edit mode — bound store info already on the KB
boundSource?: VectorStoreSource
boundName?: string
boundEngineType?: string
boundStatus?: VectorStoreStatus
}>()
const emit = defineEmits<{
(e: 'update:vectorStoreId', id: string): void
}>()
const { t } = useI18n()
const uiStore = useUIStore()
const loading = ref(false)
const allStores = ref<VectorStoreEntity[]>([])
const localVectorStoreId = ref<string>(props.vectorStoreId || '')
// Only show user-defined stores in the dropdown. The env store is
// surfaced via the explicit "System default" entry at the top of the
// list; including it twice would confuse users about which one is the
// fallback path.
const userStores = computed(() => allStores.value.filter((s) => s.source === 'user'))
// Engine type for the env store, shown as a tag next to the "System
// default" label so users know which storage backend handles unbound
// KBs (e.g. "postgres"). When the env-store entry is missing or its
// engine type is not populated, the tag is hidden entirely rather than
// showing a placeholder.
const envEngineType = computed(() => {
const envStore = allStores.value.find((s) => s.source === 'env')
return envStore?.engine_type || ''
})
watch(
() => props.vectorStoreId,
(v) => {
localVectorStoreId.value = v || ''
},
)
const handleChange = (val: string | undefined) => {
// t-select's clear emits undefined; normalize to empty string so the
// parent treats both as "use system default".
emit('update:vectorStoreId', val || '')
}
// Open the global Settings panel directly on the Vector Stores
// section. This follows the same pattern as the other KB editor "go
// to settings" links (parser, storage, models): it talks to the UI
// store rather than navigating via the router, so the host editor
// modal stays mounted and can be returned to once the user closes the
// settings panel.
const goToVectorStoreSettings = () => {
uiStore.openSettings('vectorstore')
}
onMounted(async () => {
if (props.mode !== 'create') return
loading.value = true
try {
const resp = await listVectorStores()
if (resp.success) allStores.value = resp.data || []
} catch (e) {
// Graceful degradation: if vector-store listing fails the dropdown
// simply renders only the "System default" entry, which is exactly
// the legacy behavior. The KB editor remains usable.
console.warn('[KBVectorStoreSettings] failed to load vector stores', e)
} finally {
loading.value = false
}
})
</script>
<style scoped>
.kb-vector-store-settings {
display: flex;
flex-direction: column;
gap: 16px;
}
.section-header h2 {
font-size: 16px;
font-weight: 600;
margin: 0 0 4px;
}
.section-description {
color: var(--td-text-color-secondary, #4e5969);
font-size: 13px;
margin: 0;
}
.settings-group {
background: var(--td-bg-color-container, #fff);
border: 1px solid var(--td-component-stroke, #dcdcdc);
border-radius: 6px;
padding: 16px;
}
.setting-row {
display: flex;
gap: 24px;
align-items: flex-start;
}
.setting-info {
flex: 0 0 220px;
}
.setting-info label {
font-weight: 500;
display: block;
margin-bottom: 4px;
}
.setting-info .desc {
font-size: 12px;
color: var(--td-text-color-secondary, #4e5969);
margin: 0;
}
.setting-control {
flex: 1;
display: flex;
flex-direction: column;
gap: 8px;
}
.option-hint {
font-size: 12px;
color: var(--td-text-color-secondary, #4e5969);
margin: 0;
}
.change-warning {
color: var(--td-error-color, #d54941);
}
.go-settings {
font-size: 12px;
color: var(--td-brand-color, #0052d9);
text-decoration: none;
}
.go-settings:hover {
text-decoration: underline;
}
.select-option {
display: flex;
align-items: center;
gap: 8px;
}
.loading-inline {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
color: var(--td-text-color-secondary, #4e5969);
}
</style>
+23 -2
View File
@@ -261,11 +261,19 @@ func (s *vectorStoreService) SaveDetectedVersion(ctx context.Context, store *typ
// transient infrastructure failures can be classified, but the returned
// StoreDisplay is still UnavailableStoreDisplay so a handler that ignores
// the error degrades gracefully rather than panicking on a zero value.
// EnvDefaultStoreView is the env-fallback display, enriched with the
// active env store's engine type when one is configured. Exposed
// separately from ResolveStoreView so list paths can fill the
// env-bound entries without invoking the single-KB resolver.
func (s *vectorStoreService) EnvDefaultStoreView(_ context.Context) types.StoreDisplay {
return s.defaultStoreDisplay()
}
func (s *vectorStoreService) ResolveStoreView(
ctx context.Context, tenantID uint64, storeID string,
) (types.StoreDisplay, error) {
if storeID == "" {
return types.DefaultStoreDisplay(), nil
return s.defaultStoreDisplay(), nil
}
store, err := s.repo.GetByID(ctx, tenantID, storeID)
if err != nil {
@@ -359,7 +367,7 @@ func (s *vectorStoreService) BatchResolveStoreView(
// sentinel so callers can rely on a key for every requested ID.
for _, id := range storeIDs {
if id == "" {
out[id] = types.DefaultStoreDisplay()
out[id] = s.defaultStoreDisplay()
continue
}
if _, ok := out[id]; !ok {
@@ -369,6 +377,19 @@ func (s *vectorStoreService) BatchResolveStoreView(
return out, nil
}
// defaultStoreDisplay returns the env-fallback display, enriched with the
// active env store's engine type when one is configured. Callers receive a
// fully populated StoreDisplay so UIs can render the same badge shape for
// env-bound and user-bound KBs (e.g. "postgres" vs "qdrant") without
// branching on Source.
func (s *vectorStoreService) defaultStoreDisplay() types.StoreDisplay {
d := types.DefaultStoreDisplay()
if len(s.envStores) > 0 {
d.EngineType = string(s.envStores[0].EngineType)
}
return d
}
// registerInRegistry creates an engine service and registers it in the registry.
// Logs and skips on failure — the store is already persisted in DB,
// and will be loaded on next app restart (self-healing).
+130 -3
View File
@@ -109,6 +109,132 @@ func buildKBResponse(
return m
}
// buildKBListResponse turns a slice of knowledge bases into a JSON-ready
// slice that mirrors the single-KB enrichment in buildKBResponse. Store
// views are batch-resolved once via BatchResolveStoreView to keep the
// list endpoint O(1) in vector-store service calls — the per-KB
// resolveKBStoreView would otherwise be N+1.
//
// Caller-vs-owner semantics match the single-KB path:
// - KB has no binding → DefaultStoreDisplay()
// - KB is owned by another tenant (cross-tenant shared) → SharedStoreDisplay()
// - KB is own-tenant bound → look up in the batch result; misses
// fall back to UnavailableStoreDisplay()
//
// Resolver failures degrade gracefully: every own-tenant bound KB renders
// as unavailable instead of breaking the list response.
func (h *KnowledgeBaseHandler) buildKBListResponse(
ctx context.Context, kbs []*types.KnowledgeBase, callerTenantID uint64,
) []interface{} {
defaultView := h.envDefaultStoreView(ctx)
storeViews := h.batchResolveKBStoreViews(ctx, kbs, callerTenantID)
out := make([]interface{}, 0, len(kbs))
for _, kb := range kbs {
var view types.StoreDisplay
switch {
case !kb.HasVectorStore():
view = defaultView
case kb.TenantID != callerTenantID:
view = types.SharedStoreDisplay()
default:
v, ok := storeViews[*kb.VectorStoreID]
if !ok || v.Source == "" {
view = types.UnavailableStoreDisplay()
} else {
view = v
}
}
out = append(out, buildKBResponse(kb, view, nil))
}
return out
}
// sharedKBRow projects a SharedKnowledgeBaseInfo into a response payload
// that respects the cross-tenant strip rule: the embedded KnowledgeBase
// row runs through buildKBResponse with SharedStoreDisplay() so its
// vector_store_id and any owner-tenant store metadata never reach the
// wire. The share-record fields (share_id, organization_id, etc.) are
// kept intact alongside the stripped KB. Callers can pass extras to
// merge view-specific keys such as is_mine or source_from_agent.
//
// Always uses SharedStoreDisplay() regardless of whether the caller is
// the owner; the cross-tenant share endpoints serve mixed audiences and
// the owner's "rich" view of their own bindings is already served by
// ListKnowledgeBases / single-KB GET on the standard knowledge-base
// routes. Trying to enrich own-row entries here would either require
// threading the vector-store service through the organization handler
// or duplicating the lookup logic — both larger than the security fix
// warrants and easy to follow up on once needed.
func sharedKBRow(
info *types.SharedKnowledgeBaseInfo, extras map[string]interface{},
) map[string]interface{} {
kbView := buildKBResponse(info.KnowledgeBase, types.SharedStoreDisplay(), nil)
row := map[string]interface{}{
"knowledge_base": kbView,
"share_id": info.ShareID,
"organization_id": info.OrganizationID,
"org_name": info.OrgName,
"permission": info.Permission,
"source_tenant_id": info.SourceTenantID,
"shared_at": info.SharedAt,
}
for k, v := range extras {
row[k] = v
}
return row
}
// envDefaultStoreView returns the env-fallback store display enriched with
// the configured env-store engine type when the service is available. The
// service path populates EngineType so the caller can show "postgres" or
// "qdrant" on the env-default badge instead of leaving it blank. A nil
// service (e.g. in narrow unit-test setups) falls back to the bare default
// display rather than failing the list response.
func (h *KnowledgeBaseHandler) envDefaultStoreView(ctx context.Context) types.StoreDisplay {
if h.vectorStoreService == nil {
return types.DefaultStoreDisplay()
}
return h.vectorStoreService.EnvDefaultStoreView(ctx)
}
// batchResolveKBStoreViews collects the unique own-tenant store IDs across
// the KB slice and resolves them in one BatchResolveStoreView call.
// Cross-tenant shared KBs never enter the batch — they always render
// via SharedStoreDisplay, which deliberately suppresses the owner
// tenant's store name and engine type so cross-tenant viewers cannot
// correlate the owner's store inventory from KB responses alone.
func (h *KnowledgeBaseHandler) batchResolveKBStoreViews(
ctx context.Context, kbs []*types.KnowledgeBase, callerTenantID uint64,
) map[string]types.StoreDisplay {
if h.vectorStoreService == nil {
return nil
}
storeIDs := make([]string, 0, len(kbs))
seen := make(map[string]bool, len(kbs))
for _, kb := range kbs {
if !kb.HasVectorStore() || kb.TenantID != callerTenantID {
continue
}
sid := *kb.VectorStoreID
if !seen[sid] {
seen[sid] = true
storeIDs = append(storeIDs, sid)
}
}
if len(storeIDs) == 0 {
return nil
}
views, err := h.vectorStoreService.BatchResolveStoreView(ctx, callerTenantID, storeIDs)
if err != nil {
logger.WarnWithFields(ctx, logger.Fields{
"tenant_id": callerTenantID,
"store_count": len(storeIDs),
}, "[kb.list] batch store view resolve failed; rendering bound KBs as unavailable")
return nil
}
return views
}
// resolveKBStoreView returns the store display payload to embed in the KB
// response. It applies two policies on top of the service-level resolver:
//
@@ -124,7 +250,7 @@ func (h *KnowledgeBaseHandler) resolveKBStoreView(
ctx context.Context, kb *types.KnowledgeBase, callerTenantID uint64,
) types.StoreDisplay {
if !kb.HasVectorStore() {
return types.DefaultStoreDisplay()
return h.envDefaultStoreView(ctx)
}
if kb.TenantID != callerTenantID {
return types.SharedStoreDisplay()
@@ -504,7 +630,7 @@ func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": kbs,
"data": h.buildKBListResponse(ctx, kbs, currentTenantID),
})
return
}
@@ -567,9 +693,10 @@ func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) {
// CreatorID 为空的老数据)就让字段为空,前端按 fallback 渲染。
enrichKBCreatorNames(ctx, h.userService, kbs)
callerTenantID := c.GetUint64(types.TenantIDContextKey.String())
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": kbs,
"data": h.buildKBListResponse(ctx, kbs, callerTenantID),
})
}
@@ -0,0 +1,244 @@
package handler
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// ListKnowledgeBases store-enrichment — every KB in the list response
// carries the same resolved vector_store_* metadata as the single-KB
// endpoint. The list path funnels the resolution through
// BatchResolveStoreView so an N-KB list costs one service call rather
// than N. Cross-tenant shared KBs still render via SharedStoreDisplay
// so the owner-tenant's store inventory cannot be correlated across
// rows in the same response.
// stubListKBService returns a fixed slice from ListKnowledgeBases. Only
// the methods exercised by ListKnowledgeBases are implemented; embedding
// the interface keeps the rest nil-panic'ing intentionally.
type stubListKBService struct {
interfaces.KnowledgeBaseService
kbs []*types.KnowledgeBase
}
func (s *stubListKBService) ListKnowledgeBases(context.Context) ([]*types.KnowledgeBase, error) {
return s.kbs, nil
}
// stubVectorStoreService satisfies the two service methods the list
// path depends on: BatchResolveStoreView for bound KBs and
// EnvDefaultStoreView for env-fallback KBs. ResolveStoreView is
// intentionally left nil because ListKnowledgeBases must never reach
// into the single-KB resolver — doing so per row would be the N+1
// pattern this path is designed to avoid.
type stubVectorStoreService struct {
interfaces.VectorStoreService
batch map[string]types.StoreDisplay
batchCalls int
batchErr error
envView types.StoreDisplay
}
func (s *stubVectorStoreService) BatchResolveStoreView(
_ context.Context, _ uint64, storeIDs []string,
) (map[string]types.StoreDisplay, error) {
s.batchCalls++
if s.batchErr != nil {
return nil, s.batchErr
}
out := make(map[string]types.StoreDisplay, len(storeIDs))
for _, id := range storeIDs {
if v, ok := s.batch[id]; ok {
out[id] = v
} else {
out[id] = types.UnavailableStoreDisplay()
}
}
return out, nil
}
func (s *stubVectorStoreService) EnvDefaultStoreView(_ context.Context) types.StoreDisplay {
if s.envView.Source == "" {
return types.DefaultStoreDisplay()
}
return s.envView
}
func newListKBRouter(
t *testing.T,
svc interfaces.KnowledgeBaseService,
vss interfaces.VectorStoreService,
) *gin.Engine {
t.Helper()
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
r.Use(func(c *gin.Context) {
c.Set(types.TenantIDContextKey.String(), uint64(1))
c.Set(types.UserIDContextKey.String(), "u-test")
c.Next()
})
h := &KnowledgeBaseHandler{service: svc, vectorStoreService: vss}
r.GET("/knowledge-bases", h.ListKnowledgeBases)
return r
}
func TestListKB_EnrichesEnvBoundAndSharedDistinctly(t *testing.T) {
storeUserA := "aaaa-bbbb-cccc-dddd"
storeForeign := "ffff-eeee-dddd-cccc"
kbs := []*types.KnowledgeBase{
{ID: "kb-env", Name: "env", TenantID: 1},
{ID: "kb-bound", Name: "bound", TenantID: 1, VectorStoreID: &storeUserA},
{ID: "kb-shared", Name: "shared", TenantID: 99, VectorStoreID: &storeForeign},
}
vss := &stubVectorStoreService{
batch: map[string]types.StoreDisplay{
storeUserA: {
Name: "prod-qdrant",
Source: types.StoreSourceUser,
EngineType: "qdrant",
Status: "available",
},
// storeForeign is intentionally absent — shared KBs do not
// flow through BatchResolveStoreView so the stub must never
// see it. The assertion below confirms.
},
}
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/knowledge-bases", nil)
newListKBRouter(t, &stubListKBService{kbs: kbs}, vss).ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
}
var envelope struct {
Success bool `json:"success"`
Data []map[string]interface{} `json:"data"`
}
if err := json.Unmarshal(w.Body.Bytes(), &envelope); err != nil {
t.Fatalf("decode: %v body=%s", err, w.Body.String())
}
if !envelope.Success || len(envelope.Data) != 3 {
t.Fatalf("expected 3 rows, got %d body=%s", len(envelope.Data), w.Body.String())
}
byID := map[string]map[string]interface{}{}
for _, row := range envelope.Data {
byID[row["id"].(string)] = row
}
// 1) env-store KB — System default labelling, no engine type.
envRow := byID["kb-env"]
if envRow["vector_store_source"] != string(types.StoreSourceEnv) {
t.Errorf("env KB: expected source=env, got %v", envRow["vector_store_source"])
}
if name, _ := envRow["vector_store_name"].(string); name == "" {
t.Errorf("env KB: expected non-empty system-default name")
}
// 2) own-tenant bound KB — name + engine surfaced.
boundRow := byID["kb-bound"]
if boundRow["vector_store_source"] != string(types.StoreSourceUser) {
t.Errorf("bound KB: expected source=user, got %v", boundRow["vector_store_source"])
}
if boundRow["vector_store_name"] != "prod-qdrant" {
t.Errorf("bound KB: expected name=prod-qdrant, got %v", boundRow["vector_store_name"])
}
if boundRow["vector_store_engine_type"] != "qdrant" {
t.Errorf("bound KB: expected engine=qdrant, got %v", boundRow["vector_store_engine_type"])
}
// 3) cross-tenant shared KB — UUID stripped, source=shared, no name.
sharedRow := byID["kb-shared"]
if _, exists := sharedRow["vector_store_id"]; exists {
t.Errorf("shared KB must NOT expose vector_store_id, got %v", sharedRow["vector_store_id"])
}
if sharedRow["vector_store_source"] != string(types.StoreSourceShared) {
t.Errorf("shared KB: expected source=shared, got %v", sharedRow["vector_store_source"])
}
if name, ok := sharedRow["vector_store_name"]; ok && name != "" {
t.Errorf("shared KB must not surface a name, got %v", name)
}
// Defensive: the foreign store UUID must not appear anywhere in the
// shared row's serialized payload.
serialized, _ := json.Marshal(sharedRow)
if strings.Contains(string(serialized), storeForeign) {
t.Fatalf("shared row leaked foreign store UUID: %s", serialized)
}
}
func TestListKB_BatchesStoreLookupsToAvoidNPlus1(t *testing.T) {
// Five KBs bound to three distinct stores. The list endpoint must
// resolve them in a single BatchResolveStoreView call regardless of
// row count — calling the per-KB ResolveStoreView path inside the
// loop would issue one service call per KB (the N+1 pattern this
// test pins against).
s1, s2, s3 := "store-1", "store-2", "store-3"
kbs := []*types.KnowledgeBase{
{ID: "a", TenantID: 1, VectorStoreID: &s1},
{ID: "b", TenantID: 1, VectorStoreID: &s2},
{ID: "c", TenantID: 1, VectorStoreID: &s1}, // dup
{ID: "d", TenantID: 1, VectorStoreID: &s3},
{ID: "e", TenantID: 1}, // env, no store call
}
vss := &stubVectorStoreService{
batch: map[string]types.StoreDisplay{
s1: {Name: "s1", Source: types.StoreSourceUser, EngineType: "qdrant", Status: "available"},
s2: {Name: "s2", Source: types.StoreSourceUser, EngineType: "postgres", Status: "available"},
s3: {Name: "s3", Source: types.StoreSourceUser, EngineType: "weaviate", Status: "available"},
},
}
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/knowledge-bases", nil)
newListKBRouter(t, &stubListKBService{kbs: kbs}, vss).ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", w.Code)
}
if vss.batchCalls != 1 {
t.Fatalf("expected exactly 1 batch store-view call (N+1 protection), got %d", vss.batchCalls)
}
}
func TestListKB_GracefullyDegradesWhenBatchResolveFails(t *testing.T) {
// If the store-view resolver fails, the list response must still
// succeed — bound KBs render as unavailable. The list endpoint is
// not allowed to 500 just because the vector-store service is
// momentarily unhealthy.
storeID := "aaaa-bbbb"
kbs := []*types.KnowledgeBase{
{ID: "kb", TenantID: 1, VectorStoreID: &storeID},
}
vss := &stubVectorStoreService{batchErr: errSentinel("infra glitch")}
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/knowledge-bases", nil)
newListKBRouter(t, &stubListKBService{kbs: kbs}, vss).ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200 even when batch resolve fails, got %d body=%s", w.Code, w.Body.String())
}
var envelope struct {
Success bool `json:"success"`
Data []map[string]interface{} `json:"data"`
}
_ = json.Unmarshal(w.Body.Bytes(), &envelope)
if len(envelope.Data) != 1 {
t.Fatalf("expected 1 row, got %d", len(envelope.Data))
}
if envelope.Data[0]["vector_store_source"] != string(types.StoreSourceUnavailable) {
t.Errorf("expected fallback source=unavailable, got %v", envelope.Data[0]["vector_store_source"])
}
}
+33 -3
View File
@@ -1304,10 +1304,21 @@ func (h *OrganizationHandler) ListSharedKnowledgeBases(c *gin.Context) {
return
}
// Each row goes through sharedKBRow so the embedded KnowledgeBase
// payload runs SharedStoreDisplay() before serialization. This is
// the cross-tenant strip path: callers never receive the owning
// tenant's vector_store_id, vector_store_name, or
// vector_store_engine_type from the share endpoints. The share
// metadata (share_id, organization_id, etc.) is preserved as-is.
rows := make([]map[string]interface{}, 0, len(sharedKBs))
for _, info := range sharedKBs {
rows = append(rows, sharedKBRow(info, nil))
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": sharedKBs,
"total": len(sharedKBs),
"data": rows,
"total": len(rows),
})
}
@@ -1639,7 +1650,26 @@ func (h *OrganizationHandler) ListOrganizationSharedKnowledgeBases(c *gin.Contex
c.Error(apperrors.NewInternalServerError("Failed to list shared knowledge bases"))
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": list, "total": len(list)})
// Project each row through sharedKBRow so cross-tenant strip applies
// uniformly across the space view as well. is_mine and the optional
// source_from_agent payload are passed through as extras so the
// frontend can keep its current rendering branches. Rows where
// is_mine is true are still strip-projected here — callers see the
// rich view of their own bindings on the regular KB list / detail
// endpoints, so dropping the owner-side enrichment from the space
// view trades a small UI nicety for a strictly simpler invariant
// ("share endpoints never leak vector-store metadata").
rows := make([]map[string]interface{}, 0, len(list))
for _, item := range list {
extras := map[string]interface{}{"is_mine": item.IsMine}
if item.SourceFromAgent != nil {
extras["source_from_agent"] = item.SourceFromAgent
}
rows = append(rows, sharedKBRow(&item.SharedKnowledgeBaseInfo, extras))
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": rows, "total": len(rows)})
}
// ListOrganizationSharedAgents lists all agents in the given organization (including those shared by the current tenant), for the list page when a space is selected.
+9
View File
@@ -57,6 +57,15 @@ type VectorStoreService interface {
// Intended for list endpoints that need store metadata for many KBs at
// once without incurring N+1 ResolveStoreView calls.
BatchResolveStoreView(ctx context.Context, tenantID uint64, storeIDs []string) (map[string]types.StoreDisplay, error)
// EnvDefaultStoreView returns the display payload for KBs that fall
// back to the env-configured store. Unlike DefaultStoreDisplay() in
// the types package, this method also fills the engine type
// (e.g. "postgres") so UIs can render the same badge shape for
// env-bound and user-bound KBs. Independent of ResolveStoreView so
// list paths can use it without violating the "no per-KB
// ResolveStoreView" invariant.
EnvDefaultStoreView(ctx context.Context) types.StoreDisplay
}
// VectorStoreRepository defines the repository interface for VectorStore CRUD.