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
+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.