feat(agent): enhance agent sharing and selection features

- Updated the AgentSelector component to improve agent selection logic, ensuring accurate representation of selected agents.
- Introduced new AgentShareSettings component for managing agent sharing with organizations, including UI for selecting organizations and displaying shared agents.
- Enhanced API interactions for sharing agents, including new methods for listing and managing agent shares.
- Improved localization support for agent sharing features across multiple languages.
- Updated various components to reflect changes in agent capabilities and sharing status, enhancing user experience and clarity.

This update strengthens the agent management features, providing users with better tools for sharing and selecting agents within organizations.
This commit is contained in:
wizardchen
2026-02-04 20:12:29 +08:00
committed by lyingbug
parent faa4e9e7b5
commit dfaf862bc0
45 changed files with 3606 additions and 477 deletions
@@ -0,0 +1,156 @@
package repository
import (
"context"
"errors"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
)
var (
ErrAgentShareNotFound = errors.New("agent share not found")
ErrAgentShareAlreadyExists = errors.New("agent already shared to this organization")
)
// agentShareRepository implements AgentShareRepository interface
type agentShareRepository struct {
db *gorm.DB
}
// NewAgentShareRepository creates a new agent share repository
func NewAgentShareRepository(db *gorm.DB) interfaces.AgentShareRepository {
return &agentShareRepository{db: db}
}
// Create creates a new agent share record
func (r *agentShareRepository) Create(ctx context.Context, share *types.AgentShare) error {
var count int64
r.db.WithContext(ctx).Model(&types.AgentShare{}).
Where("agent_id = ? AND source_tenant_id = ? AND organization_id = ? AND deleted_at IS NULL",
share.AgentID, share.SourceTenantID, share.OrganizationID).
Count(&count)
if count > 0 {
return ErrAgentShareAlreadyExists
}
return r.db.WithContext(ctx).Create(share).Error
}
// GetByID gets a share record by ID
func (r *agentShareRepository) GetByID(ctx context.Context, id string) (*types.AgentShare, error) {
var share types.AgentShare
err := r.db.WithContext(ctx).Where("id = ?", id).First(&share).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrAgentShareNotFound
}
return nil, err
}
return &share, nil
}
// GetByAgentAndOrg gets a share record by agent ID and organization ID
func (r *agentShareRepository) GetByAgentAndOrg(ctx context.Context, agentID string, orgID string) (*types.AgentShare, error) {
var share types.AgentShare
err := r.db.WithContext(ctx).
Where("agent_id = ? AND organization_id = ?", agentID, orgID).
First(&share).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrAgentShareNotFound
}
return nil, err
}
return &share, nil
}
// Update updates a share record
func (r *agentShareRepository) Update(ctx context.Context, share *types.AgentShare) error {
return r.db.WithContext(ctx).Model(&types.AgentShare{}).
Where("id = ?", share.ID).Updates(share).Error
}
// Delete soft deletes a share record
func (r *agentShareRepository) Delete(ctx context.Context, id string) error {
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.AgentShare{}).Error
}
// DeleteByAgentIDAndSourceTenant soft deletes all share records for an agent (id, tenant_id)
func (r *agentShareRepository) DeleteByAgentIDAndSourceTenant(ctx context.Context, agentID string, sourceTenantID uint64) error {
return r.db.WithContext(ctx).
Where("agent_id = ? AND source_tenant_id = ?", agentID, sourceTenantID).
Delete(&types.AgentShare{}).Error
}
// DeleteByOrganizationID soft deletes all share records for an organization
func (r *agentShareRepository) DeleteByOrganizationID(ctx context.Context, orgID string) error {
return r.db.WithContext(ctx).Where("organization_id = ?", orgID).Delete(&types.AgentShare{}).Error
}
// ListByAgent lists all share records for an agent
func (r *agentShareRepository) ListByAgent(ctx context.Context, agentID string) ([]*types.AgentShare, error) {
var shares []*types.AgentShare
err := r.db.WithContext(ctx).
Preload("Organization").
Where("agent_id = ?", agentID).
Order("created_at DESC").
Find(&shares).Error
if err != nil {
return nil, err
}
return shares, nil
}
// ListByOrganization lists all share records for an organization (excluding deleted agents)
func (r *agentShareRepository) ListByOrganization(ctx context.Context, orgID string) ([]*types.AgentShare, error) {
var shares []*types.AgentShare
err := r.db.WithContext(ctx).
Joins("JOIN custom_agents ON custom_agents.id = agent_shares.agent_id AND custom_agents.tenant_id = agent_shares.source_tenant_id AND custom_agents.deleted_at IS NULL").
Preload("Agent").
Where("agent_shares.organization_id = ? AND agent_shares.deleted_at IS NULL", orgID).
Order("agent_shares.created_at DESC").
Find(&shares).Error
if err != nil {
return nil, err
}
return shares, nil
}
// ListSharedAgentsForUser lists all agents shared to organizations that the user belongs to
func (r *agentShareRepository) ListSharedAgentsForUser(ctx context.Context, userID string) ([]*types.AgentShare, error) {
var shares []*types.AgentShare
err := r.db.WithContext(ctx).
Joins("JOIN custom_agents ON custom_agents.id = agent_shares.agent_id AND custom_agents.tenant_id = agent_shares.source_tenant_id AND custom_agents.deleted_at IS NULL").
Preload("Agent").
Preload("Organization").
Joins("JOIN organization_members ON organization_members.organization_id = agent_shares.organization_id").
Joins("JOIN organizations ON organizations.id = agent_shares.organization_id AND organizations.deleted_at IS NULL").
Where("organization_members.user_id = ?", userID).
Where("agent_shares.deleted_at IS NULL").
Order("agent_shares.created_at DESC").
Find(&shares).Error
if err != nil {
return nil, err
}
return shares, nil
}
// GetShareByAgentIDForUser returns one share for the given agentID that the user can access (user in org), excluding source_tenant_id == excludeTenantID. Single query.
func (r *agentShareRepository) GetShareByAgentIDForUser(ctx context.Context, userID, agentID string, excludeTenantID uint64) (*types.AgentShare, error) {
var share types.AgentShare
err := r.db.WithContext(ctx).
Joins("JOIN organization_members ON organization_members.organization_id = agent_shares.organization_id").
Where("agent_shares.agent_id = ?", agentID).
Where("organization_members.user_id = ?", userID).
Where("agent_shares.source_tenant_id != ?", excludeTenantID).
Where("agent_shares.deleted_at IS NULL").
First(&share).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrAgentShareNotFound
}
return nil, err
}
return &share, nil
}
+252
View File
@@ -0,0 +1,252 @@
package service
import (
"context"
"errors"
"fmt"
"time"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
)
var (
ErrAgentShareNotFound = errors.New("agent share not found")
ErrAgentSharePermission = errors.New("permission denied for this share operation")
ErrAgentNotFoundForShare = errors.New("agent not found")
ErrNotAgentOwner = errors.New("only agent owner can share")
ErrOrgRoleCannotShareAgent = errors.New("only editors and admins can share agents to this organization")
ErrAgentNotConfigured = errors.New("agent is not fully configured (missing required chat model or rerank model when using knowledge bases)")
)
// agentShareService implements AgentShareService interface
type agentShareService struct {
shareRepo interfaces.AgentShareRepository
orgRepo interfaces.OrganizationRepository
agentRepo interfaces.CustomAgentRepository
userRepo interfaces.UserRepository
}
// NewAgentShareService creates a new agent share service
func NewAgentShareService(
shareRepo interfaces.AgentShareRepository,
orgRepo interfaces.OrganizationRepository,
agentRepo interfaces.CustomAgentRepository,
userRepo interfaces.UserRepository,
) interfaces.AgentShareService {
return &agentShareService{
shareRepo: shareRepo,
orgRepo: orgRepo,
agentRepo: agentRepo,
userRepo: userRepo,
}
}
// ShareAgent shares an agent to an organization
func (s *agentShareService) ShareAgent(ctx context.Context, agentID string, orgID string, userID string, tenantID uint64, permission types.OrgMemberRole) (*types.AgentShare, error) {
logger.Infof(ctx, "Sharing agent %s to organization %s", agentID, orgID)
agent, err := s.agentRepo.GetAgentByID(ctx, agentID, tenantID)
if err != nil || agent == nil {
return nil, ErrAgentNotFoundForShare
}
if agent.TenantID != tenantID {
return nil, ErrNotAgentOwner
}
// Require agent to be fully configured before sharing (same rules as for conversation)
if agent.Config.ModelID == "" {
return nil, ErrAgentNotConfigured
}
usesKB := agent.Config.KBSelectionMode != "none" || len(agent.Config.KnowledgeBases) > 0
if usesKB && agent.Config.RerankModelID == "" {
return nil, ErrAgentNotConfigured
}
_, err = s.orgRepo.GetByID(ctx, orgID)
if err != nil {
if errors.Is(err, repository.ErrOrganizationNotFound) {
return nil, ErrOrgNotFound
}
return nil, err
}
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
if err != nil {
if errors.Is(err, repository.ErrOrgMemberNotFound) {
return nil, ErrUserNotInOrg
}
return nil, err
}
if !member.Role.HasPermission(types.OrgRoleEditor) {
return nil, ErrOrgRoleCannotShareAgent
}
// 智能体共享仅支持只读,不支持可编辑
permission = types.OrgRoleViewer
share := &types.AgentShare{
ID: uuid.New().String(),
AgentID: agentID,
OrganizationID: orgID,
SharedByUserID: userID,
SourceTenantID: tenantID,
Permission: permission,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
if err := s.shareRepo.Create(ctx, share); err != nil {
if errors.Is(err, repository.ErrAgentShareAlreadyExists) {
existing, err := s.shareRepo.GetByAgentAndOrg(ctx, agentID, orgID)
if err != nil {
return nil, err
}
existing.Permission = types.OrgRoleViewer
existing.UpdatedAt = time.Now()
if err := s.shareRepo.Update(ctx, existing); err != nil {
return nil, err
}
return existing, nil
}
return nil, err
}
logger.Infof(ctx, "Agent %s shared successfully to organization %s", agentID, orgID)
return share, nil
}
// RemoveShare removes an agent share
func (s *agentShareService) RemoveShare(ctx context.Context, shareID string, userID string) error {
share, err := s.shareRepo.GetByID(ctx, shareID)
if err != nil {
if errors.Is(err, repository.ErrAgentShareNotFound) {
return ErrAgentShareNotFound
}
return err
}
if share.SharedByUserID == userID {
return s.shareRepo.Delete(ctx, shareID)
}
member, err := s.orgRepo.GetMember(ctx, share.OrganizationID, userID)
if err == nil && member.Role == types.OrgRoleAdmin {
return s.shareRepo.Delete(ctx, shareID)
}
return ErrAgentSharePermission
}
// ListSharesByAgent lists all shares for an agent
func (s *agentShareService) ListSharesByAgent(ctx context.Context, agentID string) ([]*types.AgentShare, error) {
return s.shareRepo.ListByAgent(ctx, agentID)
}
// ListSharesByOrganization lists all agent shares for an organization
func (s *agentShareService) ListSharesByOrganization(ctx context.Context, orgID string) ([]*types.AgentShare, error) {
return s.shareRepo.ListByOrganization(ctx, orgID)
}
// ListSharedAgents lists agents shared to the user through organizations, deduplicated by agent ID (keep highest permission)
func (s *agentShareService) ListSharedAgents(ctx context.Context, userID string, currentTenantID uint64) ([]*types.SharedAgentInfo, error) {
shares, err := s.shareRepo.ListSharedAgentsForUser(ctx, userID)
if err != nil {
return nil, err
}
agentInfoMap := make(map[string]*types.SharedAgentInfo)
for _, share := range shares {
if share.SourceTenantID == currentTenantID {
continue
}
if share.Agent == nil {
continue
}
member, err := s.orgRepo.GetMember(ctx, share.OrganizationID, userID)
if err != nil {
continue
}
effectivePermission := share.Permission
if !member.Role.HasPermission(share.Permission) {
effectivePermission = member.Role
}
info := &types.SharedAgentInfo{
Agent: share.Agent,
ShareID: share.ID,
OrganizationID: share.OrganizationID,
OrgName: "",
Permission: effectivePermission,
SourceTenantID: share.SourceTenantID,
SharedAt: share.CreatedAt,
SharedByUserID: share.SharedByUserID,
}
if share.Organization != nil {
info.OrgName = share.Organization.Name
}
if share.SharedByUserID != "" {
if u, err := s.userRepo.GetUserByID(ctx, share.SharedByUserID); err == nil && u != nil {
info.SharedByUsername = u.Username
}
}
key := fmt.Sprintf("%s_%d", share.AgentID, share.SourceTenantID)
existing, exists := agentInfoMap[key]
if !exists {
agentInfoMap[key] = info
} else if effectivePermission.HasPermission(existing.Permission) && effectivePermission != existing.Permission {
agentInfoMap[key] = info
}
}
result := make([]*types.SharedAgentInfo, 0, len(agentInfoMap))
for _, info := range agentInfoMap {
result = append(result, info)
}
return result, nil
}
// GetSharedAgentForUser returns the shared agent by agentID if the user has access; source tenant is resolved from the user's share. One share lookup + one agent lookup.
func (s *agentShareService) GetSharedAgentForUser(ctx context.Context, userID string, currentTenantID uint64, agentID string) (*types.CustomAgent, error) {
if agentID == "" {
return nil, ErrAgentShareNotFound
}
share, err := s.shareRepo.GetShareByAgentIDForUser(ctx, userID, agentID, currentTenantID)
if err != nil {
if errors.Is(err, repository.ErrAgentShareNotFound) {
return nil, ErrAgentSharePermission
}
return nil, err
}
agent, err := s.agentRepo.GetAgentByID(ctx, agentID, share.SourceTenantID)
if err != nil {
if errors.Is(err, repository.ErrCustomAgentNotFound) {
return nil, ErrAgentNotFoundForShare
}
return nil, err
}
return agent, nil
}
// GetShare gets an agent share by ID
func (s *agentShareService) GetShare(ctx context.Context, shareID string) (*types.AgentShare, error) {
share, err := s.shareRepo.GetByID(ctx, shareID)
if err != nil {
if errors.Is(err, repository.ErrAgentShareNotFound) {
return nil, ErrAgentShareNotFound
}
return nil, err
}
return share, nil
}
// GetShareByAgentAndOrg gets an agent share by agent ID and organization ID
func (s *agentShareService) GetShareByAgentAndOrg(ctx context.Context, agentID string, orgID string) (*types.AgentShare, error) {
share, err := s.shareRepo.GetByAgentAndOrg(ctx, agentID, orgID)
if err != nil {
if errors.Is(err, repository.ErrAgentShareNotFound) {
return nil, ErrAgentShareNotFound
}
return nil, err
}
return share, nil
}
@@ -124,6 +124,22 @@ func (s *customAgentService) GetAgentByID(ctx context.Context, id string) (*type
return agent, nil
}
// GetAgentByIDAndTenant retrieves an agent by ID and tenant (for shared agents; does not resolve built-in)
func (s *customAgentService) GetAgentByIDAndTenant(ctx context.Context, id string, tenantID uint64) (*types.CustomAgent, error) {
if id == "" {
logger.Error(ctx, "Agent ID is empty")
return nil, errors.New("agent ID cannot be empty")
}
agent, err := s.repo.GetAgentByID(ctx, id, tenantID)
if err != nil {
if errors.Is(err, repository.ErrCustomAgentNotFound) {
return nil, ErrAgentNotFound
}
return nil, err
}
return agent, nil
}
// ListAgents lists all agents for the current tenant (including built-in agents)
func (s *customAgentService) ListAgents(ctx context.Context) ([]*types.CustomAgent, error) {
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
@@ -7585,6 +7585,14 @@ func (s *knowledgeService) SearchKnowledge(ctx context.Context, keyword string,
return s.repo.SearchKnowledgeInScopes(ctx, scopes, keyword, offset, limit, fileTypes)
}
// SearchKnowledgeForScopes searches knowledge within the given scopes (e.g. for shared agent context).
func (s *knowledgeService) SearchKnowledgeForScopes(ctx context.Context, scopes []types.KnowledgeSearchScope, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, error) {
if len(scopes) == 0 {
return nil, false, nil
}
return s.repo.SearchKnowledgeInScopes(ctx, scopes, keyword, offset, limit, fileTypes)
}
// ProcessKnowledgeListDelete handles Asynq knowledge list delete tasks
func (s *knowledgeService) ProcessKnowledgeListDelete(ctx context.Context, t *asynq.Task) error {
var payload types.KnowledgeListDeletePayload
@@ -139,6 +139,23 @@ func (s *knowledgeBaseService) GetKnowledgeBaseByIDOnly(ctx context.Context, id
return kb, nil
}
// GetKnowledgeBasesByIDsOnly retrieves knowledge bases by IDs without tenant filter (batch).
func (s *knowledgeBaseService) GetKnowledgeBasesByIDsOnly(ctx context.Context, ids []string) ([]*types.KnowledgeBase, error) {
if len(ids) == 0 {
return nil, nil
}
kbs, err := s.repo.GetKnowledgeBaseByIDs(ctx, ids)
if err != nil {
return nil, err
}
for _, kb := range kbs {
if kb != nil {
kb.EnsureDefaults()
}
}
return kbs, nil
}
// ListKnowledgeBases returns all knowledge bases for a tenant
func (s *knowledgeBaseService) ListKnowledgeBases(ctx context.Context) ([]*types.KnowledgeBase, error) {
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
@@ -195,6 +212,59 @@ func (s *knowledgeBaseService) ListKnowledgeBases(ctx context.Context) ([]*types
return kbs, nil
}
// ListKnowledgeBasesByTenantID returns all knowledge bases for the given tenant (e.g. for shared agent context).
func (s *knowledgeBaseService) ListKnowledgeBasesByTenantID(ctx context.Context, tenantID uint64) ([]*types.KnowledgeBase, error) {
kbs, err := s.repo.ListKnowledgeBasesByTenantID(ctx, tenantID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": tenantID,
})
return nil, err
}
for _, kb := range kbs {
kb.EnsureDefaults()
switch kb.Type {
case types.KnowledgeBaseTypeDocument:
if cnt, err := s.kgRepo.CountKnowledgeByKnowledgeBaseID(ctx, tenantID, kb.ID); err == nil {
kb.KnowledgeCount = cnt
}
case types.KnowledgeBaseTypeFAQ:
if cnt, err := s.chunkRepo.CountChunksByKnowledgeBaseID(ctx, tenantID, kb.ID); err == nil {
kb.ChunkCount = cnt
}
}
if processingCount, err := s.kgRepo.CountKnowledgeByStatus(ctx, tenantID, kb.ID, []string{"pending", "processing"}); err == nil {
kb.IsProcessing = processingCount > 0
kb.ProcessingCount = processingCount
}
}
return kbs, nil
}
// FillKnowledgeBaseCounts fills KnowledgeCount, ChunkCount, IsProcessing, ProcessingCount for the given KB using kb.TenantID.
func (s *knowledgeBaseService) FillKnowledgeBaseCounts(ctx context.Context, kb *types.KnowledgeBase) error {
if kb == nil {
return nil
}
tenantID := kb.TenantID
kb.EnsureDefaults()
switch kb.Type {
case types.KnowledgeBaseTypeDocument:
if cnt, err := s.kgRepo.CountKnowledgeByKnowledgeBaseID(ctx, tenantID, kb.ID); err == nil {
kb.KnowledgeCount = cnt
}
case types.KnowledgeBaseTypeFAQ:
if cnt, err := s.chunkRepo.CountChunksByKnowledgeBaseID(ctx, tenantID, kb.ID); err == nil {
kb.ChunkCount = cnt
}
}
if processingCount, err := s.kgRepo.CountKnowledgeByStatus(ctx, tenantID, kb.ID, []string{"pending", "processing"}); err == nil {
kb.IsProcessing = processingCount > 0
kb.ProcessingCount = processingCount
}
return nil
}
// UpdateKnowledgeBase updates a knowledge base's properties
func (s *knowledgeBaseService) UpdateKnowledgeBase(ctx context.Context,
id string,
+22 -7
View File
@@ -39,17 +39,24 @@ var (
// organizationService implements OrganizationService interface
type organizationService struct {
orgRepo interfaces.OrganizationRepository
userRepo interfaces.UserRepository
shareRepo interfaces.KBShareRepository
orgRepo interfaces.OrganizationRepository
userRepo interfaces.UserRepository
shareRepo interfaces.KBShareRepository
agentShareRepo interfaces.AgentShareRepository
}
// NewOrganizationService creates a new organization service
func NewOrganizationService(orgRepo interfaces.OrganizationRepository, userRepo interfaces.UserRepository, shareRepo interfaces.KBShareRepository) interfaces.OrganizationService {
func NewOrganizationService(
orgRepo interfaces.OrganizationRepository,
userRepo interfaces.UserRepository,
shareRepo interfaces.KBShareRepository,
agentShareRepo interfaces.AgentShareRepository,
) interfaces.OrganizationService {
return &organizationService{
orgRepo: orgRepo,
userRepo: userRepo,
shareRepo: shareRepo,
orgRepo: orgRepo,
userRepo: userRepo,
shareRepo: shareRepo,
agentShareRepo: agentShareRepo,
}
}
@@ -227,6 +234,7 @@ func (s *organizationService) SearchSearchableOrganizations(ctx context.Context,
}
memberCounts := make(map[string]int64)
shareCounts := make(map[string]int64)
agentShareCounts := make(map[string]int)
memberOrgIDs := make(map[string]bool)
for _, org := range orgs {
if mc, err := s.orgRepo.CountMembers(ctx, org.ID); err == nil {
@@ -234,6 +242,9 @@ func (s *organizationService) SearchSearchableOrganizations(ctx context.Context,
}
shares, _ := s.shareRepo.ListByOrganization(ctx, org.ID)
shareCounts[org.ID] = int64(len(shares))
if agentShares, err := s.agentShareRepo.ListByOrganization(ctx, org.ID); err == nil {
agentShareCounts[org.ID] = len(agentShares)
}
_, err := s.orgRepo.GetMember(ctx, org.ID, userID)
memberOrgIDs[org.ID] = (err == nil)
}
@@ -247,6 +258,7 @@ func (s *organizationService) SearchSearchableOrganizations(ctx context.Context,
MemberCount: int(memberCounts[org.ID]),
MemberLimit: org.MemberLimit,
ShareCount: int(shareCounts[org.ID]),
AgentShareCount: agentShareCounts[org.ID],
IsAlreadyMember: memberOrgIDs[org.ID],
RequireApproval: org.RequireApproval,
})
@@ -312,6 +324,9 @@ func (s *organizationService) DeleteOrganization(ctx context.Context, id string,
if err := s.shareRepo.DeleteByOrganizationID(ctx, id); err != nil {
logger.Warnf(ctx, "Failed to delete KB shares for organization %s: %v", id, err)
}
if err := s.agentShareRepo.DeleteByOrganizationID(ctx, id); err != nil {
logger.Warnf(ctx, "Failed to delete agent shares for organization %s: %v", id, err)
}
return s.orgRepo.Delete(ctx, id)
}
+69 -42
View File
@@ -577,8 +577,20 @@ func (s *sessionService) KnowledgeQA(
}
}
// Retrieval scope: when agent is set, use agent's tenant (own or shared); otherwise session tenant or context
retrievalTenantID := session.TenantID
if customAgent != nil && customAgent.TenantID != 0 {
retrievalTenantID = customAgent.TenantID
logger.Infof(ctx, "Using agent tenant %d for retrieval scope", retrievalTenantID)
} else if v := ctx.Value(types.TenantIDContextKey); v != nil {
if tid, ok := v.(uint64); ok && tid != 0 {
retrievalTenantID = tid
logger.Infof(ctx, "Using effective tenant %d for retrieval from context", retrievalTenantID)
}
}
// Build unified search targets (computed once, used throughout pipeline)
searchTargets, err := s.buildSearchTargets(ctx, session.TenantID, knowledgeBaseIDs, knowledgeIDs)
searchTargets, err := s.buildSearchTargets(ctx, retrievalTenantID, knowledgeBaseIDs, knowledgeIDs)
if err != nil {
logger.Warnf(ctx, "Failed to build search targets: %v", err)
}
@@ -614,7 +626,7 @@ func (s *sessionService) KnowledgeQA(
FallbackPrompt: fallbackPrompt,
EventBus: eventBus.AsEventBusInterface(), // NEW: For pipeline to emit events directly
WebSearchEnabled: webSearchEnabled,
TenantID: session.TenantID,
TenantID: retrievalTenantID, // Effective tenant for retrieval (shared agent = agent's tenant)
RewritePromptSystem: rewritePromptSystem,
RewritePromptUser: rewritePromptUser,
EnableRewrite: enableRewrite,
@@ -923,12 +935,12 @@ func (s *sessionService) configureSkillsFromAgent(
}
// buildSearchTargets computes the unified search targets from knowledgeBaseIDs and knowledgeIDs
// This is called once at the request entry point to avoid repeated queries later in the pipeline
// buildSearchTargets computes the unified search targets from knowledgeBaseIDs and knowledgeIDs.
// tenantID is the retrieval scope: session.TenantID or effective tenant from shared agent (set by handler).
// This is called once at the request entry point to avoid repeated queries later in the pipeline.
// Logic:
// - For each knowledgeBaseID: create a SearchTargetTypeKnowledgeBase target with correct TenantID
// - For each knowledgeID: find its knowledgeBaseID, if the KB is already in the list, skip (covered by full KB search)
// otherwise create a SearchTargetTypeKnowledge target grouped by KB
// - For each knowledgeBaseID: resolve actual TenantID (own, org-shared, or in retrieval-tenant scope for shared agent)
// - For each knowledgeID: find its knowledgeBaseID; if the KB is already in the list, skip; otherwise add SearchTargetTypeKnowledge
func (s *sessionService) buildSearchTargets(
ctx context.Context,
tenantID uint64,
@@ -943,34 +955,31 @@ func (s *sessionService) buildSearchTargets(
// Track which KBs are fully searched
fullKBSet := make(map[string]bool)
// First pass: process knowledge base IDs and get their tenant info
// First pass: batch-fetch KBs, then resolve tenant per ID (tenant scope already set by caller)
if len(knowledgeBaseIDs) > 0 {
// Get KB details to determine their actual tenant IDs (may include shared KBs)
kbs, _ := s.knowledgeBaseService.GetKnowledgeBasesByIDsOnly(ctx, knowledgeBaseIDs)
kbByID := make(map[string]*types.KnowledgeBase, len(kbs))
for _, kb := range kbs {
if kb != nil {
kbByID[kb.ID] = kb
}
}
userID, _ := ctx.Value(types.UserIDContextKey).(string)
for _, kbID := range knowledgeBaseIDs {
fullKBSet[kbID] = true
// Try to get KB info - first from current tenant, then from shared access
kb, err := s.knowledgeBaseService.GetKnowledgeBaseByID(ctx, kbID)
if err != nil {
// May be a shared KB from another tenant - use kbShareService to check
if s.kbShareService != nil {
userID, _ := ctx.Value(types.UserIDContextKey).(string)
if userID != "" {
// Check if user has at least viewer permission on this KB
hasAccess, _ := s.kbShareService.HasKBPermission(ctx, kbID, userID, types.OrgRoleViewer)
if hasAccess {
// Get KB info without tenant filter
kbInfo, err := s.knowledgeBaseService.GetKnowledgeBaseByIDOnly(ctx, kbID)
if err == nil && kbInfo != nil {
kbTenantMap[kbID] = kbInfo.TenantID
}
}
}
kb := kbByID[kbID]
if kb == nil {
kbTenantMap[kbID] = tenantID
} else if kb.TenantID == tenantID {
kbTenantMap[kbID] = tenantID
} else if s.kbShareService != nil && userID != "" {
hasAccess, _ := s.kbShareService.HasKBPermission(ctx, kbID, userID, types.OrgRoleViewer)
if hasAccess {
kbTenantMap[kbID] = kb.TenantID
} else {
kbTenantMap[kbID] = tenantID
}
} else if kb != nil {
kbTenantMap[kbID] = kb.TenantID
}
// Default to current tenant if we couldn't determine the actual tenant
if kbTenantMap[kbID] == 0 {
} else {
kbTenantMap[kbID] = tenantID
}
targets = append(targets, &types.SearchTarget{
@@ -1215,26 +1224,44 @@ func (s *sessionService) AgentQA(
knowledgeIDs []string,
) error {
sessionID := session.ID
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
sessionJSON, err := json.Marshal(session)
if err != nil {
logger.Errorf(ctx, "Failed to marshal session, session ID: %s, error: %v", sessionID, err)
return fmt.Errorf("failed to marshal session: %w", err)
}
logger.Infof(ctx, "Start agent-based question answering, session ID: %s, tenant ID: %d, query: %s, session: %s",
sessionID, tenantID, query, string(sessionJSON))
// Build effective agent configuration by merging session and tenant configs
// All config now comes from customAgent parameter
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
// customAgent is required for AgentQA
// customAgent is required for AgentQA (handler has already done permission check for shared agent)
if customAgent == nil {
logger.Warnf(ctx, "Custom agent not provided for session: %s", sessionID)
return errors.New("custom agent configuration is required for agent QA")
}
// Use agent's tenant for retrieval and tenant-scoped config (handler has validated access)
agentTenantID := customAgent.TenantID
if agentTenantID == 0 {
agentTenantID = session.TenantID
}
logger.Infof(ctx, "Start agent-based question answering, session ID: %s, agent tenant ID: %d, query: %s, session: %s",
sessionID, agentTenantID, query, string(sessionJSON))
var tenantInfo *types.Tenant
if v := ctx.Value(types.TenantInfoContextKey); v != nil {
tenantInfo, _ = v.(*types.Tenant)
}
// When agent belongs to another tenant (shared agent), use agent's tenant for KB/model scope; load tenantInfo if needed
if tenantInfo == nil || tenantInfo.ID != agentTenantID {
if s.tenantService != nil {
if agentTenant, err := s.tenantService.GetTenantByID(ctx, agentTenantID); err == nil && agentTenant != nil {
tenantInfo = agentTenant
logger.Infof(ctx, "Using agent tenant info for retrieval scope, tenant ID: %d", agentTenantID)
}
}
}
if tenantInfo == nil {
logger.Warnf(ctx, "Tenant info not available for agent tenant %d, proceeding with defaults", agentTenantID)
tenantInfo = &types.Tenant{ID: agentTenantID}
}
// Ensure defaults are set
customAgent.EnsureDefaults()
@@ -1317,8 +1344,8 @@ func (s *sessionService) AgentQA(
logger.Infof(ctx, "No knowledge bases specified for agent, running in pure agent mode")
}
// Build search targets for agent (pre-compute once to avoid repeated queries)
searchTargets, err := s.buildSearchTargets(ctx, tenantInfo.ID, agentConfig.KnowledgeBases, agentConfig.KnowledgeIDs)
// Build search targets using agent's tenant (handler has validated access for shared agent)
searchTargets, err := s.buildSearchTargets(ctx, agentTenantID, agentConfig.KnowledgeBases, agentConfig.KnowledgeIDs)
if err != nil {
logger.Warnf(ctx, "Failed to build search targets for agent: %v", err)
// Continue without search targets, the tool will handle empty targets