2026-05-18 01:10:01 +00:00
|
|
|
package service
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
stderrors "errors"
|
|
|
|
|
"testing"
|
2026-05-18 09:56:06 +00:00
|
|
|
"time"
|
2026-05-18 01:10:01 +00:00
|
|
|
|
2026-09-08 07:36:33 +00:00
|
|
|
"github.com/Tencent/WeKnora/internal/application/access"
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/application/repository"
|
2026-05-18 01:10:01 +00:00
|
|
|
"github.com/Tencent/WeKnora/internal/application/service/retriever"
|
|
|
|
|
apperrors "github.com/Tencent/WeKnora/internal/errors"
|
2026-07-15 02:57:32 +00:00
|
|
|
"github.com/Tencent/WeKnora/internal/storageallowlist"
|
2026-05-18 01:10:01 +00:00
|
|
|
"github.com/Tencent/WeKnora/internal/types"
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
|
"github.com/stretchr/testify/require"
|
|
|
|
|
"gorm.io/gorm"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
// Vector-store binding service-level tests
|
|
|
|
|
//
|
|
|
|
|
// Coverage:
|
|
|
|
|
// - CreateKnowledgeBase: vector_store_id validation matrix (Normalize,
|
|
|
|
|
// malformed UUID, sentinel wrap, error code distinction).
|
|
|
|
|
// - CopyKnowledgeBase: embedding-model + store defenses, new-KB
|
|
|
|
|
// VectorStoreID copy.
|
|
|
|
|
//
|
|
|
|
|
// These are pure logic tests that drive `validateVectorStoreBinding` and
|
|
|
|
|
// `CopyKnowledgeBase` through stubbed dependencies — no DB I/O.
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
// validKBStoreUUID is a well-formed UUID used to drive the validation
|
|
|
|
|
// branches that survive the uuid.Parse() pre-flight.
|
|
|
|
|
const validKBStoreUUID = "0193b8a0-1111-7000-8000-000000000001"
|
|
|
|
|
|
|
|
|
|
type fakeOwnership struct {
|
|
|
|
|
owned map[string]uint64 // storeID -> tenantID owner
|
|
|
|
|
err error
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (f *fakeOwnership) StoreOwnedBy(_ context.Context, storeID string, tenantID uint64) (bool, error) {
|
|
|
|
|
if f.err != nil {
|
|
|
|
|
return false, f.err
|
|
|
|
|
}
|
|
|
|
|
owner, ok := f.owned[storeID]
|
|
|
|
|
return ok && owner == tenantID, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type fakeRegistry struct {
|
|
|
|
|
registered map[string]struct{}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (f *fakeRegistry) Register(_ interfaces.RetrieveEngineService) error { return nil }
|
|
|
|
|
func (f *fakeRegistry) GetRetrieveEngineService(_ types.RetrieverEngineType) (interfaces.RetrieveEngineService, error) {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
|
|
|
|
func (f *fakeRegistry) GetAllRetrieveEngineServices() []interfaces.RetrieveEngineService { return nil }
|
|
|
|
|
func (f *fakeRegistry) GetByStoreID(storeID string) (interfaces.RetrieveEngineService, error) {
|
|
|
|
|
if _, ok := f.registered[storeID]; ok {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
|
|
|
|
return nil, stderrors.New("not registered")
|
|
|
|
|
}
|
|
|
|
|
|
fix(retriever): rebuild a missing vector store engine on demand
The engine registry is per-process, so a store's engine is missing
whenever this process did not create it. That happens three ways:
- Startup skips a store whose engine fails to construct and never
retries it, so that instance cannot serve the store again -- not
even after a restart, if the backend is slow to come up.
- A store registered on one instance is absent on every other until
they restart, because registration is not broadcast.
- Registration can fail on the instance handling the create, leaving
the store missing even there.
Each one surfaces as "vector store is currently unavailable" and is
cleared today only by restarting the process.
Add GetOrLoadByStoreID, which falls back to building the engine from the
store row when the lookup misses, and route the two bound-store lookups
through it. The method goes on RetrieveEngineRegistry rather than
StoreRegistry because that is the interface the factory functions
receive; the two declare GetByStoreID separately and neither embeds the
other.
Concurrent callers collapse onto one build. That build runs on a context
detached from the caller that started it: callers share the result, so
letting the first one's cancellation abort it would fail everyone else
waiting. A panic inside the build is contained, because singleflight
re-raises it on a goroutine the HTTP recovery middleware cannot reach
and the build calls third-party client constructors.
Publishing is guarded by a per-store generation sampled before the
build, so an engine that finishes after the entry was registered or
removed by someone else does not overwrite it and leave that engine
orphaned with its connections open. A failed build starts a cooldown:
collapsing only helps concurrent callers, so without it a backend that
stays down would cost a full build timeout on every sequential request.
Separate "the store is gone" from "its engine cannot be built right
now". Async delete handlers answer ErrVectorStoreNotFound with
asynq.SkipRetry, so reporting a database blip or a backend outage that
way would permanently discard knowledge-base and index delete tasks and
orphan the vector data they exist to remove. ErrVectorStoreUnavailable
covers the retryable cases; the repository already distinguishes them,
returning (nil, nil) for a missing row and an error for a failure.
For the same reason a caller's own cancellation is never folded into a
store sentinel. The ownership check runs first and queries the database
with that context, so on a shutdown it is usually where cancellation is
noticed.
A search resolves one engine per distinct store, sequentially, and this
server sets no HTTP read or write timeout, so the resolution loop gets a
budget above a single build. An exhausted budget still leaves the
engines warming, since the build is detached, and is reported as an
unavailable store because retrying is likely to succeed.
Build failures are logged where they happen, with the panic stack. The
cause cannot travel back to the caller -- factory errors embed endpoints
and credentials -- so without this the one thing an operator needs when
self-healing fails to heal would be discarded with the error.
Note a deliberate contract change: an ownership lookup failure used to
be reported as not-found, and a test asserted that on purpose. A
database failure says nothing about whether the store exists, and
treating it as permanent is what discards the task, so that assertion is
inverted rather than preserved.
2026-07-27 11:25:46 +00:00
|
|
|
// This fake never rebuilds a missing engine, so a miss stays a miss.
|
|
|
|
|
func (f *fakeRegistry) GetOrLoadByStoreID(
|
|
|
|
|
_ context.Context, _ uint64, storeID string,
|
|
|
|
|
) (interfaces.RetrieveEngineService, error) {
|
|
|
|
|
return f.GetByStoreID(storeID)
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-18 01:10:01 +00:00
|
|
|
// fakeKBRepo is the smallest KnowledgeBaseRepository needed by
|
|
|
|
|
// CreateKnowledgeBase + CopyKnowledgeBase tests. It stores rows in a map
|
|
|
|
|
// keyed by ID. No tenant scoping is applied — the tested paths already
|
|
|
|
|
// enforce that explicitly.
|
|
|
|
|
type fakeKBRepo struct {
|
|
|
|
|
rows map[string]*types.KnowledgeBase
|
|
|
|
|
createErr error
|
|
|
|
|
}
|
|
|
|
|
|
feat(knowledge): derive knowledge base descriptions from document profiles (#3370)
* feat(knowledge): derive knowledge base descriptions from document profiles
Knowledge bases only had a hand-written description, which most users
leave empty, so agents bound to several knowledge bases had nothing to
route on and searched all of them. This adds a generated description
that is derived from per-document data instead of maintained by a model.
Document profile: the summary call now returns JSON with a 2-3 sentence
summary plus a gist, 3-5 topic keywords, a document type and one
typical question (knowledges.profile). Input is capped at 8k chars and
output at 1024 tokens; plain-text replies from custom templates still
work and simply carry no profile. The summary chunk embeds the gist and
short summary.
Knowledge base aggregate: a database-only fold over those rows (counts
per file type, tag, normalized topic and doc type; stratified samples of
titles and questions; a hash of the inputs). Deleting, moving or
re-parsing a document changes nothing but the rows, so the next rebuild
is exact without any model judgement.
Description text: one small model call over the aggregate yields a
gist, merged topics and typical questions (knowledge_bases.
generated_profile). The call is skipped when the aggregate hash is
unchanged; failures keep the previous text and record the error; an
empty knowledge base clears it. The manual description is never
touched, and the agent runtime context renders both so the model can
pass knowledge_base_ids instead of fanning out.
Refreshes are requested from summary task exit, post-process completion,
deletion, cross-KB moves and enabling the option, debounced per
knowledge base in 30 s windows via kb:profile on the summary queue.
POST /knowledge-bases/:id/profile/generate regenerates synchronously.
profile_config (enabled, model_id, custom_instructions) opts a document
knowledge base in; the settings dialog shows the generated card with
regenerate and adopt-as-description actions in five locales. Search
results now log hits per chunk type so the value of indexing summary
chunks can be measured.
Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the
SQLite schema test expects the new version and columns.
* fix(knowledge): keep generated descriptions out of duplicates and refresh clones
DuplicateKnowledgeBase copies the source row through JSON, which carried
generated_profile onto a knowledge base that has no documents yet, so
an empty duplicate advertised the source's topics. The duplicate now
starts without a generated description and keeps profile_config so it
derives its own once documents arrive.
CopyKnowledgeBase builds the target field by field and skipped
profile_config, and the clone task never asked for a description after
copying the documents, so a clone stayed undescribed until its next
upload. The target now carries a copy of profile_config and both clone
paths request a refresh on completion.
* fix(knowledge): refresh the loaded clone target and carry document profiles
ProcessKBClone requested the description refresh with the reservation
stub it builds before CopyKnowledgeBase runs. For the main create path
that stub has neither a type nor profile_config, so the refresh helper
rejected it and nothing was enqueued. The refresh now uses the loaded
target returned by CopyKnowledgeBase.
cloneKnowledge copied the summary text but not the structured profile,
so even a scheduled refresh would have aggregated titles without topics
until every clone was re-summarized. Cloned documents now carry an
independent copy of the profile.
2026-09-17 14:21:55 +00:00
|
|
|
func (r *fakeKBRepo) UpdateKnowledgeBaseGeneratedProfile(
|
|
|
|
|
_ context.Context, id string, profile *types.KnowledgeBaseProfile,
|
|
|
|
|
) error {
|
|
|
|
|
if kb, ok := r.rows[id]; ok {
|
|
|
|
|
kb.GeneratedProfile = profile
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-18 01:10:01 +00:00
|
|
|
func newFakeKBRepo() *fakeKBRepo { return &fakeKBRepo{rows: map[string]*types.KnowledgeBase{}} }
|
|
|
|
|
|
|
|
|
|
func (r *fakeKBRepo) CreateKnowledgeBase(_ context.Context, kb *types.KnowledgeBase) error {
|
|
|
|
|
if r.createErr != nil {
|
|
|
|
|
return r.createErr
|
|
|
|
|
}
|
|
|
|
|
r.rows[kb.ID] = kb
|
|
|
|
|
return nil
|
|
|
|
|
}
|
2026-09-08 07:36:33 +00:00
|
|
|
|
2026-05-18 01:10:01 +00:00
|
|
|
func (r *fakeKBRepo) GetKnowledgeBaseByID(_ context.Context, id string) (*types.KnowledgeBase, error) {
|
|
|
|
|
return r.rows[id], nil
|
|
|
|
|
}
|
2026-09-08 07:36:33 +00:00
|
|
|
|
2026-05-18 01:10:01 +00:00
|
|
|
func (r *fakeKBRepo) GetKnowledgeBaseByIDAndTenant(_ context.Context, id string, tenantID uint64) (*types.KnowledgeBase, error) {
|
|
|
|
|
kb := r.rows[id]
|
|
|
|
|
if kb == nil || kb.TenantID != tenantID {
|
2026-09-08 07:36:33 +00:00
|
|
|
return nil, repository.ErrKnowledgeBaseNotFound
|
2026-05-18 01:10:01 +00:00
|
|
|
}
|
|
|
|
|
return kb, nil
|
|
|
|
|
}
|
2026-09-08 07:36:33 +00:00
|
|
|
|
2026-05-18 01:10:01 +00:00
|
|
|
func (r *fakeKBRepo) GetKnowledgeBaseByIDs(_ context.Context, _ []string) ([]*types.KnowledgeBase, error) {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
2026-09-08 07:36:33 +00:00
|
|
|
|
2026-05-18 01:10:01 +00:00
|
|
|
func (r *fakeKBRepo) ListKnowledgeBases(_ context.Context) ([]*types.KnowledgeBase, error) {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
2026-09-08 07:36:33 +00:00
|
|
|
|
2026-07-08 12:43:12 +00:00
|
|
|
func (r *fakeKBRepo) ListKnowledgeBasesByTenantID(_ context.Context, tenantID uint64) ([]*types.KnowledgeBase, error) {
|
|
|
|
|
rows := make([]*types.KnowledgeBase, 0, len(r.rows))
|
|
|
|
|
for _, kb := range r.rows {
|
|
|
|
|
if kb != nil && kb.TenantID == tenantID {
|
|
|
|
|
rows = append(rows, kb)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return rows, nil
|
2026-05-18 01:10:01 +00:00
|
|
|
}
|
2026-09-08 07:36:33 +00:00
|
|
|
|
2026-05-18 01:10:01 +00:00
|
|
|
func (r *fakeKBRepo) UpdateKnowledgeBase(_ context.Context, _ *types.KnowledgeBase) error {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
func (r *fakeKBRepo) DeleteKnowledgeBase(_ context.Context, _ string) error { return nil }
|
|
|
|
|
func (r *fakeKBRepo) TogglePinKnowledgeBase(_ context.Context, _ string, _ uint64) (*types.KnowledgeBase, error) {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
2026-09-08 07:36:33 +00:00
|
|
|
|
2026-05-18 01:10:01 +00:00
|
|
|
func (r *fakeKBRepo) CountByVectorStoreID(_ context.Context, _ *gorm.DB, _ uint64, _ string) (int64, error) {
|
|
|
|
|
return 0, nil
|
|
|
|
|
}
|
2026-09-08 07:36:33 +00:00
|
|
|
|
2026-06-23 12:33:01 +00:00
|
|
|
func (r *fakeKBRepo) CountByModelID(_ context.Context, _ uint64, _ string) (int64, error) {
|
|
|
|
|
return 0, nil
|
|
|
|
|
}
|
2026-09-02 09:20:37 +00:00
|
|
|
|
|
|
|
|
func (r *fakeKBRepo) ListModelUsages(_ context.Context, _ uint64, _ string) ([]types.ModelUsageResource, error) {
|
|
|
|
|
return []types.ModelUsageResource{}, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-18 09:56:06 +00:00
|
|
|
func (r *fakeKBRepo) SetUserKBPin(_ context.Context, _ uint64, _ string, _ string, _ bool) (*time.Time, error) {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
2026-09-02 09:20:37 +00:00
|
|
|
|
2026-05-18 09:56:06 +00:00
|
|
|
func (r *fakeKBRepo) ListUserKBPinIDs(_ context.Context, _ uint64, _ string) (map[string]time.Time, error) {
|
|
|
|
|
return map[string]time.Time{}, nil
|
|
|
|
|
}
|
2026-05-18 01:10:01 +00:00
|
|
|
|
|
|
|
|
// Force compile-time conformance check so any future interface change
|
|
|
|
|
// surfaces as a build error here rather than at usage site.
|
|
|
|
|
var _ interfaces.KnowledgeBaseRepository = (*fakeKBRepo)(nil)
|
|
|
|
|
|
|
|
|
|
func newPR3KBService(repo *fakeKBRepo, registry *fakeRegistry, ownership *fakeOwnership) *knowledgeBaseService {
|
|
|
|
|
return &knowledgeBaseService{
|
|
|
|
|
repo: repo,
|
|
|
|
|
retrieveEngine: registry,
|
|
|
|
|
ownership: ownership,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func ctxWithTenant(tenantID uint64) context.Context {
|
|
|
|
|
return context.WithValue(context.Background(), types.TenantIDContextKey, tenantID)
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-29 05:36:06 +00:00
|
|
|
func ctxWithTenantStorage(tenantID uint64, defaultProvider string) context.Context {
|
|
|
|
|
ctx := ctxWithTenant(tenantID)
|
|
|
|
|
tenant := &types.Tenant{
|
|
|
|
|
ID: tenantID,
|
|
|
|
|
StorageEngineConfig: &types.StorageEngineConfig{
|
|
|
|
|
DefaultProvider: defaultProvider,
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
return context.WithValue(ctx, types.TenantInfoContextKey, tenant)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestCreateKnowledgeBase_DefaultStorageProviderFromTenant(t *testing.T) {
|
|
|
|
|
repo := newFakeKBRepo()
|
|
|
|
|
svc := newPR3KBService(repo, &fakeRegistry{registered: map[string]struct{}{}}, &fakeOwnership{})
|
|
|
|
|
|
|
|
|
|
kb, err := svc.CreateKnowledgeBase(ctxWithTenantStorage(1, "minio"), &types.KnowledgeBase{Name: "kb"})
|
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
assert.Equal(t, "minio", kb.GetStorageProvider())
|
|
|
|
|
|
|
|
|
|
kbExplicit, err := svc.CreateKnowledgeBase(ctxWithTenantStorage(1, "minio"), &types.KnowledgeBase{
|
|
|
|
|
Name: "kb2",
|
|
|
|
|
StorageProviderConfig: &types.StorageProviderConfig{Provider: "cos"},
|
|
|
|
|
})
|
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
assert.Equal(t, "cos", kbExplicit.GetStorageProvider())
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-15 02:57:32 +00:00
|
|
|
func TestCreateKnowledgeBase_DefaultStorageProviderRespectsAllowList(t *testing.T) {
|
|
|
|
|
t.Setenv(storageallowlist.AllowListEnv, "minio")
|
|
|
|
|
repo := newFakeKBRepo()
|
|
|
|
|
svc := newPR3KBService(repo, &fakeRegistry{registered: map[string]struct{}{}}, &fakeOwnership{})
|
|
|
|
|
|
|
|
|
|
kb, err := svc.CreateKnowledgeBase(ctxWithTenantStorage(1, ""), &types.KnowledgeBase{Name: "kb"})
|
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
assert.Equal(t, "minio", kb.GetStorageProvider())
|
|
|
|
|
|
|
|
|
|
kbDisallowedDefault, err := svc.CreateKnowledgeBase(ctxWithTenantStorage(1, "local"), &types.KnowledgeBase{Name: "kb2"})
|
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
assert.Equal(t, "minio", kbDisallowedDefault.GetStorageProvider())
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-18 01:10:01 +00:00
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
// CreateKnowledgeBase — vector_store_id binding validation matrix
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
func TestCreateKnowledgeBase_VectorStoreBinding(t *testing.T) {
|
|
|
|
|
registered := map[string]struct{}{validKBStoreUUID: {}}
|
|
|
|
|
|
|
|
|
|
t.Run("nil vector_store_id persists unchanged", func(t *testing.T) {
|
|
|
|
|
repo := newFakeKBRepo()
|
|
|
|
|
svc := newPR3KBService(repo,
|
|
|
|
|
&fakeRegistry{registered: registered},
|
|
|
|
|
&fakeOwnership{owned: map[string]uint64{validKBStoreUUID: 1}},
|
|
|
|
|
)
|
|
|
|
|
kb, err := svc.CreateKnowledgeBase(ctxWithTenant(1), &types.KnowledgeBase{Name: "kb"})
|
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
assert.Nil(t, kb.VectorStoreID)
|
|
|
|
|
assert.Len(t, repo.rows, 1)
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
t.Run("empty string vector_store_id normalizes to nil", func(t *testing.T) {
|
|
|
|
|
repo := newFakeKBRepo()
|
|
|
|
|
svc := newPR3KBService(repo,
|
|
|
|
|
&fakeRegistry{registered: registered},
|
|
|
|
|
&fakeOwnership{},
|
|
|
|
|
)
|
|
|
|
|
empty := ""
|
|
|
|
|
kb, err := svc.CreateKnowledgeBase(ctxWithTenant(1), &types.KnowledgeBase{Name: "kb", VectorStoreID: &empty})
|
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
assert.Nil(t, kb.VectorStoreID)
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
t.Run("malformed UUID rejected with BindingInvalid code", func(t *testing.T) {
|
|
|
|
|
repo := newFakeKBRepo()
|
|
|
|
|
svc := newPR3KBService(repo,
|
|
|
|
|
&fakeRegistry{registered: registered},
|
|
|
|
|
&fakeOwnership{},
|
|
|
|
|
)
|
|
|
|
|
bad := "not-a-uuid"
|
|
|
|
|
_, err := svc.CreateKnowledgeBase(ctxWithTenant(1), &types.KnowledgeBase{Name: "kb", VectorStoreID: &bad})
|
|
|
|
|
require.Error(t, err)
|
|
|
|
|
appErr, ok := apperrors.IsAppError(err)
|
|
|
|
|
require.True(t, ok)
|
|
|
|
|
assert.Equal(t, apperrors.ErrVectorStoreBindingInvalid, appErr.Code)
|
|
|
|
|
assert.NotContains(t, appErr.Message, bad, "UUID must not echo back")
|
|
|
|
|
assert.Empty(t, repo.rows, "must not persist on validation failure")
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
t.Run("valid UUID + owned + registered → persist OK", func(t *testing.T) {
|
|
|
|
|
repo := newFakeKBRepo()
|
|
|
|
|
svc := newPR3KBService(repo,
|
|
|
|
|
&fakeRegistry{registered: registered},
|
|
|
|
|
&fakeOwnership{owned: map[string]uint64{validKBStoreUUID: 1}},
|
|
|
|
|
)
|
|
|
|
|
id := validKBStoreUUID
|
|
|
|
|
kb, err := svc.CreateKnowledgeBase(ctxWithTenant(1), &types.KnowledgeBase{Name: "kb", VectorStoreID: &id})
|
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
require.NotNil(t, kb.VectorStoreID)
|
|
|
|
|
assert.Equal(t, validKBStoreUUID, *kb.VectorStoreID)
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
t.Run("valid UUID + cross-tenant → BindingInvalid", func(t *testing.T) {
|
|
|
|
|
repo := newFakeKBRepo()
|
|
|
|
|
svc := newPR3KBService(repo,
|
|
|
|
|
&fakeRegistry{registered: registered},
|
|
|
|
|
&fakeOwnership{owned: map[string]uint64{validKBStoreUUID: 2}}, // owned by tenant 2
|
|
|
|
|
)
|
|
|
|
|
id := validKBStoreUUID
|
|
|
|
|
_, err := svc.CreateKnowledgeBase(ctxWithTenant(1), &types.KnowledgeBase{Name: "kb", VectorStoreID: &id})
|
|
|
|
|
require.Error(t, err)
|
|
|
|
|
appErr, ok := apperrors.IsAppError(err)
|
|
|
|
|
require.True(t, ok)
|
|
|
|
|
assert.Equal(t, apperrors.ErrVectorStoreBindingInvalid, appErr.Code)
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
t.Run("valid UUID + owned but unregistered → Unavailable", func(t *testing.T) {
|
|
|
|
|
repo := newFakeKBRepo()
|
|
|
|
|
svc := newPR3KBService(repo,
|
|
|
|
|
&fakeRegistry{registered: map[string]struct{}{}}, // not registered
|
|
|
|
|
&fakeOwnership{owned: map[string]uint64{validKBStoreUUID: 1}},
|
|
|
|
|
)
|
|
|
|
|
id := validKBStoreUUID
|
|
|
|
|
_, err := svc.CreateKnowledgeBase(ctxWithTenant(1), &types.KnowledgeBase{Name: "kb", VectorStoreID: &id})
|
|
|
|
|
require.Error(t, err)
|
|
|
|
|
appErr, ok := apperrors.IsAppError(err)
|
|
|
|
|
require.True(t, ok)
|
|
|
|
|
assert.Equal(t, apperrors.ErrVectorStoreUnavailable, appErr.Code)
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
t.Run("ownership infra error → 500", func(t *testing.T) {
|
|
|
|
|
repo := newFakeKBRepo()
|
|
|
|
|
svc := newPR3KBService(repo,
|
|
|
|
|
&fakeRegistry{registered: registered},
|
|
|
|
|
&fakeOwnership{err: stderrors.New("db down")},
|
|
|
|
|
)
|
|
|
|
|
id := validKBStoreUUID
|
|
|
|
|
_, err := svc.CreateKnowledgeBase(ctxWithTenant(1), &types.KnowledgeBase{Name: "kb", VectorStoreID: &id})
|
|
|
|
|
require.Error(t, err)
|
|
|
|
|
appErr, ok := apperrors.IsAppError(err)
|
|
|
|
|
require.True(t, ok)
|
|
|
|
|
assert.Equal(t, 500, appErr.HTTPCode)
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
// Compile-time check: the retriever sentinels still match what we expect
|
|
|
|
|
// in the wrapper logic. If they are ever renamed or removed, this fails
|
|
|
|
|
// at build time rather than silently degrading the wrap.
|
|
|
|
|
_ = retriever.ErrVectorStoreForbidden
|
|
|
|
|
_ = retriever.ErrVectorStoreNotFound
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
// CopyKnowledgeBase — embedding model + vector store defenses
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
feat(knowledge): derive knowledge base descriptions from document profiles (#3370)
* feat(knowledge): derive knowledge base descriptions from document profiles
Knowledge bases only had a hand-written description, which most users
leave empty, so agents bound to several knowledge bases had nothing to
route on and searched all of them. This adds a generated description
that is derived from per-document data instead of maintained by a model.
Document profile: the summary call now returns JSON with a 2-3 sentence
summary plus a gist, 3-5 topic keywords, a document type and one
typical question (knowledges.profile). Input is capped at 8k chars and
output at 1024 tokens; plain-text replies from custom templates still
work and simply carry no profile. The summary chunk embeds the gist and
short summary.
Knowledge base aggregate: a database-only fold over those rows (counts
per file type, tag, normalized topic and doc type; stratified samples of
titles and questions; a hash of the inputs). Deleting, moving or
re-parsing a document changes nothing but the rows, so the next rebuild
is exact without any model judgement.
Description text: one small model call over the aggregate yields a
gist, merged topics and typical questions (knowledge_bases.
generated_profile). The call is skipped when the aggregate hash is
unchanged; failures keep the previous text and record the error; an
empty knowledge base clears it. The manual description is never
touched, and the agent runtime context renders both so the model can
pass knowledge_base_ids instead of fanning out.
Refreshes are requested from summary task exit, post-process completion,
deletion, cross-KB moves and enabling the option, debounced per
knowledge base in 30 s windows via kb:profile on the summary queue.
POST /knowledge-bases/:id/profile/generate regenerates synchronously.
profile_config (enabled, model_id, custom_instructions) opts a document
knowledge base in; the settings dialog shows the generated card with
regenerate and adopt-as-description actions in five locales. Search
results now log hits per chunk type so the value of indexing summary
chunks can be measured.
Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the
SQLite schema test expects the new version and columns.
* fix(knowledge): keep generated descriptions out of duplicates and refresh clones
DuplicateKnowledgeBase copies the source row through JSON, which carried
generated_profile onto a knowledge base that has no documents yet, so
an empty duplicate advertised the source's topics. The duplicate now
starts without a generated description and keeps profile_config so it
derives its own once documents arrive.
CopyKnowledgeBase builds the target field by field and skipped
profile_config, and the clone task never asked for a description after
copying the documents, so a clone stayed undescribed until its next
upload. The target now carries a copy of profile_config and both clone
paths request a refresh on completion.
* fix(knowledge): refresh the loaded clone target and carry document profiles
ProcessKBClone requested the description refresh with the reservation
stub it builds before CopyKnowledgeBase runs. For the main create path
that stub has neither a type nor profile_config, so the refresh helper
rejected it and nothing was enqueued. The refresh now uses the loaded
target returned by CopyKnowledgeBase.
cloneKnowledge copied the summary text but not the structured profile,
so even a scheduled refresh would have aggregated titles without topics
until every clone was re-summarized. Cloned documents now carry an
independent copy of the profile.
2026-09-17 14:21:55 +00:00
|
|
|
func TestCopyKnowledgeBase_CarriesProfileConfigButNotGeneratedProfile(t *testing.T) {
|
|
|
|
|
repo := newFakeKBRepo()
|
|
|
|
|
repo.rows["src"] = &types.KnowledgeBase{
|
|
|
|
|
ID: "src", Name: "src", TenantID: 1, EmbeddingModelID: "embed-1",
|
|
|
|
|
ProfileConfig: &types.KnowledgeBaseProfileConfig{
|
|
|
|
|
Enabled: true, ModelID: "m", CustomInstructions: "audience",
|
|
|
|
|
},
|
|
|
|
|
GeneratedProfile: &types.KnowledgeBaseProfile{
|
|
|
|
|
Gist: "source gist", Status: types.KnowledgeBaseProfileStatusReady,
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
|
|
|
|
|
|
|
|
|
|
_, tgt, err := svc.CopyKnowledgeBase(copyTaskTestContext(t, repo, ""), "src", "")
|
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
require.NotNil(t, tgt.ProfileConfig)
|
|
|
|
|
assert.Equal(t, *repo.rows["src"].ProfileConfig, *tgt.ProfileConfig)
|
|
|
|
|
assert.NotSame(t, repo.rows["src"].ProfileConfig, tgt.ProfileConfig, "config is copied, not shared")
|
|
|
|
|
assert.Nil(t, tgt.GeneratedProfile, "the clone derives its own description after its documents land")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestDuplicateKnowledgeBase_DropsGeneratedProfile(t *testing.T) {
|
|
|
|
|
repo := newFakeKBRepo()
|
|
|
|
|
repo.rows["src"] = &types.KnowledgeBase{
|
|
|
|
|
ID: "src", Name: "src", TenantID: 1, EmbeddingModelID: "embed-1",
|
|
|
|
|
Type: types.KnowledgeBaseTypeDocument,
|
|
|
|
|
ProfileConfig: &types.KnowledgeBaseProfileConfig{Enabled: true},
|
|
|
|
|
GeneratedProfile: &types.KnowledgeBaseProfile{
|
|
|
|
|
Gist: "source gist", Status: types.KnowledgeBaseProfileStatusReady,
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
|
|
|
|
|
|
|
|
|
|
dup, err := svc.DuplicateKnowledgeBase(ctxWithTenant(1), "src")
|
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
assert.Nil(t, dup.GeneratedProfile, "an empty duplicate must not advertise the source's documents")
|
|
|
|
|
require.NotNil(t, dup.ProfileConfig)
|
|
|
|
|
assert.True(t, dup.ProfileConfig.Enabled)
|
|
|
|
|
assert.Nil(t, repo.rows[dup.ID].GeneratedProfile)
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-18 01:10:01 +00:00
|
|
|
func TestCopyKnowledgeBase_Defenses(t *testing.T) {
|
|
|
|
|
mkKB := func(id string, tenant uint64, embed string, vsid *string) *types.KnowledgeBase {
|
|
|
|
|
return &types.KnowledgeBase{
|
|
|
|
|
ID: id, Name: id, TenantID: tenant, EmbeddingModelID: embed, VectorStoreID: vsid,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
storeA := "store-A"
|
|
|
|
|
storeB := "store-B"
|
|
|
|
|
|
|
|
|
|
t.Run("dstKB empty -> new KB inherits VectorStoreID", func(t *testing.T) {
|
|
|
|
|
repo := newFakeKBRepo()
|
|
|
|
|
repo.rows["src"] = mkKB("src", 1, "embed-1", &storeA)
|
|
|
|
|
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
|
|
|
|
|
|
2026-09-08 07:36:33 +00:00
|
|
|
src, tgt, err := svc.CopyKnowledgeBase(copyTaskTestContext(t, repo, ""), "src", "")
|
2026-05-18 01:10:01 +00:00
|
|
|
require.NoError(t, err)
|
|
|
|
|
require.NotNil(t, src.VectorStoreID)
|
|
|
|
|
require.NotNil(t, tgt.VectorStoreID)
|
|
|
|
|
assert.Equal(t, *src.VectorStoreID, *tgt.VectorStoreID, "M17: VectorStoreID preserved")
|
|
|
|
|
|
|
|
|
|
// Reload from fake repo and re-verify
|
|
|
|
|
stored := repo.rows[tgt.ID]
|
|
|
|
|
require.NotNil(t, stored)
|
|
|
|
|
require.NotNil(t, stored.VectorStoreID)
|
|
|
|
|
assert.Equal(t, storeA, *stored.VectorStoreID)
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
t.Run("dstKB empty + source nil VectorStoreID -> new target nil too", func(t *testing.T) {
|
|
|
|
|
repo := newFakeKBRepo()
|
|
|
|
|
repo.rows["src"] = mkKB("src", 1, "embed-1", nil)
|
|
|
|
|
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
|
|
|
|
|
|
2026-09-08 07:36:33 +00:00
|
|
|
_, tgt, err := svc.CopyKnowledgeBase(copyTaskTestContext(t, repo, ""), "src", "")
|
2026-05-18 01:10:01 +00:00
|
|
|
require.NoError(t, err)
|
|
|
|
|
assert.Nil(t, tgt.VectorStoreID)
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
t.Run("dstKB set + same embedding model + both nil stores -> OK", func(t *testing.T) {
|
|
|
|
|
repo := newFakeKBRepo()
|
|
|
|
|
repo.rows["src"] = mkKB("src", 1, "embed-1", nil)
|
|
|
|
|
repo.rows["dst"] = mkKB("dst", 1, "embed-1", nil)
|
|
|
|
|
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
|
|
|
|
|
|
2026-09-08 07:36:33 +00:00
|
|
|
_, _, err := svc.CopyKnowledgeBase(copyTaskTestContext(t, repo, "dst"), "src", "dst")
|
2026-05-18 01:10:01 +00:00
|
|
|
require.NoError(t, err)
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
t.Run("dstKB set + same store UUID -> OK", func(t *testing.T) {
|
|
|
|
|
repo := newFakeKBRepo()
|
|
|
|
|
repo.rows["src"] = mkKB("src", 1, "embed-1", &storeA)
|
|
|
|
|
repo.rows["dst"] = mkKB("dst", 1, "embed-1", &storeA)
|
|
|
|
|
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
|
|
|
|
|
|
2026-09-08 07:36:33 +00:00
|
|
|
_, _, err := svc.CopyKnowledgeBase(copyTaskTestContext(t, repo, "dst"), "src", "dst")
|
2026-05-18 01:10:01 +00:00
|
|
|
require.NoError(t, err)
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
t.Run("dstKB set + different embedding models -> 400", func(t *testing.T) {
|
|
|
|
|
repo := newFakeKBRepo()
|
|
|
|
|
repo.rows["src"] = mkKB("src", 1, "embed-1", &storeA)
|
|
|
|
|
repo.rows["dst"] = mkKB("dst", 1, "embed-2", &storeA)
|
|
|
|
|
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
|
|
|
|
|
|
2026-09-08 07:36:33 +00:00
|
|
|
_, _, err := svc.CopyKnowledgeBase(copyTaskTestContext(t, repo, "dst"), "src", "dst")
|
2026-05-18 01:10:01 +00:00
|
|
|
require.Error(t, err)
|
|
|
|
|
assert.Contains(t, err.Error(), "different embedding models")
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
t.Run("dstKB set + different stores -> 400 (no Phase number)", func(t *testing.T) {
|
|
|
|
|
repo := newFakeKBRepo()
|
|
|
|
|
repo.rows["src"] = mkKB("src", 1, "embed-1", &storeA)
|
|
|
|
|
repo.rows["dst"] = mkKB("dst", 1, "embed-1", &storeB)
|
|
|
|
|
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
|
|
|
|
|
|
2026-09-08 07:36:33 +00:00
|
|
|
_, _, err := svc.CopyKnowledgeBase(copyTaskTestContext(t, repo, "dst"), "src", "dst")
|
2026-05-18 01:10:01 +00:00
|
|
|
require.Error(t, err)
|
|
|
|
|
assert.Contains(t, err.Error(), "different vector stores")
|
|
|
|
|
assert.NotContains(t, err.Error(), "Phase 4", "internal roadmap labels must not leak to end-user error messages")
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
t.Run("dstKB set + one nil + one set -> 400", func(t *testing.T) {
|
|
|
|
|
repo := newFakeKBRepo()
|
|
|
|
|
repo.rows["src"] = mkKB("src", 1, "embed-1", nil)
|
|
|
|
|
repo.rows["dst"] = mkKB("dst", 1, "embed-1", &storeA)
|
|
|
|
|
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
|
|
|
|
|
|
2026-09-08 07:36:33 +00:00
|
|
|
_, _, err := svc.CopyKnowledgeBase(copyTaskTestContext(t, repo, "dst"), "src", "dst")
|
2026-05-18 01:10:01 +00:00
|
|
|
require.Error(t, err)
|
|
|
|
|
assert.Contains(t, err.Error(), "different vector stores")
|
|
|
|
|
})
|
|
|
|
|
}
|
2026-07-08 12:43:12 +00:00
|
|
|
|
|
|
|
|
func TestDuplicateKnowledgeBase_CreatesSettingsOnlyDuplicate(t *testing.T) {
|
|
|
|
|
repo := newFakeKBRepo()
|
|
|
|
|
source := &types.KnowledgeBase{
|
|
|
|
|
ID: "src",
|
|
|
|
|
Name: "Source KB",
|
|
|
|
|
Type: types.KnowledgeBaseTypeDocument,
|
|
|
|
|
Description: "source description",
|
|
|
|
|
TenantID: 1,
|
|
|
|
|
CreatorID: "source-owner",
|
|
|
|
|
IsTemporary: true,
|
|
|
|
|
ChunkingConfig: types.ChunkingConfig{
|
|
|
|
|
ChunkSize: 800,
|
|
|
|
|
ChunkOverlap: 80,
|
|
|
|
|
Separators: []string{"\n\n", "."},
|
|
|
|
|
ParserEngineRules: []types.ParserEngineRule{{
|
|
|
|
|
FileTypes: []string{"pdf"},
|
|
|
|
|
Engine: "docreader",
|
|
|
|
|
}},
|
|
|
|
|
},
|
|
|
|
|
ImageProcessingConfig: types.ImageProcessingConfig{ModelID: "vlm-image"},
|
|
|
|
|
EmbeddingModelID: "embed-1",
|
|
|
|
|
SummaryModelID: "summary-1",
|
|
|
|
|
VLMConfig: types.VLMConfig{Enabled: true, ModelID: "vlm-1"},
|
|
|
|
|
ASRConfig: types.ASRConfig{Enabled: true, ModelID: "asr-1", Language: "zh"},
|
|
|
|
|
StorageProviderConfig: &types.StorageProviderConfig{Provider: "local"},
|
|
|
|
|
ExtractConfig: &types.ExtractConfig{
|
|
|
|
|
Enabled: true,
|
|
|
|
|
Text: "extract entities",
|
|
|
|
|
Tags: []string{"product"},
|
|
|
|
|
Nodes: []*types.GraphNode{{Name: "Product"}},
|
|
|
|
|
},
|
|
|
|
|
QuestionGenerationConfig: &types.QuestionGenerationConfig{Enabled: true, QuestionCount: 5},
|
|
|
|
|
WikiConfig: &types.WikiConfig{SynthesisModelID: "wiki-llm", MaxPagesPerIngest: 12},
|
|
|
|
|
IndexingStrategy: types.IndexingStrategy{
|
|
|
|
|
VectorEnabled: true,
|
|
|
|
|
KeywordEnabled: true,
|
|
|
|
|
WikiEnabled: true,
|
|
|
|
|
GraphEnabled: true,
|
|
|
|
|
},
|
|
|
|
|
IsPinned: true,
|
|
|
|
|
KnowledgeCount: 9,
|
|
|
|
|
ChunkCount: 27,
|
|
|
|
|
IsProcessing: true,
|
|
|
|
|
ProcessingCount: 2,
|
|
|
|
|
ShareCount: 3,
|
|
|
|
|
CreatorName: "Source Owner",
|
|
|
|
|
}
|
|
|
|
|
repo.rows["src"] = source
|
|
|
|
|
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
|
|
|
|
|
ctx := context.WithValue(ctxWithTenant(1), types.UserIDContextKey, "copy-user")
|
|
|
|
|
|
2026-07-08 12:53:59 +00:00
|
|
|
target, err := svc.DuplicateKnowledgeBase(ctx, "src")
|
2026-07-08 12:43:12 +00:00
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
2026-07-08 12:53:59 +00:00
|
|
|
require.NotEmpty(t, target.ID)
|
2026-07-08 12:43:12 +00:00
|
|
|
assert.Equal(t, uint64(1), target.TenantID)
|
|
|
|
|
assert.Equal(t, "copy-user", target.CreatorID)
|
|
|
|
|
assert.Equal(t, "Source KB 副本", target.Name)
|
|
|
|
|
assert.Equal(t, source.Description, target.Description)
|
|
|
|
|
assert.Equal(t, source.ChunkingConfig, target.ChunkingConfig)
|
|
|
|
|
assert.Equal(t, source.ImageProcessingConfig, target.ImageProcessingConfig)
|
|
|
|
|
assert.Equal(t, source.EmbeddingModelID, target.EmbeddingModelID)
|
|
|
|
|
assert.Equal(t, source.SummaryModelID, target.SummaryModelID)
|
|
|
|
|
assert.Equal(t, source.VLMConfig, target.VLMConfig)
|
|
|
|
|
assert.Equal(t, source.ASRConfig, target.ASRConfig)
|
|
|
|
|
require.NotNil(t, target.StorageProviderConfig)
|
|
|
|
|
assert.Equal(t, "local", target.StorageProviderConfig.Provider)
|
|
|
|
|
require.NotNil(t, target.ExtractConfig)
|
|
|
|
|
assert.Equal(t, source.ExtractConfig.Text, target.ExtractConfig.Text)
|
|
|
|
|
require.NotNil(t, target.QuestionGenerationConfig)
|
|
|
|
|
assert.Equal(t, 5, target.QuestionGenerationConfig.QuestionCount)
|
|
|
|
|
require.NotNil(t, target.WikiConfig)
|
|
|
|
|
assert.Equal(t, "wiki-llm", target.WikiConfig.SynthesisModelID)
|
|
|
|
|
assert.Equal(t, source.IndexingStrategy, target.IndexingStrategy)
|
|
|
|
|
|
|
|
|
|
assert.False(t, target.IsTemporary)
|
|
|
|
|
assert.False(t, target.IsPinned)
|
|
|
|
|
assert.Nil(t, target.PinnedAt)
|
|
|
|
|
assert.Zero(t, target.KnowledgeCount)
|
|
|
|
|
assert.Zero(t, target.ChunkCount)
|
|
|
|
|
assert.False(t, target.IsProcessing)
|
|
|
|
|
assert.Zero(t, target.ProcessingCount)
|
|
|
|
|
assert.Zero(t, target.ShareCount)
|
|
|
|
|
assert.Empty(t, target.CreatorName)
|
2026-07-08 12:53:59 +00:00
|
|
|
require.Same(t, target, repo.rows[target.ID])
|
2026-07-08 12:43:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestDuplicateKnowledgeBase_UsesDistinctNameWhenDuplicateExists(t *testing.T) {
|
|
|
|
|
repo := newFakeKBRepo()
|
|
|
|
|
repo.rows["src"] = &types.KnowledgeBase{
|
|
|
|
|
ID: "src",
|
|
|
|
|
Name: "Source KB",
|
|
|
|
|
Type: types.KnowledgeBaseTypeDocument,
|
|
|
|
|
TenantID: 1,
|
|
|
|
|
}
|
|
|
|
|
repo.rows["existing-copy"] = &types.KnowledgeBase{
|
|
|
|
|
ID: "existing-copy",
|
|
|
|
|
Name: "Source KB 副本",
|
|
|
|
|
Type: types.KnowledgeBaseTypeDocument,
|
|
|
|
|
TenantID: 1,
|
|
|
|
|
}
|
|
|
|
|
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
|
|
|
|
|
|
2026-07-08 12:53:59 +00:00
|
|
|
target, err := svc.DuplicateKnowledgeBase(ctxWithTenant(1), "src")
|
2026-07-08 12:43:12 +00:00
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
|
|
assert.Equal(t, "Source KB 副本 2", target.Name)
|
|
|
|
|
}
|
2026-07-08 12:53:59 +00:00
|
|
|
|
|
|
|
|
func TestDuplicateKnowledgeBase_UsesLocalizedEnglishSuffix(t *testing.T) {
|
|
|
|
|
repo := newFakeKBRepo()
|
|
|
|
|
repo.rows["src"] = &types.KnowledgeBase{
|
|
|
|
|
ID: "src",
|
|
|
|
|
Name: "Source KB",
|
|
|
|
|
Type: types.KnowledgeBaseTypeDocument,
|
|
|
|
|
TenantID: 1,
|
|
|
|
|
}
|
|
|
|
|
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
|
|
|
|
|
ctx := context.WithValue(ctxWithTenant(1), types.LanguageContextKey, "en-US")
|
|
|
|
|
|
|
|
|
|
target, err := svc.DuplicateKnowledgeBase(ctx, "src")
|
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
|
|
assert.Equal(t, "Source KB Copy", target.Name)
|
|
|
|
|
}
|
2026-09-08 07:36:33 +00:00
|
|
|
|
|
|
|
|
func copyTaskTestContext(t *testing.T, repo *fakeKBRepo, dst string) context.Context {
|
|
|
|
|
t.Helper()
|
|
|
|
|
target := repo.rows[dst]
|
|
|
|
|
if target == nil {
|
|
|
|
|
target = &types.KnowledgeBase{ID: "reserved-copy", TenantID: 1}
|
|
|
|
|
}
|
|
|
|
|
ctx, err := access.WithKBTransferTask(
|
|
|
|
|
context.Background(),
|
|
|
|
|
repo.rows["src"],
|
|
|
|
|
target,
|
|
|
|
|
1,
|
|
|
|
|
access.KBTransferClone,
|
|
|
|
|
"clone-task",
|
|
|
|
|
dst == "",
|
|
|
|
|
)
|
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
return ctx
|
|
|
|
|
}
|