feat(knowledge-base): implement per-user pinning for knowledge bases
Refactored the pinning mechanism for knowledge bases to be user-specific, allowing any user with read access to pin knowledge bases independently. This change includes the introduction of a new `user_kb_pins` table to manage pin states, replacing the previous tenant-wide pinning system. Updated relevant API endpoints and service logic to support this new functionality, ensuring that the UI reflects the user's personal pin status. Additionally, adjusted the knowledge base listing to sort by user-specific pin status, enhancing the user experience by prioritizing pinned items. Refs: #1303
This commit is contained in:
@@ -72,44 +72,99 @@ func (r *knowledgeBaseRepository) ListKnowledgeBases(ctx context.Context) ([]*ty
|
||||
return kbs, nil
|
||||
}
|
||||
|
||||
// ListKnowledgeBasesByTenantID lists all knowledge bases by tenant id
|
||||
// ListKnowledgeBasesByTenantID lists all knowledge bases by tenant id.
|
||||
//
|
||||
// Ordering used to also include `is_pinned DESC, pinned_at DESC` so the
|
||||
// repository would return tenant-wide pinned rows first. That column is
|
||||
// no longer the source of truth (see migration 000050) — pin state is
|
||||
// now per (user, kb) and applied by the service layer after enrichment.
|
||||
// We keep `created_at DESC` here so callers that don't enrich (chat
|
||||
// pipeline, agent editor, IM commands) still get a stable ordering.
|
||||
func (r *knowledgeBaseRepository) ListKnowledgeBasesByTenantID(
|
||||
ctx context.Context, tenantID uint64,
|
||||
) ([]*types.KnowledgeBase, error) {
|
||||
var kbs []*types.KnowledgeBase
|
||||
if err := r.db.WithContext(ctx).Where("tenant_id = ? AND is_temporary = ?", tenantID, false).
|
||||
Order("is_pinned DESC, pinned_at DESC, created_at DESC").Find(&kbs).Error; err != nil {
|
||||
Order("created_at DESC").Find(&kbs).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return kbs, nil
|
||||
}
|
||||
|
||||
// TogglePinKnowledgeBase toggles the pin status of a knowledge base
|
||||
func (r *knowledgeBaseRepository) TogglePinKnowledgeBase(ctx context.Context, id string, tenantID uint64) (*types.KnowledgeBase, error) {
|
||||
var kb types.KnowledgeBase
|
||||
if err := r.db.WithContext(ctx).Where("id = ? AND tenant_id = ?", id, tenantID).First(&kb).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrKnowledgeBaseNotFound
|
||||
// userKBPinRow mirrors the user_kb_pins table. Kept local to the
|
||||
// repository because it never escapes the package; callers see the
|
||||
// higher-level map[kb_id]pinned_at returned by ListUserKBPinIDs.
|
||||
type userKBPinRow struct {
|
||||
TenantID uint64 `gorm:"column:tenant_id"`
|
||||
UserID string `gorm:"column:user_id"`
|
||||
KBID string `gorm:"column:kb_id"`
|
||||
PinnedAt time.Time `gorm:"column:pinned_at"`
|
||||
}
|
||||
|
||||
func (userKBPinRow) TableName() string { return "user_kb_pins" }
|
||||
|
||||
// SetUserKBPin upserts (pinned=true) or deletes (pinned=false) the row
|
||||
// for the given (tenant, user, kb) triple. The returned pinned_at is
|
||||
// nil when pinned=false; otherwise it carries the timestamp written
|
||||
// to the row (either the existing one if the row already existed, or
|
||||
// the current time on insert) so the caller can stamp the response
|
||||
// without a follow-up SELECT.
|
||||
func (r *knowledgeBaseRepository) SetUserKBPin(
|
||||
ctx context.Context, tenantID uint64, userID string, kbID string, pinned bool,
|
||||
) (*time.Time, error) {
|
||||
if userID == "" {
|
||||
return nil, errors.New("user_kb_pins: empty user_id")
|
||||
}
|
||||
if !pinned {
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND user_id = ? AND kb_id = ?", tenantID, userID, kbID).
|
||||
Delete(&userKBPinRow{}).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, err
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if kb.IsPinned {
|
||||
kb.IsPinned = false
|
||||
kb.PinnedAt = nil
|
||||
} else {
|
||||
kb.IsPinned = true
|
||||
now := time.Now()
|
||||
kb.PinnedAt = &now
|
||||
// Upsert with idempotent INSERT … ON CONFLICT DO NOTHING. We then
|
||||
// SELECT to learn whether an existing row's pinned_at survived (so
|
||||
// repeated calls return a stable timestamp instead of bumping it).
|
||||
row := userKBPinRow{
|
||||
TenantID: tenantID,
|
||||
UserID: userID,
|
||||
KBID: kbID,
|
||||
PinnedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := r.db.WithContext(ctx).Model(&kb).Updates(map[string]interface{}{
|
||||
"is_pinned": kb.IsPinned,
|
||||
"pinned_at": kb.PinnedAt,
|
||||
}).Error; err != nil {
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND user_id = ? AND kb_id = ?", tenantID, userID, kbID).
|
||||
Attrs(userKBPinRow{PinnedAt: row.PinnedAt}).
|
||||
FirstOrCreate(&row).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &kb, nil
|
||||
pa := row.PinnedAt
|
||||
return &pa, nil
|
||||
}
|
||||
|
||||
// ListUserKBPinIDs returns every KB id this user has personally pinned
|
||||
// in this tenant, mapped to its pinned_at. Returns an empty map (not
|
||||
// nil) when there are no pins, so callers can do `len(m) == 0` checks
|
||||
// without a nil guard.
|
||||
func (r *knowledgeBaseRepository) ListUserKBPinIDs(
|
||||
ctx context.Context, tenantID uint64, userID string,
|
||||
) (map[string]time.Time, error) {
|
||||
out := make(map[string]time.Time)
|
||||
if userID == "" {
|
||||
return out, nil
|
||||
}
|
||||
var rows []userKBPinRow
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND user_id = ?", tenantID, userID).
|
||||
Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, row := range rows {
|
||||
out[row.KBID] = row.PinnedAt
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// UpdateKnowledgeBase updates a knowledge base
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/service/retriever"
|
||||
@@ -300,6 +301,14 @@ func (s *knowledgeBaseService) ListKnowledgeBases(ctx context.Context) ([]*types
|
||||
kb.ProcessingCount = processingCount
|
||||
}
|
||||
}
|
||||
|
||||
// Per-user pin stamping + ordering. The "main" list view is the
|
||||
// only path that needs to honour the caller's personal pin set;
|
||||
// agent/share/IM callers go through ListKnowledgeBasesByTenantID
|
||||
// which also enriches but keys off the user in their own context.
|
||||
if userID, ok := types.UserIDFromContext(ctx); ok && userID != "" {
|
||||
s.applyUserKBPins(ctx, tenantID, userID, kbs)
|
||||
}
|
||||
return kbs, nil
|
||||
}
|
||||
|
||||
@@ -329,6 +338,15 @@ func (s *knowledgeBaseService) ListKnowledgeBasesByTenantID(ctx context.Context,
|
||||
kb.ProcessingCount = processingCount
|
||||
}
|
||||
}
|
||||
|
||||
// Stamp pin state from the caller's perspective. The tenantID
|
||||
// argument may not match the caller's own tenant (this method is
|
||||
// also used to list a shared-agent's source-tenant KBs); we still
|
||||
// scope user_kb_pins by `tenantID` since a pin tied to one tenant
|
||||
// shouldn't surface when browsing another tenant's KBs.
|
||||
if userID, ok := types.UserIDFromContext(ctx); ok && userID != "" {
|
||||
s.applyUserKBPins(ctx, tenantID, userID, kbs)
|
||||
}
|
||||
return kbs, nil
|
||||
}
|
||||
|
||||
@@ -441,23 +459,127 @@ func (s *knowledgeBaseService) UpdateKnowledgeBase(ctx context.Context,
|
||||
return kb, nil
|
||||
}
|
||||
|
||||
// TogglePinKnowledgeBase toggles the pin status of a knowledge base
|
||||
func (s *knowledgeBaseService) TogglePinKnowledgeBase(ctx context.Context, id string) (*types.KnowledgeBase, error) {
|
||||
// TogglePinKnowledgeBase toggles whether the calling user has pinned
|
||||
// this knowledge base. Pin state is per-(user, kb) as of migration
|
||||
// 000050; previously this method flipped a tenant-wide column on the
|
||||
// KB row which broke down under RBAC (only Admin/creator could pin,
|
||||
// and the pin reordered the list for everyone in the tenant). The
|
||||
// public signature is unchanged so the HTTP handler / CLI / SDK don't
|
||||
// move.
|
||||
//
|
||||
// The KB still has to belong to the caller's tenant — the route is
|
||||
// already gated behind KBAccessRead, but we re-check via
|
||||
// GetKnowledgeBaseByIDAndTenant so a stale param survives a tenant
|
||||
// switch cleanly.
|
||||
func (s *knowledgeBaseService) TogglePinKnowledgeBase(
|
||||
ctx context.Context, id string,
|
||||
) (*types.KnowledgeBase, error) {
|
||||
if id == "" {
|
||||
return nil, errors.New("knowledge base ID cannot be empty")
|
||||
}
|
||||
tenantID := types.MustTenantIDFromContext(ctx)
|
||||
kb, err := s.repo.TogglePinKnowledgeBase(ctx, id, tenantID)
|
||||
userID, ok := types.UserIDFromContext(ctx)
|
||||
if !ok || userID == "" {
|
||||
// API-key callers without a user identity can't have a personal
|
||||
// pin set. We surface this rather than silently flipping a
|
||||
// shared-tenant flag like the old behaviour.
|
||||
return nil, errors.New("pin requires an authenticated user")
|
||||
}
|
||||
|
||||
// Look the KB up without a tenant filter: the route's KBAccessRead
|
||||
// guard already validated that this caller can see this KB (own,
|
||||
// org-shared, or agent-shared). Filtering by the caller's tenant
|
||||
// here would 404 every legitimate pin against a shared KB whose
|
||||
// owning tenant differs from the caller's active tenant.
|
||||
kb, err := s.repo.GetKnowledgeBaseByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"knowledge_base_id": id,
|
||||
"tenant_id": tenantID,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
logger.Infof(ctx, "Knowledge base pin toggled, ID: %s, is_pinned: %v", id, kb.IsPinned)
|
||||
|
||||
// Read current pin state to decide direction. ListUserKBPinIDs is
|
||||
// already optimised for the "many KBs at once" path; for a single-id
|
||||
// check the round-trip is acceptable and avoids leaking a second
|
||||
// repository method just for this.
|
||||
pins, err := s.repo.ListUserKBPinIDs(ctx, tenantID, userID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"knowledge_base_id": id,
|
||||
"tenant_id": tenantID,
|
||||
"user_id": userID,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
_, currentlyPinned := pins[id]
|
||||
|
||||
pinnedAt, err := s.repo.SetUserKBPin(ctx, tenantID, userID, id, !currentlyPinned)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"knowledge_base_id": id,
|
||||
"tenant_id": tenantID,
|
||||
"user_id": userID,
|
||||
"target_pinned": !currentlyPinned,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
kb.EnsureDefaults()
|
||||
kb.IsPinned = !currentlyPinned
|
||||
kb.PinnedAt = pinnedAt
|
||||
logger.Infof(ctx, "Knowledge base pin toggled, ID: %s, user: %s, is_pinned: %v",
|
||||
id, userID, kb.IsPinned)
|
||||
return kb, nil
|
||||
}
|
||||
|
||||
// applyUserKBPins stamps IsPinned / PinnedAt onto each KB in the slice
|
||||
// from the caller's perspective and sorts the slice so pinned rows
|
||||
// float to the top (newest pin first, ties broken by created_at desc).
|
||||
// Safe to call with an empty userID (no-op stamp; default sort by
|
||||
// created_at preserved).
|
||||
func (s *knowledgeBaseService) applyUserKBPins(
|
||||
ctx context.Context, tenantID uint64, userID string, kbs []*types.KnowledgeBase,
|
||||
) {
|
||||
if len(kbs) == 0 || userID == "" {
|
||||
return
|
||||
}
|
||||
pins, err := s.repo.ListUserKBPinIDs(ctx, tenantID, userID)
|
||||
if err != nil {
|
||||
// Pin enrichment is best-effort: a transient DB blip here
|
||||
// should not break listing KBs. Log and bail without altering
|
||||
// the slice — caller still gets a valid list, just unsorted by
|
||||
// pin.
|
||||
logger.Warnf(ctx, "applyUserKBPins: failed to load pins for tenant=%d user=%s: %v",
|
||||
tenantID, userID, err)
|
||||
return
|
||||
}
|
||||
if len(pins) == 0 {
|
||||
return
|
||||
}
|
||||
for _, kb := range kbs {
|
||||
if ts, ok := pins[kb.ID]; ok {
|
||||
kb.IsPinned = true
|
||||
t := ts
|
||||
kb.PinnedAt = &t
|
||||
}
|
||||
}
|
||||
sort.SliceStable(kbs, func(i, j int) bool {
|
||||
a, b := kbs[i], kbs[j]
|
||||
if a.IsPinned != b.IsPinned {
|
||||
return a.IsPinned
|
||||
}
|
||||
if a.IsPinned && b.IsPinned {
|
||||
at, bt := a.PinnedAt, b.PinnedAt
|
||||
if at != nil && bt != nil && !at.Equal(*bt) {
|
||||
return at.After(*bt)
|
||||
}
|
||||
}
|
||||
return a.CreatedAt.After(b.CreatedAt)
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteKnowledgeBase deletes a knowledge base by its ID
|
||||
// This method marks the knowledge base as deleted and enqueues an async task
|
||||
// to handle the heavy cleanup operations (embeddings, chunks, files, graph data)
|
||||
|
||||
Reference in New Issue
Block a user