feat(settings): bind internal/external knowledge bases from the UI

Routing targets move from env-only to a UI-managed binding (migration
000034 routing_kb_bindings, single active row):
- GET/PUT /api/v1/routing-bindings + /options: env defaults act as the
  bootstrap fallback; a UI binding wins and takes effect immediately
  (per-request resolution, no restart), and clearing falls back to env
- PUT validates against the connected WeKnora instance (real knowledge
  base list via the scoped API key) and rejects same-KB bindings;
  saves require the admin role
- route/catalog capabilities now resolve through the binding so both
  annotation paths share one source of truth
- system settings > 服务配置 gains a 知识库绑定 panel: dropdown picker
  (or raw ID when WeKnora is unreachable) showing bound name, origin
  (UI vs env default) and last author
- contract tests: OpenAPI, handler matrix (fallback, validation,
  same-KB rejection, capability resolution), frontend fetch/save layer
This commit is contained in:
姚章浩
2026-09-14 14:45:35 +08:00
parent 4c86c5e659
commit 021e91eae4
17 changed files with 676 additions and 13 deletions
+68
View File
@@ -1127,6 +1127,74 @@
}
}
},
"/api/v1/routing-bindings": {
"get": {
"tags": [
"Settings"
],
"operationId": "getRoutingBindings",
"summary": "读取对内/对外知识库绑定",
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
},
"put": {
"tags": [
"Settings"
],
"operationId": "saveRoutingBindings",
"summary": "绑定对内/对外知识库(管理员)",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
},
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
},
"/api/v1/routing-bindings/options": {
"get": {
"tags": [
"Settings"
],
"operationId": "listRoutingBindingOptions",
"summary": "列出可绑定的 WeKnora 知识库",
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
},
"/api/v1/ui-settings": {
"get": {
"tags": [
+4
View File
@@ -58,6 +58,7 @@ func run(ctx context.Context, getenv func(string) string) error {
// P10: with a mounted API key the probe verifies a real knowledge-base read
// (readiness); without one it degrades to the liveness-only HTTP check.
var weknoraReadiness func(context.Context) error
var knowledgeBaseLister httpapi.KnowledgeBaseLister
if strings.TrimSpace(config.TestWeKnoraBaseURL) != "" {
if apiKey, keyErr := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile); keyErr == nil {
probeTimeout := config.TestWeKnoraHTTPTimeout
@@ -65,6 +66,7 @@ func run(ctx context.Context, getenv func(string) string) error {
probeTimeout = 10 * time.Second
}
if probeClient, clientErr := weknora.NewClient(weknora.ClientConfig{BaseURL: config.TestWeKnoraBaseURL, APIKey: apiKey, Timeout: probeTimeout, AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP}); clientErr == nil {
knowledgeBaseLister = probeClient
routingKB := config.InternalRoutingKnowledgeBaseID
weknoraReadiness = func(probeCtx context.Context) error {
_, _, err := probeClient.ListKnowledge(probeCtx, routingKB, 1, 1)
@@ -82,6 +84,8 @@ func run(ctx context.Context, getenv func(string) string) error {
Monitor: monitorProvider,
InternalRoutingKnowledgeBaseID: config.InternalRoutingKnowledgeBaseID,
ExternalRoutingKnowledgeBaseID: config.ExternalRoutingKnowledgeBaseID,
RoutingBindings: postgresstore.NewStore(pool),
KnowledgeBases: knowledgeBaseLister,
ProductionReleaseRequestsEnabled: config.ProductionReleaseRequestsEnabled,
ProductionBackupRestoreVerified: config.ProductionBackupRestoreVerified,
ProductionReleaseAuthorizerRef: config.ProductionReleaseAuthorizerRef,
+5
View File
@@ -117,6 +117,11 @@ func classifyRole(method, path string) string {
if strings.Contains(path, "/settings/revisions") {
return roleAdmin
}
// Binding the internal/external knowledge bases re-routes every future
// annotation: admin-only, like the roster and production authority.
if path == "/api/v1/routing-bindings" && method != http.MethodGet {
return roleAdmin
}
// Everything else that mutates (review, batch, seal, confirm, start, retry,
// route visibility, disable) is engineer work; viewers cannot POST at all.
return roleEngineer
+160
View File
@@ -0,0 +1,160 @@
package httpapi
import (
"context"
"net/http"
"strings"
"knowledge-governance/internal/platform/weknora"
)
// RoutingBindingStore persists the UI-managed knowledge base bindings
// (migration 000034). Empty stored values fall back to env defaults.
type RoutingBindingStore interface {
LoadRoutingKBBindings(context.Context) (string, string, string, error)
SaveRoutingKBBindings(context.Context, string, string, string) error
}
// KnowledgeBaseLister enumerates candidate knowledge bases in the connected
// WeKnora so the settings page offers a picker instead of raw UUIDs.
type KnowledgeBaseLister interface {
ListKnowledgeBases(context.Context) ([]weknora.KnowledgeBase, error)
}
type routingBindingView struct {
InternalKBID string `json:"internal_kb_id"`
ExternalKBID string `json:"external_kb_id"`
InternalEnvFallback bool `json:"internal_env_fallback"`
ExternalEnvFallback bool `json:"external_env_fallback"`
InternalBoundByUI bool `json:"internal_bound_by_ui"`
ExternalBoundByUI bool `json:"external_bound_by_ui"`
InternalKBName string `json:"internal_kb_name"`
ExternalKBName string `json:"external_kb_name"`
UpdatedBy string `json:"updated_by"`
WeKnoraConnected bool `json:"weknora_connected"`
}
type routingKnowledgeBaseOption struct {
ID string `json:"id"`
Name string `json:"name"`
KnowledgeCount int64 `json:"knowledge_count"`
}
// effectiveRoutingTargets resolves (internal, external) WeKnora knowledge
// base ids for this request: UI bindings win, environment defaults fill the
// unbound side. Load failures behave as "unbound" (fail toward env, never
// toward a half-configured new target).
func (config Config) effectiveRoutingTargets(ctx context.Context) (string, string) {
internal, external := config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID
if config.RoutingBindings == nil {
return internal, external
}
storedInternal, storedExternal, _, err := config.RoutingBindings.LoadRoutingKBBindings(ctx)
if err != nil {
return internal, external
}
if storedInternal != "" {
internal = storedInternal
}
if storedExternal != "" {
external = storedExternal
}
return internal, external
}
func (config Config) routingBindingNames(ctx context.Context) (map[string]string, bool) {
if config.KnowledgeBases == nil {
return nil, false
}
bases, err := config.KnowledgeBases.ListKnowledgeBases(ctx)
if err != nil {
return nil, false
}
names := make(map[string]string, len(bases))
for _, base := range bases {
names[base.ID] = base.Name
}
return names, true
}
func (config Config) handleRoutingBindings(w http.ResponseWriter, r *http.Request) {
names, connected := config.routingBindingNames(r.Context())
storedInternal, storedExternal, updatedBy, err := config.RoutingBindings.LoadRoutingKBBindings(r.Context())
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load routing bindings"})
return
}
internal, external := config.effectiveRoutingTargets(r.Context())
view := routingBindingView{
InternalKBID: internal, ExternalKBID: external,
InternalBoundByUI: storedInternal != "", ExternalBoundByUI: storedExternal != "",
InternalEnvFallback: storedInternal == "" && config.InternalRoutingKnowledgeBaseID != "",
ExternalEnvFallback: storedExternal == "" && config.ExternalRoutingKnowledgeBaseID != "",
InternalKBName: names[storedInternal], ExternalKBName: names[storedExternal],
UpdatedBy: updatedBy, WeKnoraConnected: connected,
}
writeJSON(w, http.StatusOK, map[string]any{"data": view})
}
func (config Config) handleRoutingKnowledgeBaseOptions(w http.ResponseWriter, r *http.Request) {
if config.KnowledgeBases == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "WeKnora connection is not configured"})
return
}
bases, err := config.KnowledgeBases.ListKnowledgeBases(r.Context())
if err != nil {
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "could not list WeKnora knowledge bases"})
return
}
options := make([]routingKnowledgeBaseOption, 0, len(bases))
for _, base := range bases {
options = append(options, routingKnowledgeBaseOption{ID: base.ID, Name: base.Name, KnowledgeCount: base.KnowledgeCount})
}
writeJSON(w, http.StatusOK, map[string]any{"data": options})
}
func (config Config) handleSaveRoutingBindings(w http.ResponseWriter, r *http.Request) {
var input struct {
InternalKBID string `json:"internal_kb_id"`
ExternalKBID string `json:"external_kb_id"`
}
if err := decodeStrictJSON(r, &input); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"})
return
}
internal := strings.TrimSpace(input.InternalKBID)
external := strings.TrimSpace(input.ExternalKBID)
for _, id := range []string{internal, external} {
if id != "" && !validCatalogID(id) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "knowledge base ID is invalid"})
return
}
}
if internal != "" && internal == external {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "对内与对外必须绑定不同的知识库"})
return
}
// When WeKnora is reachable the binding must name a real knowledge base;
// offline saves fall through to the DB so the page never hard-fails, but
// the response reports connected=false honestly.
names, connected := config.routingBindingNames(r.Context())
if connected {
if internal != "" {
if _, ok := names[internal]; !ok {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "对内绑定的知识库在该 WeKnora 实例中不存在"})
return
}
}
if external != "" {
if _, ok := names[external]; !ok {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "对外绑定的知识库在该 WeKnora 实例中不存在"})
return
}
}
}
if err := config.RoutingBindings.SaveRoutingKBBindings(r.Context(), internal, external, actorFor(r)); err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not save routing bindings"})
return
}
config.handleRoutingBindings(w, r)
}
+121
View File
@@ -0,0 +1,121 @@
package httpapi
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"knowledge-governance/internal/platform/weknora"
)
type bindingStoreFake struct {
internal string
external string
saver string
}
func (fake *bindingStoreFake) LoadRoutingKBBindings(context.Context) (string, string, string, error) {
return fake.internal, fake.external, fake.saver, nil
}
func (fake *bindingStoreFake) SaveRoutingKBBindings(_ context.Context, internal, external, updatedBy string) error {
fake.internal, fake.external, fake.saver = internal, external, updatedBy
return nil
}
type kbListerFake struct {
bases []weknora.KnowledgeBase
err error
}
func (fake *kbListerFake) ListKnowledgeBases(context.Context) ([]weknora.KnowledgeBase, error) {
return fake.bases, fake.err
}
func bindingsTestHandler(t *testing.T, store RoutingBindingStore, lister KnowledgeBaseLister, envInternal, envExternal string) http.Handler {
t.Helper()
handler, err := NewHandler(Config{
Store: &fakeJobStore{}, Monitor: nil,
InternalRoutingKnowledgeBaseID: envInternal, ExternalRoutingKnowledgeBaseID: envExternal,
RoutingBindings: store, KnowledgeBases: lister,
Now: func() time.Time { return time.Date(2026, time.September, 13, 8, 0, 0, 0, time.UTC) },
})
if err != nil {
t.Fatalf("NewHandler: %v", err)
}
return handler
}
func TestRoutingBindingsReadFallsBackToEnv(t *testing.T) {
store := &bindingStoreFake{internal: "", external: "fd-ext"}
handler := bindingsTestHandler(t, store, &kbListerFake{bases: []weknora.KnowledgeBase{{ID: "fd-ext", Name: "对外库"}}}, "sn-internal", "env-external")
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/routing-bindings", nil))
if recorder.Code != http.StatusOK {
t.Fatalf("status = %d body %s", recorder.Code, recorder.Body.String())
}
var envelope struct {
Data routingBindingView `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &envelope); err != nil {
t.Fatal(err)
}
view := envelope.Data
if view.InternalKBID != "sn-internal" || !view.InternalEnvFallback || view.InternalBoundByUI {
t.Fatalf("internal side = %#v", view)
}
if view.ExternalKBID != "fd-ext" || !view.ExternalBoundByUI || view.ExternalKBName != "对外库" {
t.Fatalf("external side = %#v", view)
}
if !view.WeKnoraConnected {
t.Fatalf("connected must be true: %#v", view)
}
}
func TestRoutingBindingsSaveValidatesAgainstWeKnora(t *testing.T) {
store := &bindingStoreFake{}
lister := &kbListerFake{bases: []weknora.KnowledgeBase{{ID: "kb-in", Name: "对内库"}, {ID: "kb-ex", Name: "对外库"}}}
handler := bindingsTestHandler(t, store, lister, "", "")
body := `{"internal_kb_id":"kb-in","external_kb_id":"missing"}`
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPut, "/api/v1/routing-bindings", strings.NewReader(body)))
if recorder.Code != http.StatusBadRequest || !strings.Contains(recorder.Body.String(), "对外绑定的知识库") {
t.Fatalf("unknown target must be rejected: %d %s", recorder.Code, recorder.Body.String())
}
if store.internal != "" {
t.Fatalf("rejected save must not persist: %#v", store)
}
recorder = httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPut, "/api/v1/routing-bindings", strings.NewReader(`{"internal_kb_id":"kb-in","external_kb_id":"kb-in"}`)))
if recorder.Code != http.StatusBadRequest || !strings.Contains(recorder.Body.String(), "不同的知识库") {
t.Fatalf("same-kb binding must be rejected: %d %s", recorder.Code, recorder.Body.String())
}
recorder = httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPut, "/api/v1/routing-bindings", strings.NewReader(`{"internal_kb_id":"kb-in","external_kb_id":"kb-ex"}`)))
if recorder.Code != http.StatusOK {
t.Fatalf("valid binding must save: %d %s", recorder.Code, recorder.Body.String())
}
if store.internal != "kb-in" || store.external != "kb-ex" {
t.Fatalf("store = %#v", store)
}
}
func TestRouteCatalogFilesUsesUIBinding(t *testing.T) {
store := &bindingStoreFake{internal: "ui-internal", external: "ui-external"}
handler := bindingsTestHandler(t, store, &kbListerFake{}, "env-internal", "env-external")
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/source-catalog/routing-capabilities", nil))
var envelope struct {
Data map[string]bool `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &envelope); err != nil {
t.Fatal(err)
}
if !envelope.Data["internal_enabled"] || !envelope.Data["external_enabled"] {
t.Fatalf("capabilities = %#v", envelope.Data)
}
}
+33 -11
View File
@@ -99,6 +99,8 @@ type Config struct {
Monitor MonitorProvider
InternalRoutingKnowledgeBaseID string
ExternalRoutingKnowledgeBaseID string
RoutingBindings RoutingBindingStore
KnowledgeBases KnowledgeBaseLister
Now func() time.Time
RequireWeKnoraReady bool
ProductionReleaseRequestsEnabled bool
@@ -202,8 +204,26 @@ func NewHandler(config Config) (http.Handler, error) {
mux.HandleFunc("GET /api/v1/source-catalog/change-sets/latest", func(w http.ResponseWriter, r *http.Request) {
getLatestCatalogChangeSet(w, r, config.Store)
})
mux.HandleFunc("GET /api/v1/source-catalog/routing-capabilities", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]bool{"internal_enabled": config.InternalRoutingKnowledgeBaseID != "", "external_enabled": config.ExternalRoutingKnowledgeBaseID != ""}})
mux.HandleFunc("GET /api/v1/source-catalog/routing-capabilities", func(w http.ResponseWriter, r *http.Request) {
internal, external := config.effectiveRoutingTargets(r.Context())
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]bool{"internal_enabled": internal != "", "external_enabled": external != ""}})
})
mux.HandleFunc("GET /api/v1/routing-bindings", func(w http.ResponseWriter, r *http.Request) {
if config.RoutingBindings == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "routing bindings storage unavailable"})
return
}
config.handleRoutingBindings(w, r)
})
mux.HandleFunc("GET /api/v1/routing-bindings/options", func(w http.ResponseWriter, r *http.Request) {
config.handleRoutingKnowledgeBaseOptions(w, r)
})
mux.HandleFunc("PUT /api/v1/routing-bindings", func(w http.ResponseWriter, r *http.Request) {
if config.RoutingBindings == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "routing bindings storage unavailable"})
return
}
config.handleSaveRoutingBindings(w, r)
})
mux.HandleFunc("POST /api/v1/source-catalog/route", func(w http.ResponseWriter, r *http.Request) {
routeCatalogFiles(w, r, config)
@@ -651,22 +671,23 @@ func routeCatalogFiles(w http.ResponseWriter, r *http.Request, config Config) {
policy = strings.TrimSpace(input.Visibility)
}
visibility := governance.Visibility(policy)
effectiveInternal, effectiveExternal := config.effectiveRoutingTargets(r.Context())
targetKnowledgeBaseIDs := make([]string, 0, 2)
switch visibility {
case governance.VisibilityInternal:
if config.InternalRoutingKnowledgeBaseID != "" {
targetKnowledgeBaseIDs = append(targetKnowledgeBaseIDs, config.InternalRoutingKnowledgeBaseID)
if effectiveInternal != "" {
targetKnowledgeBaseIDs = append(targetKnowledgeBaseIDs, effectiveInternal)
}
case governance.VisibilityExternal:
if config.ExternalRoutingKnowledgeBaseID != "" {
targetKnowledgeBaseIDs = append(targetKnowledgeBaseIDs, config.ExternalRoutingKnowledgeBaseID)
if effectiveExternal != "" {
targetKnowledgeBaseIDs = append(targetKnowledgeBaseIDs, effectiveExternal)
}
case governance.VisibilityBoth:
if config.InternalRoutingKnowledgeBaseID != "" {
targetKnowledgeBaseIDs = append(targetKnowledgeBaseIDs, config.InternalRoutingKnowledgeBaseID)
if effectiveInternal != "" {
targetKnowledgeBaseIDs = append(targetKnowledgeBaseIDs, effectiveInternal)
}
if config.ExternalRoutingKnowledgeBaseID != "" {
targetKnowledgeBaseIDs = append(targetKnowledgeBaseIDs, config.ExternalRoutingKnowledgeBaseID)
if effectiveExternal != "" {
targetKnowledgeBaseIDs = append(targetKnowledgeBaseIDs, effectiveExternal)
}
case governance.VisibilityBlocked:
default:
@@ -1728,10 +1749,11 @@ func confirmCatalogChangeSet(w http.ResponseWriter, r *http.Request, config Conf
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid change set confirmation"})
return
}
internalTarget, externalTarget := config.effectiveRoutingTargets(r.Context())
result, replayed, err := config.Store.ConfirmCatalogChangeSetWithOperation(r.Context(), governance.ConfirmCatalogChangeSetRequest{
ChangeSetID: r.PathValue("id"), ItemSeqs: input.ItemSeqs,
OperatorRef: actorFor(r), Reason: input.Reason,
InternalTargetKBID: config.InternalRoutingKnowledgeBaseID, ExternalTargetKBID: config.ExternalRoutingKnowledgeBaseID,
InternalTargetKBID: internalTarget, ExternalTargetKBID: externalTarget,
Now: config.Now().UTC(),
}, operationID)
if err != nil {
@@ -0,0 +1 @@
DROP TABLE IF EXISTS routing_kb_bindings;
@@ -0,0 +1,14 @@
-- Policy-driven ingestion, step 3: routable knowledge-base bindings move from
-- environment-only configuration into the UI. A single row stores which
-- WeKnora knowledge base receives 对内 and which receives 对外 annotations.
-- The env-supplied defaults stay as a bootstrap fallback only.
CREATE TABLE routing_kb_bindings (
id TEXT PRIMARY KEY DEFAULT 'active' CHECK (id = 'active'),
internal_kb_id VARCHAR(64) NOT NULL DEFAULT '',
external_kb_id VARCHAR(64) NOT NULL DEFAULT '',
updated_by VARCHAR(64) NOT NULL DEFAULT '',
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
INSERT INTO routing_kb_bindings(id,internal_kb_id,external_kb_id,updated_by)
VALUES('active','','','system:migration');
@@ -11,8 +11,8 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
if err != nil {
t.Fatalf("loadMigrations() error = %v", err)
}
if len(migrations) != 33 {
t.Fatalf("migration count = %d, want 33", len(migrations))
if len(migrations) != 34 {
t.Fatalf("migration count = %d, want 34", len(migrations))
}
if migrations[0].Version != 1 || !strings.Contains(migrations[0].UpSQL, "CREATE TABLE IF NOT EXISTS jobs") {
t.Fatalf("migration 1 = %#v", migrations[0])
@@ -0,0 +1,48 @@
package postgres
import (
"context"
"errors"
"github.com/jackc/pgx/v5"
)
// RoutingBinding is the UI-managed knowledge base binding row. Empty ids mean
// "not bound in the UI"; callers fall back to their environment defaults.
type RoutingBinding struct {
InternalKBID string
ExternalKBID string
UpdatedBy string
}
// LoadRoutingKBBindings reads the single active binding row. A missing row
// reads back as unbound rather than an error.
func (s *Store) LoadRoutingKBBindings(ctx context.Context) (string, string, string, error) {
var binding RoutingBinding
err := s.db.QueryRow(ctx, `SELECT internal_kb_id,external_kb_id,updated_by FROM routing_kb_bindings WHERE id='active'`).
Scan(&binding.InternalKBID, &binding.ExternalKBID, &binding.UpdatedBy)
if errors.Is(err, pgx.ErrNoRows) {
return "", "", "", nil
}
if err != nil {
return "", "", "", errors.New("load routing kb bindings")
}
return binding.InternalKBID, binding.ExternalKBID, binding.UpdatedBy, nil
}
// SaveRoutingKBBindings upserts the binding row. Each side is either empty
// (unbind, fall back to env) or a knowledge base id validated by the caller.
func (s *Store) SaveRoutingKBBindings(ctx context.Context, internalID, externalID, updatedBy string) error {
_, err := s.db.Exec(ctx, `
INSERT INTO routing_kb_bindings(id,internal_kb_id,external_kb_id,updated_by,updated_at)
VALUES('active',$1,$2,$3,NOW())
ON CONFLICT(id) DO UPDATE SET
internal_kb_id=EXCLUDED.internal_kb_id,
external_kb_id=EXCLUDED.external_kb_id,
updated_by=EXCLUDED.updated_by,
updated_at=NOW()`, internalID, externalID, updatedBy)
if err != nil {
return errors.New("save routing kb bindings")
}
return nil
}
+13
View File
@@ -221,6 +221,19 @@ func (c *Client) ListKnowledge(ctx context.Context, knowledgeBaseID string, page
return response.Data, response.Total, nil
}
// ListKnowledgeBases lists the knowledge bases visible to this API key so the
// UI can bind routing targets without humans copying UUIDs.
func (c *Client) ListKnowledgeBases(ctx context.Context) ([]KnowledgeBase, error) {
var response knowledgeBaseListResponse
if err := c.doJSON(ctx, http.MethodGet, "/api/v1/knowledge-bases", nil, &response); err != nil {
return nil, err
}
if !response.Success {
return nil, errors.New("WeKnora returned an unsuccessful knowledge base list")
}
return response.Data, nil
}
func (c *Client) ListChunks(ctx context.Context, knowledgeID string, page, pageSize int, chunkTypes []string) ([]Chunk, int64, error) {
if !validPathSegment(knowledgeID) || !validPage(page, pageSize) {
return nil, 0, errors.New("invalid chunk list request")
+14
View File
@@ -62,6 +62,20 @@ type knowledgeListResponse struct {
PageSize int `json:"page_size"`
}
// KnowledgeBase is the routing-relevant projection of a WeKnora knowledge
// base as listed by GET /api/v1/knowledge-bases.
type KnowledgeBase struct {
ID string `json:"id"`
Name string `json:"name"`
KnowledgeCount int64 `json:"knowledge_count"`
ChunkCount int64 `json:"chunk_count"`
}
type knowledgeBaseListResponse struct {
Success bool `json:"success"`
Data []KnowledgeBase `json:"data"`
}
type chunkListResponse struct {
Success bool `json:"success"`
Data []Chunk `json:"data"`
+80
View File
@@ -0,0 +1,80 @@
import { useCallback, useEffect, useState } from 'react'
import { useOptionalAuth } from './auth'
import { fetchRoutingBindingOptions, fetchRoutingBindings, saveRoutingBindings } from './routingBindings'
import type { KnowledgeBaseOption, RoutingBindings } from './routingBindings'
export function RoutingBindingsSection() {
const auth = useOptionalAuth()
const isAdmin = auth?.identity?.role === 'admin'
const [bindings, setBindings] = useState<RoutingBindings | null>(null)
const [options, setOptions] = useState<KnowledgeBaseOption[]>([])
const [internalDraft, setInternalDraft] = useState('')
const [externalDraft, setExternalDraft] = useState('')
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
const [message, setMessage] = useState('')
const load = useCallback(async () => {
setLoading(true); setError(null)
try {
const next = await fetchRoutingBindings()
setBindings(next)
setInternalDraft(next.internal_bound_by_ui ? next.internal_kb_id : '')
setExternalDraft(next.external_bound_by_ui ? next.external_kb_id : '')
try { setOptions(await fetchRoutingBindingOptions()) } catch { setOptions([]) }
} catch (cause) { setError(cause instanceof Error ? cause.message : '读取知识库绑定失败') }
finally { setLoading(false) }
}, [])
useEffect(() => { void load() }, [load])
const dirty = bindings !== null && (internalDraft !== (bindings.internal_bound_by_ui ? bindings.internal_kb_id : '') || externalDraft !== (bindings.external_bound_by_ui ? bindings.external_kb_id : ''))
const sameSelection = internalDraft !== '' && internalDraft === externalDraft
const save = async () => {
setSaving(true); setError(null); setMessage('')
try {
const next = await saveRoutingBindings({ internal_kb_id: internalDraft, external_kb_id: externalDraft })
setBindings(next)
setMessage(`绑定已生效:对内 ${next.internal_kb_name || next.internal_kb_id.slice(0, 8) || '未绑定'} · 对外 ${next.external_kb_name || next.external_kb_id.slice(0, 8) || '未绑定'}。此后“来源与目录”的标记按新绑定路由。`)
} catch (cause) { setError(cause instanceof Error ? cause.message : '保存知识库绑定失败') }
finally { setSaving(false) }
}
const optionLabel = (base: KnowledgeBaseOption) => `${base.name}(${base.knowledge_count} 文档 · ${base.id.slice(0, 8)}…)`
const renderSide = (label: string, boundID: string, boundName: string, fromEnv: boolean, boundByUI: boolean) => (
<div className={`kb-binding-side ${boundID ? 'bound' : 'warn'}`}>
<b>{label}</b>
<span>{boundID ? (boundName || `${boundID.slice(0, 8)}…`) : '未绑定 · 该方向的标记会被拒绝'}</span>
<small>{boundID ? (boundByUI ? (boundName ? `UI 绑定 · ${boundID.slice(0, 8)}…` : 'UI 绑定') : fromEnv ? '来自部署默认值(env)' : '') : '请绑定一个测试知识库'}</small>
</div>
)
const editorFor = (value: string, onChange: (next: string) => void, placeholder: string) => (
options.length > 0
? <select value={value} onChange={(event) => onChange(event.target.value)} aria-label={placeholder}>
<option value="">{placeholder}</option>
{options.map((base) => <option key={base.id} value={base.id}>{optionLabel(base)}</option>)}
</select>
: <input value={value} onChange={(event) => onChange(event.target.value.trim())} placeholder={`${placeholder}(输入知识库 ID)`} aria-label={placeholder} />
)
return <section className="settings-panel wide" id="settings-routing-bindings">
<div className="settings-section-heading"><div><h2>知识库绑定</h2><p>“来源与目录”里的对内 / 对外标记按这里的绑定分发到对应 WeKnora 知识库;保存后立即生效,无需重启。</p></div><button onClick={() => void load()} disabled={loading}>{loading ? '读取中…' : '重新读取'}</button></div>
{error ? <p className="error-message" role="alert">{error}</p> : null}
{bindings ? <div className="kb-binding-grid">
{renderSide('对内知识库', bindings.internal_kb_id, bindings.internal_kb_name, bindings.internal_env_fallback, bindings.internal_bound_by_ui)}
{renderSide('对外知识库', bindings.external_kb_id, bindings.external_kb_name, bindings.external_env_fallback, bindings.external_bound_by_ui)}
</div> : null}
{bindings && !bindings.weknora_connected ? <p className="hint">当前读不到 WeKnora 的库列表,只能按 ID 填写;连接恢复后可改为下拉选择。</p> : null}
{isAdmin && bindings ? <div className="kb-binding-editor">
<label>对内绑定 {editorFor(internalDraft, setInternalDraft, '选择对内知识库')}</label>
<label>对外绑定 {editorFor(externalDraft, setExternalDraft, '选择对外知识库')}</label>
<p className="hint">留空 = 取消 UI 绑定,回退到部署默认值;对内与对外必须是不同的库。</p>
{sameSelection ? <p className="error-message">对内与对外必须绑定不同的知识库</p> : null}
<button onClick={() => void save()} disabled={saving || !dirty || sameSelection}>{saving ? '正在校验并保存…' : '保存绑定'}</button>
{message ? <p className="success-message" role="status">{message}</p> : null}
</div> : null}
{!isAdmin ? <p className="hint">仅管理员可修改知识库绑定。</p> : null}
</section>
}
+2
View File
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useState } from 'react'
import { MembersSection } from './MembersSection'
import { RoutingBindingsSection } from './RoutingBindingsSection'
import { useOptionalAuth } from './auth'
import { fetchMonitorOverview } from './monitor'
import type { MonitorOverview } from './monitor'
@@ -171,6 +172,7 @@ export function SystemSettingsView({ sources, connections, monitor, settings, pr
<div className="settings-section-heading"><div><h2>服务配置</h2><p>测试、生产必须独立配置端点、凭据引用和知识库 ID;凭据只写不读。</p></div></div>
<div className="environment-cards"><article><b>测试 WeKnora</b><span>本地真实连接</span><small>端点 / 凭据 / 知识库 ID:管理员受限配置,页面上不可回读</small></article><article className="production"><b>生产 WeKnora</b><span>未连接</span><small>生产写入:关闭;凭据不可回读</small></article></div>
<div className="mapping-row"><span>测试知识库映射</span><b>对内解析队列:{routingCapabilities.internal_enabled ? '已配置' : '未配置'}</b><b>对外解析队列:{routingCapabilities.external_enabled ? '已配置' : '未配置'}</b><b>生产映射:未配置</b></div>
<RoutingBindingsSection />
<div className="dependency-grid">{['PostgreSQL', 'MinerU', 'Embedding', 'LLM API', 'Redis / MQ', 'OSS'].map((name) => { const health = (monitor.health || []).find((item) => item.name === name || item.name.startsWith(name)); const service = monitor.services.find((item) => item.name === name || item.name.startsWith(name)); const liveLabel = !health ? (service ? (service.state === 'healthy' ? '正常' : service.state === 'unknown' ? '未接入' : '需关注') : '待配置') : health.readiness === 'ready' ? '可达 · 可接单' : health.readiness === 'not_configured' ? '状态未知 · 未配置' : health.readiness === 'not_applicable' ? '未部署' : (health.liveness === 'up' ? '可达 · 不可接单' : '不可达 · 不可接单'); return <article key={name} className={health && health.readiness !== 'ready' && health.readiness !== 'not_applicable' ? 'warn' : ''}><span>{name}</span><b>{liveLabel}</b><small>{health ? [health.reason, health.last_success_at ? `最近成功 ${new Date(health.last_success_at).toLocaleTimeString('zh-CN', { hour12: false })}` : '', health.consecutive_failures ? `连续失败${health.consecutive_failures}次` : ''].filter(Boolean).join(';') || (health.readiness === 'ready' ? `延迟 ${health.latency_ms}ms` : '') : service?.detail || '真实 Provider 未接入'}</small></article> })}</div>
</section> : null}
{section === 'storage' ? <section className="settings-panel wide storage-settings-panel" id="settings-storage">
+37
View File
@@ -0,0 +1,37 @@
import { describe, expect, it, vi } from 'vitest'
import { fetchRoutingBindingOptions, fetchRoutingBindings, saveRoutingBindings } from './routingBindings'
const binding = {
internal_kb_id: '1b52c140-2e18-4676-afc5-4c7d8d190a8c', external_kb_id: 'fd7db6aa-763a-46f1-84d2-ecc7c952a5ea',
internal_env_fallback: true, external_env_fallback: false, internal_bound_by_ui: false, external_bound_by_ui: true,
internal_kb_name: '', external_kb_name: 'governance-external-local', updated_by: 'yao', weknora_connected: true,
}
describe('routing bindings API', () => {
it('reads the active binding projection', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { ...binding, secret: 'drop' } }), { status: 200 })))
const result = await fetchRoutingBindings()
expect(result.internal_env_fallback).toBe(true)
expect(result.external_bound_by_ui).toBe(true)
expect(result).not.toHaveProperty('secret')
vi.unstubAllGlobals()
})
it('lists knowledge base options for the picker', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: [{ id: 'kb-1', name: '对内', knowledge_count: 4 }, { id: '', name: '坏行' }] }), { status: 200 })))
expect(await fetchRoutingBindingOptions()).toEqual([{ id: 'kb-1', name: '对内', knowledge_count: 4 }])
vi.unstubAllGlobals()
})
it('saves bindings with an idempotency key and surfaces the server reason', async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(new Response(JSON.stringify({ data: binding }), { status: 200 }))
.mockResolvedValueOnce(new Response(JSON.stringify({ error: '对内与对外必须绑定不同的知识库' }), { status: 400 }))
vi.stubGlobal('fetch', fetchMock)
await expect(saveRoutingBindings({ internal_kb_id: 'kb-1', external_kb_id: '' })).resolves.toMatchObject({ internal_bound_by_ui: false })
const [, init] = fetchMock.mock.calls[0]
expect(init.method).toBe('PUT')
expect(init.headers['Idempotency-Key']).toBeTruthy()
await expect(saveRoutingBindings({ internal_kb_id: 'kb-1', external_kb_id: 'kb-1' })).rejects.toThrow('对内与对外必须绑定不同的知识库')
vi.unstubAllGlobals()
})
})
+73
View File
@@ -0,0 +1,73 @@
import { newOperationID } from './operationKey'
export interface RoutingBindings {
internal_kb_id: string
external_kb_id: string
internal_env_fallback: boolean
external_env_fallback: boolean
internal_bound_by_ui: boolean
external_bound_by_ui: boolean
internal_kb_name: string
external_kb_name: string
updated_by: string
weknora_connected: boolean
}
export interface KnowledgeBaseOption {
id: string
name: string
knowledge_count: number
}
const record = (value: unknown): value is Record<string, unknown> => Boolean(value) && typeof value === 'object' && !Array.isArray(value)
function bindingProjection(item: Record<string, unknown>): RoutingBindings {
return {
internal_kb_id: typeof item.internal_kb_id === 'string' ? item.internal_kb_id : '',
external_kb_id: typeof item.external_kb_id === 'string' ? item.external_kb_id : '',
internal_env_fallback: item.internal_env_fallback === true,
external_env_fallback: item.external_env_fallback === true,
internal_bound_by_ui: item.internal_bound_by_ui === true,
external_bound_by_ui: item.external_bound_by_ui === true,
internal_kb_name: typeof item.internal_kb_name === 'string' ? item.internal_kb_name : '',
external_kb_name: typeof item.external_kb_name === 'string' ? item.external_kb_name : '',
updated_by: typeof item.updated_by === 'string' ? item.updated_by : '',
weknora_connected: item.weknora_connected === true,
}
}
export async function fetchRoutingBindings(signal?: AbortSignal): Promise<RoutingBindings> {
const response = await fetch('/api/v1/routing-bindings', { signal, headers: { Accept: 'application/json' } })
if (!response.ok) throw new Error(`读取知识库绑定失败(HTTP ${response.status})`)
const value = await response.json() as unknown
if (!record(value) || !record(value.data)) throw new Error('知识库绑定响应无效')
return bindingProjection(value.data)
}
export async function fetchRoutingBindingOptions(signal?: AbortSignal): Promise<KnowledgeBaseOption[]> {
const response = await fetch('/api/v1/routing-bindings/options', { signal, headers: { Accept: 'application/json' } })
if (!response.ok) throw new Error(`读取可绑定知识库失败(HTTP ${response.status})`)
const value = await response.json() as unknown
if (!record(value) || !Array.isArray(value.data)) throw new Error('知识库列表响应无效')
return value.data.filter(record).map((item) => ({
id: typeof item.id === 'string' ? item.id : '',
name: typeof item.name === 'string' ? item.name : '',
knowledge_count: typeof item.knowledge_count === 'number' ? item.knowledge_count : 0,
})).filter((item) => item.id)
}
export async function saveRoutingBindings(input: { internal_kb_id: string; external_kb_id: string }, signal?: AbortSignal): Promise<RoutingBindings> {
const response = await fetch('/api/v1/routing-bindings', {
method: 'PUT', signal,
headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'Idempotency-Key': newOperationID() },
body: JSON.stringify(input),
})
if (!response.ok) {
let reason = `保存知识库绑定失败(HTTP ${response.status})`
try { const body = await response.json() as unknown; if (record(body) && typeof body.error === 'string') reason = body.error } catch { /* keep status text */ }
throw new Error(reason)
}
const value = await response.json() as unknown
if (!record(value) || !record(value.data)) throw new Error('知识库绑定响应无效')
return bindingProjection(value.data)
}
+1
View File
@@ -26,3 +26,4 @@ button.link{background:none;border:none;color:var(--c-run);cursor:pointer;text-d
.modal-card p{color:var(--ink-base);font-size:14px;line-height:1.6}
.modal-actions{display:flex;gap:10px;justify-content:flex-end;margin-top:14px}
@media (max-width:900px){.settings-layout{grid-template-columns:1fr}.settings-nav{position:static;flex-direction:row;flex-wrap:wrap}}
.kb-binding-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin:12px 0}.kb-binding-side{display:grid;gap:4px;border:1px solid var(--border-base);border-radius:9px;padding:11px;background:var(--bg-soft)}.kb-binding-side.bound{border-color:var(--c-done)}.kb-binding-side.warn{border-color:var(--c-fail)}.kb-binding-side b{color:var(--ink-base);font-size:11px}.kb-binding-side span{color:var(--c-done);font-size:11px;word-break:break-all}.kb-binding-side.warn span{color:var(--c-fail)}.kb-binding-side small{color:var(--ink-mute);font-size:9px}.kb-binding-editor{display:grid;gap:10px;border-top:1px dashed var(--border-base);margin-top:8px;padding-top:12px}.kb-binding-editor label{display:grid;gap:6px;color:var(--ink-mute);font-size:10px}.kb-binding-editor select,.kb-binding-editor input{border:1px solid var(--border-strong);border-radius:7px;padding:8px;background:var(--bg-panel);color:var(--ink-base)}.kb-binding-editor button{justify-self:start;padding:7px 10px}@media(max-width:650px){.kb-binding-grid{grid-template-columns:1fr}}.hint{color:var(--ink-mute);font-size:10px;margin:4px 0}