feat: add organization management features

- Introduced a new API for organization management, including creation, updating, and deletion of organizations.
- Implemented organization sharing functionality for knowledge bases, allowing users to share knowledge bases with specific organizations and set permissions.
- Added UI components for organization selection and sharing dialogs.
- Enhanced existing components to support organization-related features, including shared knowledge base handling and organization role management.

This update enhances collaboration capabilities within the application by allowing users to manage and share knowledge bases across different organizations.
This commit is contained in:
wizardchen
2026-01-30 16:28:01 +08:00
committed by lyingbug
parent 548450c170
commit 4158773849
72 changed files with 14685 additions and 1419 deletions
+2 -1
View File
@@ -369,7 +369,8 @@ func (t *DataAnalysisTool) LoadFromKnowledge(ctx context.Context, knowledge *typ
// - *TableSchema: schema information of the created table
// - error: any error that occurred during the operation
func (t *DataAnalysisTool) LoadFromKnowledgeID(ctx context.Context, knowledgeID string) (*TableSchema, error) {
knowledge, err := t.knowledgeService.GetKnowledgeByID(ctx, knowledgeID)
// Use GetKnowledgeByIDOnly to support cross-tenant shared KB
knowledge, err := t.knowledgeService.GetKnowledgeByIDOnly(ctx, knowledgeID)
if err != nil {
logger.Errorf(ctx, "[Tool][DataAnalysis] Failed to get knowledge by ID '%s': %v", knowledgeID, err)
return nil, fmt.Errorf("failed to get knowledge by ID: %w", err)
+2 -2
View File
@@ -49,8 +49,8 @@ func (t *DataSchemaTool) Execute(ctx context.Context, args json.RawMessage) (*ty
}, err
}
// Get knowledge to get TenantID
knowledge, err := t.knowledgeService.GetKnowledgeByID(ctx, input.KnowledgeID)
// Get knowledge to get TenantID (use IDOnly to support cross-tenant shared KB)
knowledge, err := t.knowledgeService.GetKnowledgeByIDOnly(ctx, input.KnowledgeID)
if err != nil {
return &types.ToolResult{
Success: false,
+17 -9
View File
@@ -54,27 +54,25 @@ type GetDocumentInfoTool struct {
BaseTool
knowledgeService interfaces.KnowledgeService
chunkService interfaces.ChunkService
searchTargets types.SearchTargets // Pre-computed unified search targets with KB-tenant mapping
}
// NewGetDocumentInfoTool creates a new get document info tool
func NewGetDocumentInfoTool(
knowledgeService interfaces.KnowledgeService,
chunkService interfaces.ChunkService,
searchTargets types.SearchTargets,
) *GetDocumentInfoTool {
return &GetDocumentInfoTool{
BaseTool: getDocumentInfoTool,
knowledgeService: knowledgeService,
chunkService: chunkService,
searchTargets: searchTargets,
}
}
// Execute retrieves document information with concurrent processing
func (t *GetDocumentInfoTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
tenantID := uint64(0)
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok {
tenantID = tid
}
// Parse args from json.RawMessage
var input GetDocumentInfoInput
if err := json.Unmarshal(args, &input); err != nil {
@@ -118,8 +116,8 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args json.RawMessage)
go func(id string) {
defer wg.Done()
// Get knowledge metadata
knowledge, err := t.knowledgeService.GetRepository().GetKnowledgeByID(ctx, tenantID, id)
// Get knowledge metadata without tenant filter to support shared KB
knowledge, err := t.knowledgeService.GetKnowledgeByIDOnly(ctx, id)
if err != nil {
mu.Lock()
results[id] = &docInfo{
@@ -129,9 +127,19 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args json.RawMessage)
return
}
// Get chunk count
// Verify the knowledge's KB is in searchTargets (permission check)
if !t.searchTargets.ContainsKB(knowledge.KnowledgeBaseID) {
mu.Lock()
results[id] = &docInfo{
err: fmt.Errorf("知识库 %s 不可访问", knowledge.KnowledgeBaseID),
}
mu.Unlock()
return
}
// Use knowledge's actual tenant_id for chunk query (supports cross-tenant shared KB)
_, total, err := t.chunkService.GetRepository().
ListPagedChunksByKnowledgeID(ctx, tenantID, id, &types.Pagination{
ListPagedChunksByKnowledgeID(ctx, knowledge.TenantID, id, &types.Pagination{
Page: 1,
PageSize: 1000,
}, []types.ChunkType{"text"}, "", "", "", "", "")
+62 -32
View File
@@ -94,18 +94,16 @@ type GrepChunksInput struct {
// Similar to grep command in Unix-like systems, but operates on knowledge base content
type GrepChunksTool struct {
BaseTool
db *gorm.DB
knowledgeBaseIDs []string
knowledgeIDs []string // Specific knowledge/document IDs to search within
db *gorm.DB
searchTargets types.SearchTargets // Pre-computed unified search targets with KB-tenant mapping
}
// NewGrepChunksTool creates a new grep chunks tool
func NewGrepChunksTool(db *gorm.DB, knowledgeBaseIDs []string, knowledgeIDs []string) *GrepChunksTool {
func NewGrepChunksTool(db *gorm.DB, searchTargets types.SearchTargets) *GrepChunksTool {
return &GrepChunksTool{
BaseTool: grepChunksTool,
db: db,
knowledgeBaseIDs: knowledgeBaseIDs,
knowledgeIDs: knowledgeIDs,
BaseTool: grepChunksTool,
db: db,
searchTargets: searchTargets,
}
}
@@ -148,27 +146,38 @@ func (t *GrepChunksTool) Execute(ctx context.Context, args json.RawMessage) (*ty
}
}
// Parse knowledge_base_ids filter
kbIDs := input.KnowledgeBaseIDs
if len(kbIDs) == 0 {
kbIDs = t.knowledgeBaseIDs
// Get allowed KBs from searchTargets
allowedKBIDs := t.searchTargets.GetAllKnowledgeBaseIDs()
kbTenantMap := t.searchTargets.GetKBTenantMap()
// Collect all specific knowledge IDs from searchTargets
var allowedKnowledgeIDs []string
for _, target := range t.searchTargets {
if target.Type == types.SearchTargetTypeKnowledge && len(target.KnowledgeIDs) > 0 {
allowedKnowledgeIDs = append(allowedKnowledgeIDs, target.KnowledgeIDs...)
}
}
// // Parse knowledge_ids filter
// var knowledgeIDs []string
// if knowledgeIDsRaw, ok := args["knowledge_ids"].([]interface{}); ok {
// for _, id := range knowledgeIDsRaw {
// if idStr, ok := id.(string); ok && idStr != "" {
// knowledgeIDs = append(knowledgeIDs, idStr)
// }
// }
// }
// Parse knowledge_base_ids filter from input
kbIDs := input.KnowledgeBaseIDs
if len(kbIDs) == 0 {
kbIDs = allowedKBIDs
} else {
// Validate input KBs against allowed KBs
validKBs := make([]string, 0)
for _, kbID := range kbIDs {
if t.searchTargets.ContainsKB(kbID) {
validKBs = append(validKBs, kbID)
}
}
kbIDs = validKBs
}
logger.Infof(ctx, "[Tool][GrepChunks] Patterns: %v, MaxResults: %d, KnowledgeIDs: %v",
patterns, maxResults, t.knowledgeIDs)
logger.Infof(ctx, "[Tool][GrepChunks] Patterns: %v, MaxResults: %d, KBs: %v, KnowledgeIDs: %v, KBTenantMap: %v",
patterns, maxResults, kbIDs, allowedKnowledgeIDs, kbTenantMap)
// Build and execute query
results, totalCount, err := t.searchChunks(ctx, patterns, kbIDs, t.knowledgeIDs)
// Build and execute query with tenant info
results, totalCount, err := t.searchChunks(ctx, patterns, kbIDs, allowedKnowledgeIDs, kbTenantMap)
if err != nil {
logger.Errorf(ctx, "[Tool][GrepChunks] Search failed: %v", err)
return &types.ToolResult{
@@ -256,32 +265,53 @@ type chunkWithTitle struct {
}
// searchChunks performs the database search with pattern matching
// kbTenantMap provides KB-to-tenant mapping for cross-tenant queries
func (t *GrepChunksTool) searchChunks(
ctx context.Context,
patterns []string,
kbIDs []string,
knowledgeIDs []string,
kbTenantMap map[string]uint64,
) ([]chunkWithTitle, int64, error) {
tenantID := uint64(0)
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok {
tenantID = tid
// Safety check: must have either kbIDs or knowledgeIDs
if len(kbIDs) == 0 && len(knowledgeIDs) == 0 {
logger.Warnf(ctx, "[Tool][GrepChunks] No kbIDs or knowledgeIDs specified, returning empty results")
return nil, 0, nil
}
// Build base query
// Use knowledge_base_id filter combined with tenant_id to ensure data isolation
query := t.db.Debug().WithContext(ctx).Table("chunks").
Select("chunks.id, chunks.content, chunks.chunk_index, chunks.knowledge_id, chunks.knowledge_base_id, chunks.chunk_type, chunks.created_at, knowledges.title as knowledge_title, COUNT(*) OVER (PARTITION BY chunks.knowledge_id) AS total_chunk_count").
Joins("LEFT JOIN knowledges ON chunks.knowledge_id = knowledges.id").
Where("chunks.tenant_id = ?", tenantID).
Where("chunks.is_enabled = ?", true).
Where("chunks.deleted_at IS NULL").
Where("knowledges.deleted_at IS NULL")
// Apply knowledge IDs filter (specific documents) - takes priority over KB filter
// Build tenant-aware KB filter: (kb_id = X AND tenant_id = Y) OR (kb_id = Z AND tenant_id = W) ...
// This ensures we only access chunks from KBs we have permission for, with correct tenant scope
if len(knowledgeIDs) > 0 {
// For specific knowledge IDs, filter directly by knowledge_id
// Permission already checked when building searchTargets
query = query.Where("chunks.knowledge_id IN ?", knowledgeIDs)
logger.Infof(ctx, "[Tool][GrepChunks] Filtering by %d specific knowledge IDs", len(knowledgeIDs))
} else if len(kbIDs) > 0 {
// Apply knowledge base filter only if no specific knowledge IDs
query = query.Where("chunks.knowledge_base_id IN ?", kbIDs)
// Build OR conditions for each KB with its tenant
var conditions []string
var args []interface{}
for _, kbID := range kbIDs {
tenantID := kbTenantMap[kbID]
if tenantID > 0 {
conditions = append(conditions, "(chunks.knowledge_base_id = ? AND chunks.tenant_id = ?)")
args = append(args, kbID, tenantID)
}
}
if len(conditions) > 0 {
query = query.Where("("+strings.Join(conditions, " OR ")+")", args...)
} else {
logger.Warnf(ctx, "[Tool][GrepChunks] No valid KB-tenant pairs found")
return nil, 0, nil
}
}
// Apply pattern matching (case-insensitive fixed string matching, OR logic for multiple patterns)
+21 -17
View File
@@ -965,10 +965,6 @@ func (t *KnowledgeSearchTool) formatOutput(
kbsToSearch []string,
queries []string,
) (*types.ToolResult, error) {
tenantID := uint64(0)
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok {
tenantID = tid
}
if len(results) == 0 {
data := map[string]interface{}{
"knowledge_base_ids": kbsToSearch,
@@ -1052,22 +1048,30 @@ func (t *KnowledgeSearchTool) formatOutput(
output += fmt.Sprintf("[Source Document: %s]\n", result.KnowledgeTitle)
// Get total chunk count for this knowledge (cache it)
// Use KB's tenant_id from searchTargets to support cross-tenant shared KB
if _, exists := knowledgeTotalMap[result.KnowledgeID]; !exists {
_, total, err := t.chunkService.GetRepository().ListPagedChunksByKnowledgeID(ctx,
tenantID, result.KnowledgeID,
&types.Pagination{Page: 1, PageSize: 1},
[]types.ChunkType{types.ChunkTypeText}, "", "", "", "", "",
)
if err != nil {
logger.Warnf(
ctx,
"[Tool][KnowledgeSearch] Failed to get total chunks for knowledge %s: %v",
result.KnowledgeID,
err,
)
// Get tenant_id from searchTargets using the KB ID from the result
effectiveTenantID := t.searchTargets.GetTenantIDForKB(result.KnowledgeBaseID)
if effectiveTenantID == 0 {
logger.Warnf(ctx, "[Tool][KnowledgeSearch] KB %s not found in searchTargets, skipping chunk count", result.KnowledgeBaseID)
knowledgeTotalMap[result.KnowledgeID] = 0
} else {
knowledgeTotalMap[result.KnowledgeID] = total
_, total, err := t.chunkService.GetRepository().ListPagedChunksByKnowledgeID(ctx,
effectiveTenantID, result.KnowledgeID,
&types.Pagination{Page: 1, PageSize: 1},
[]types.ChunkType{types.ChunkTypeText}, "", "", "", "", "",
)
if err != nil {
logger.Warnf(
ctx,
"[Tool][KnowledgeSearch] Failed to get total chunks for knowledge %s: %v",
result.KnowledgeID,
err,
)
knowledgeTotalMap[result.KnowledgeID] = 0
} else {
knowledgeTotalMap[result.KnowledgeID] = total
}
}
}
}
+26 -7
View File
@@ -67,27 +67,25 @@ type ListKnowledgeChunksTool struct {
BaseTool
chunkService interfaces.ChunkService
knowledgeService interfaces.KnowledgeService
searchTargets types.SearchTargets // Pre-computed unified search targets with KB-tenant mapping
}
// NewListKnowledgeChunksTool creates a new tool instance.
func NewListKnowledgeChunksTool(
knowledgeService interfaces.KnowledgeService,
chunkService interfaces.ChunkService,
searchTargets types.SearchTargets,
) *ListKnowledgeChunksTool {
return &ListKnowledgeChunksTool{
BaseTool: listKnowledgeChunksTool,
chunkService: chunkService,
knowledgeService: knowledgeService,
searchTargets: searchTargets,
}
}
// Execute performs the chunk fetch against the chunk service.
func (t *ListKnowledgeChunksTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
tenantID := uint64(0)
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok {
tenantID = tid
}
// Parse args from json.RawMessage
var input ListKnowledgeChunksInput
if err := json.Unmarshal(args, &input); err != nil {
@@ -107,6 +105,26 @@ func (t *ListKnowledgeChunksTool) Execute(ctx context.Context, args json.RawMess
}
knowledgeID = strings.TrimSpace(knowledgeID)
// Get knowledge info without tenant filter to support shared KB
knowledge, err := t.knowledgeService.GetKnowledgeByIDOnly(ctx, knowledgeID)
if err != nil {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Knowledge not found: %v", err),
}, err
}
// Verify the knowledge's KB is in searchTargets (permission check)
if !t.searchTargets.ContainsKB(knowledge.KnowledgeBaseID) {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Knowledge base %s is not accessible", knowledge.KnowledgeBaseID),
}, fmt.Errorf("knowledge base not in search targets")
}
// Use the knowledge's actual tenant_id for chunk query (supports cross-tenant shared KB)
effectiveTenantID := knowledge.TenantID
chunkLimit := 20
if input.Limit > 0 {
chunkLimit = input.Limit
@@ -125,7 +143,7 @@ func (t *ListKnowledgeChunksTool) Execute(ctx context.Context, args json.RawMess
}
chunks, total, err := t.chunkService.GetRepository().ListPagedChunksByKnowledgeID(ctx,
tenantID, knowledgeID, pagination, []types.ChunkType{types.ChunkTypeText, types.ChunkTypeFAQ}, "", "", "", "", "")
effectiveTenantID, knowledgeID, pagination, []types.ChunkType{types.ChunkTypeText, types.ChunkTypeFAQ}, "", "", "", "", "")
if err != nil {
return &types.ToolResult{
Success: false,
@@ -206,11 +224,12 @@ func (t *ListKnowledgeChunksTool) Execute(ctx context.Context, args json.RawMess
}
// lookupKnowledgeTitle looks up the title of a knowledge document
// Uses GetKnowledgeByIDOnly to support cross-tenant shared KB
func (t *ListKnowledgeChunksTool) lookupKnowledgeTitle(ctx context.Context, knowledgeID string) string {
if t.knowledgeService == nil {
return ""
}
knowledge, err := t.knowledgeService.GetKnowledgeByID(ctx, knowledgeID)
knowledge, err := t.knowledgeService.GetKnowledgeByIDOnly(ctx, knowledgeID)
if err != nil || knowledge == nil {
return ""
}