diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.go index 5e605c3e..377f805f 100644 --- a/internal/application/service/agent_service.go +++ b/internal/application/service/agent_service.go @@ -55,31 +55,23 @@ func agentHasKnowledgeScope(config *types.AgentConfig) bool { ) } -// knowledgeBaseIDsForPrompt returns KB IDs to show in runtime_context metadata. -// Prefer explicit KnowledgeBases; fall back to deduped IDs from SearchTargets. -func knowledgeBaseIDsForPrompt(config *types.AgentConfig) []string { +// knowledgeBaseScopesForPrompt returns the KB IDs to show in runtime_context +// metadata, together with the tenant each KB should be queried under. +// +// The tenant map always comes from SearchTargets, which buildSearchTargets has +// already resolved (and authorized) per KB: a directly shared KB carries its +// source tenant there. KnowledgeBases alone cannot tell own from shared KBs — +// both KBSelectionMode="all" and an @mention put shared KB IDs into it. +// KBs missing from the map fall back to the caller's tenant. +func knowledgeBaseScopesForPrompt(config *types.AgentConfig) ([]string, map[string]uint64) { if config == nil { - return nil + return nil, nil } + kbTenantMap := config.SearchTargets.GetKBTenantMap() if len(config.KnowledgeBases) > 0 { - return config.KnowledgeBases + return config.KnowledgeBases, kbTenantMap } - if len(config.SearchTargets) == 0 { - return nil - } - seen := make(map[string]struct{}, len(config.SearchTargets)) - out := make([]string, 0, len(config.SearchTargets)) - for _, target := range config.SearchTargets { - if target == nil || target.KnowledgeBaseID == "" { - continue - } - if _, ok := seen[target.KnowledgeBaseID]; ok { - continue - } - seen[target.KnowledgeBaseID] = struct{}{} - out = append(out, target.KnowledgeBaseID) - } - return out + return config.SearchTargets.GetAllKnowledgeBaseIDs(), kbTenantMap } // agentService implements agent-related business logic @@ -322,8 +314,8 @@ func (s *agentService) resolveKBAndDocInfos( ctx context.Context, config *types.AgentConfig, ) ([]*agent.KnowledgeBaseInfo, []*agent.SelectedDocumentInfo) { - kbIDs := knowledgeBaseIDsForPrompt(config) - kbInfos, err := s.getKnowledgeBaseInfos(ctx, kbIDs) + kbIDs, kbTenantMap := knowledgeBaseScopesForPrompt(config) + kbInfos, err := s.getKnowledgeBaseInfos(ctx, kbIDs, kbTenantMap) if err != nil { logger.Warnf(ctx, "Failed to get knowledge base details, using IDs only: %v", err) kbInfos = make([]*agent.KnowledgeBaseInfo, 0, len(kbIDs)) @@ -735,8 +727,10 @@ func (s *agentService) ValidateConfig(config *types.AgentConfig) error { return nil } -// getKnowledgeBaseInfos retrieves detailed information for knowledge bases -func (s *agentService) getKnowledgeBaseInfos(ctx context.Context, kbIDs []string) ([]*agent.KnowledgeBaseInfo, error) { +// getKnowledgeBaseInfos retrieves detailed information for knowledge bases. +// kbTenantMap carries the tenant each KB should be queried under (source tenant +// for directly shared KBs); a missing entry falls back to the request tenant. +func (s *agentService) getKnowledgeBaseInfos(ctx context.Context, kbIDs []string, kbTenantMap map[string]uint64) ([]*agent.KnowledgeBaseInfo, error) { if len(kbIDs) == 0 { return []*agent.KnowledgeBaseInfo{}, nil } @@ -765,12 +759,22 @@ func (s *agentService) getKnowledgeBaseInfos(ctx context.Context, kbIDs []string continue } + // Document/FAQ listing below is tenant-scoped, so a directly shared KB + // must be queried under its source tenant — the request context belongs + // to the receiving tenant and would silently yield doc_count=0. The + // tenant comes from the SearchTarget that buildSearchTargets already + // authorized; this only widens the metadata query, never the KB set. + metaCtx := ctx + if scopeTenantID := kbTenantMap[kbID]; scopeTenantID != 0 { + metaCtx = context.WithValue(ctx, types.TenantIDContextKey, scopeTenantID) + } + // Get document count and recent documents docCount := 0 recentDocs := []agent.RecentDocInfo{} if kb.Type == types.KnowledgeBaseTypeFAQ { - pageResult, err := s.knowledgeService.ListFAQEntries(ctx, kbID, &types.Pagination{ + pageResult, err := s.knowledgeService.ListFAQEntries(metaCtx, kbID, &types.Pagination{ Page: 1, PageSize: 10, }, nil, 0, "", "", "") @@ -801,7 +805,7 @@ func (s *agentService) getKnowledgeBaseInfos(ctx context.Context, kbIDs []string // Fallback to generic knowledge listing when not FAQ or FAQ retrieval failed if kb.Type != types.KnowledgeBaseTypeFAQ || len(recentDocs) == 0 { - pageResult, err := s.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbID, &types.Pagination{ + pageResult, err := s.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(metaCtx, kbID, &types.Pagination{ Page: 1, PageSize: 10, }, types.KnowledgeListFilter{ diff --git a/internal/application/service/agent_service_scope_test.go b/internal/application/service/agent_service_scope_test.go index 6a61b52f..85731d76 100644 --- a/internal/application/service/agent_service_scope_test.go +++ b/internal/application/service/agent_service_scope_test.go @@ -25,7 +25,7 @@ func TestAgentHasKnowledgeScope_Empty(t *testing.T) { assert.False(t, agentHasKnowledgeScope(nil)) } -func TestKnowledgeBaseIDsForPrompt_FromSearchTargets(t *testing.T) { +func TestKnowledgeBaseScopesForPrompt_FromSearchTargets(t *testing.T) { cfg := &types.AgentConfig{ SearchTargets: types.SearchTargets{ {KnowledgeBaseID: "kb-1", TagIDs: []string{"tag-a"}}, @@ -33,5 +33,40 @@ func TestKnowledgeBaseIDsForPrompt_FromSearchTargets(t *testing.T) { {KnowledgeBaseID: "kb-2", TagIDs: []string{"tag-c"}}, }, } - assert.Equal(t, []string{"kb-1", "kb-2"}, knowledgeBaseIDsForPrompt(cfg)) + ids, _ := knowledgeBaseScopesForPrompt(cfg) + assert.Equal(t, []string{"kb-1", "kb-2"}, ids) +} + +func TestKnowledgeBaseScopesForPrompt_CarriesSharedKBSourceTenant(t *testing.T) { + cfg := &types.AgentConfig{ + SearchTargets: types.SearchTargets{ + {KnowledgeBaseID: "shared-kb", TenantID: 42}, + {KnowledgeBaseID: "own-kb", TenantID: 0}, + }, + } + ids, tenantMap := knowledgeBaseScopesForPrompt(cfg) + assert.Equal(t, []string{"shared-kb", "own-kb"}, ids) + assert.Equal(t, uint64(42), tenantMap["shared-kb"]) + assert.Zero(t, tenantMap["own-kb"]) +} + +// KnowledgeBases carries shared KB IDs too (KBSelectionMode="all" and @mentions +// both write into it), so the source tenant must still come from SearchTargets. +func TestKnowledgeBaseScopesForPrompt_ExplicitKnowledgeBasesKeepSourceTenant(t *testing.T) { + cfg := &types.AgentConfig{ + KnowledgeBases: []string{"own-kb", "shared-kb"}, + SearchTargets: types.SearchTargets{ + {KnowledgeBaseID: "own-kb", TenantID: 7}, + {KnowledgeBaseID: "shared-kb", TenantID: 42}, + }, + } + ids, tenantMap := knowledgeBaseScopesForPrompt(cfg) + assert.Equal(t, []string{"own-kb", "shared-kb"}, ids) + assert.Equal(t, uint64(42), tenantMap["shared-kb"]) +} + +func TestKnowledgeBaseScopesForPrompt_NilConfig(t *testing.T) { + ids, tenantMap := knowledgeBaseScopesForPrompt(nil) + assert.Nil(t, ids) + assert.Empty(t, tenantMap) } diff --git a/internal/application/service/agent_service_test.go b/internal/application/service/agent_service_test.go index d74600ec..52ed5085 100644 --- a/internal/application/service/agent_service_test.go +++ b/internal/application/service/agent_service_test.go @@ -28,15 +28,17 @@ type fakeAgentKnowledgeService struct { interfaces.KnowledgeService knowledges []*types.Knowledge lastFilter types.KnowledgeListFilter + lastTenant uint64 } func (s *fakeAgentKnowledgeService) ListPagedKnowledgeByKnowledgeBaseID( - _ context.Context, + ctx context.Context, _ string, page *types.Pagination, filter types.KnowledgeListFilter, ) (*types.PageResult, error) { s.lastFilter = filter + s.lastTenant, _ = types.TenantIDFromContext(ctx) filtered := make([]*types.Knowledge, 0, len(s.knowledges)) for _, knowledge := range s.knowledges { @@ -48,6 +50,46 @@ func (s *fakeAgentKnowledgeService) ListPagedKnowledgeByKnowledgeBaseID( return types.NewPageResult(int64(len(filtered)), page, filtered), nil } +func TestGetKnowledgeBaseInfos_SharedKnowledgeBaseUsesSourceTenant(t *testing.T) { + const ( + receiverTenantID = uint64(7) + sourceTenantID = uint64(42) + ) + now := time.Now() + knowledgeService := &fakeAgentKnowledgeService{ + knowledges: []*types.Knowledge{ + { + ID: "shared-doc", + KnowledgeBaseID: "shared-kb", + Title: "shared document", + ParseStatus: types.ParseStatusCompleted, + CreatedAt: now, + }, + }, + } + service := &agentService{ + knowledgeBaseService: &fakeAgentKnowledgeBaseService{ + kb: &types.KnowledgeBase{ + ID: "shared-kb", + Name: "Shared KB", + Type: types.KnowledgeBaseTypeDocument, + TenantID: sourceTenantID, + }, + }, + knowledgeService: knowledgeService, + } + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, receiverTenantID) + + infos, err := service.getKnowledgeBaseInfos(ctx, []string{"shared-kb"}, map[string]uint64{"shared-kb": sourceTenantID}) + + require.NoError(t, err) + require.Len(t, infos, 1) + assert.Equal(t, 1, infos[0].DocCount) + require.Len(t, infos[0].RecentDocs, 1) + assert.Equal(t, "shared-doc", infos[0].RecentDocs[0].KnowledgeID) + assert.Equal(t, sourceTenantID, knowledgeService.lastTenant) +} + func TestGetKnowledgeBaseInfos_ExcludesUnprocessedDocuments(t *testing.T) { now := time.Now() knowledgeService := &fakeAgentKnowledgeService{ @@ -84,7 +126,7 @@ func TestGetKnowledgeBaseInfos_ExcludesUnprocessedDocuments(t *testing.T) { knowledgeService: knowledgeService, } - infos, err := service.getKnowledgeBaseInfos(context.Background(), []string{"kb-1"}) + infos, err := service.getKnowledgeBaseInfos(context.Background(), []string{"kb-1"}, nil) require.NoError(t, err) require.Len(t, infos, 1)