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:
@@ -150,10 +150,6 @@
|
||||
}"
|
||||
:ref="el => { if (highlightedKbId !== null && highlightedKbId === kb.id && el) highlightedCardRef = el as HTMLElement }"
|
||||
@click="handleCardClick(kb)">
|
||||
<!-- 置顶标识 -->
|
||||
<div v-if="kb.is_pinned" class="pin-indicator">
|
||||
<t-icon name="pin-filled" size="14px" />
|
||||
</div>
|
||||
<!-- 收藏按钮:右上角浮动 -->
|
||||
<button type="button" class="kb-favorite-star" :class="{ 'is-favorited': isKbFavorited(kb.id) }"
|
||||
@click.stop="toggleFavoriteKb(kb.id, $event)">
|
||||
@@ -162,7 +158,11 @@
|
||||
<!-- 卡片头部 -->
|
||||
<div class="card-header">
|
||||
<span class="card-title" :title="kb.name">{{ kb.name }}</span>
|
||||
<t-popup v-if="canManageKBCard(kb)" overlayClassName="card-more-popup" trigger="click" destroy-on-close
|
||||
<!-- The card menu always exists when the card is visible: pin
|
||||
is now per-user and available to anyone who can see the KB
|
||||
(backend route only requires KB read access). Settings /
|
||||
Delete are mutations, so they stay behind canManageKBCard. -->
|
||||
<t-popup overlayClassName="card-more-popup" trigger="click" destroy-on-close
|
||||
placement="bottom-right">
|
||||
<div class="more-wrap" @click.stop>
|
||||
<img class="more-icon" src="@/assets/img/more.png" alt="" />
|
||||
@@ -173,14 +173,16 @@
|
||||
<t-icon class="menu-icon" :name="kb.is_pinned ? 'pin-filled' : 'pin'" />
|
||||
<span>{{ kb.is_pinned ? $t('knowledgeList.pin.unpin') : $t('knowledgeList.pin.pin') }}</span>
|
||||
</div>
|
||||
<div class="popup-menu-item" @click.stop="handleSettingsById(kb.id)">
|
||||
<t-icon class="menu-icon" name="setting" />
|
||||
<span>{{ $t('knowledgeBase.settings') }}</span>
|
||||
</div>
|
||||
<div class="popup-menu-item delete" @click.stop="handleDeleteById(kb.id)">
|
||||
<t-icon class="menu-icon" name="delete" />
|
||||
<span>{{ $t('common.delete') }}</span>
|
||||
</div>
|
||||
<template v-if="canManageKBCard(kb)">
|
||||
<div class="popup-menu-item" @click.stop="handleSettingsById(kb.id)">
|
||||
<t-icon class="menu-icon" name="setting" />
|
||||
<span>{{ $t('knowledgeBase.settings') }}</span>
|
||||
</div>
|
||||
<div class="popup-menu-item delete" @click.stop="handleDeleteById(kb.id)">
|
||||
<t-icon class="menu-icon" name="delete" />
|
||||
<span>{{ $t('common.delete') }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
</t-popup>
|
||||
@@ -350,10 +352,6 @@
|
||||
}"
|
||||
:ref="el => { if (highlightedKbId !== null && highlightedKbId === kb.id && el) highlightedCardRef = el as HTMLElement }"
|
||||
@click="handleCardClick(kb)">
|
||||
<!-- 置顶标识 -->
|
||||
<div v-if="kb.is_pinned" class="pin-indicator">
|
||||
<t-icon name="pin-filled" size="14px" />
|
||||
</div>
|
||||
<!-- 收藏按钮 -->
|
||||
<button type="button" class="kb-favorite-star" :class="{ 'is-favorited': isKbFavorited(kb.id) }"
|
||||
@click.stop="toggleFavoriteKb(kb.id, $event)">
|
||||
@@ -362,7 +360,9 @@
|
||||
<!-- 卡片头部 -->
|
||||
<div class="card-header">
|
||||
<span class="card-title" :title="kb.name">{{ kb.name }}</span>
|
||||
<t-popup v-if="canManageKBCard(kb)" v-model="kb.showMore" overlayClassName="card-more-popup"
|
||||
<!-- See the matching block in the "all" tab template for why
|
||||
this is no longer gated by canManageKBCard. -->
|
||||
<t-popup v-model="kb.showMore" overlayClassName="card-more-popup"
|
||||
:on-visible-change="onVisibleChange" trigger="click" destroy-on-close placement="bottom-right">
|
||||
<div variant="outline" class="more-wrap" @click.stop="openMore(index)"
|
||||
:class="{ 'active-more': currentMoreIndex === index }">
|
||||
@@ -374,14 +374,16 @@
|
||||
<t-icon class="menu-icon" :name="kb.is_pinned ? 'pin-filled' : 'pin'" />
|
||||
<span>{{ kb.is_pinned ? $t('knowledgeList.pin.unpin') : $t('knowledgeList.pin.pin') }}</span>
|
||||
</div>
|
||||
<div class="popup-menu-item" @click.stop="handleSettings(kb)">
|
||||
<t-icon class="menu-icon" name="setting" />
|
||||
<span>{{ $t('knowledgeBase.settings') }}</span>
|
||||
</div>
|
||||
<div class="popup-menu-item delete" @click.stop="handleDelete(kb)">
|
||||
<t-icon class="menu-icon" name="delete" />
|
||||
<span>{{ $t('common.delete') }}</span>
|
||||
</div>
|
||||
<template v-if="canManageKBCard(kb)">
|
||||
<div class="popup-menu-item" @click.stop="handleSettings(kb)">
|
||||
<t-icon class="menu-icon" name="setting" />
|
||||
<span>{{ $t('knowledgeBase.settings') }}</span>
|
||||
</div>
|
||||
<div class="popup-menu-item delete" @click.stop="handleDelete(kb)">
|
||||
<t-icon class="menu-icon" name="delete" />
|
||||
<span>{{ $t('common.delete') }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
</t-popup>
|
||||
@@ -1132,11 +1134,17 @@ const handleSettings = (kb: KB) => {
|
||||
goSettings(kb.id)
|
||||
}
|
||||
|
||||
// canManageKBCard mirrors KnowledgeBase.vue's `canManage` for the
|
||||
// per-card more-menu so a Viewer cannot click into Settings or Delete
|
||||
// for a KB they don't own. The server still rejects the call (PR 5
|
||||
// guards every mutation with OwnedKBOrAdmin) but the UI shouldn't
|
||||
// surface buttons the user has no authority to use.
|
||||
// canManageKBCard mirrors KnowledgeBase.vue's `canManage`, gating the
|
||||
// destructive items of the per-card menu — Settings, Delete — so a
|
||||
// Viewer cannot click into them for a KB they don't own. The server
|
||||
// still rejects the call (PR 5 guards every such mutation with
|
||||
// OwnedKBOrAdmin) but the UI shouldn't surface buttons the user has
|
||||
// no authority to use.
|
||||
//
|
||||
// The pin item is intentionally NOT gated by this predicate any more:
|
||||
// pin state is per (user, kb) as of migration 000050 and the backend
|
||||
// route only requires KB read access, so anyone who can see the card
|
||||
// should be able to pin it for themselves.
|
||||
//
|
||||
// Legacy KBs created before PR 5 have an empty creator_id; treat
|
||||
// those as tenant-owned (Admin+ may manage) so existing KBs aren't
|
||||
@@ -2042,15 +2050,6 @@ const handleUploadFinishedEvent = (event: Event) => {
|
||||
}
|
||||
}
|
||||
|
||||
.pin-indicator {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
left: 8px;
|
||||
color: var(--td-brand-color);
|
||||
z-index: 2;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.kb-favorite-star {
|
||||
position: absolute;
|
||||
top: 6px;
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -354,7 +354,13 @@ func RegisterKnowledgeBaseRoutes(r *gin.RouterGroup, handler *handler.KnowledgeB
|
||||
// 删除知识库 — 创建者本人 OR Admin+ 且对 KB 有 write 权限
|
||||
kb.DELETE("/:id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.DeleteKnowledgeBase)
|
||||
// 置顶/取消置顶知识库 — 创建者本人 OR Admin+ 且对 KB 有 write 权限
|
||||
kb.PUT("/:id/pin", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.TogglePinKnowledgeBase)
|
||||
// Pin state is now per-(user, kb) (migration 000050). Anyone with
|
||||
// at least Viewer-level read access to the KB — including users
|
||||
// who reached it via a shared agent — may pin it for themselves;
|
||||
// no edit permission is required. The OwnedKBOrAdmin guard was
|
||||
// removed accordingly. The route still requires KB read access
|
||||
// so callers can't poke at KBs they can't see.
|
||||
kb.PUT("/:id/pin", g.Viewer(), g.KBAccessRead("id"), handler.TogglePinKnowledgeBase)
|
||||
// 混合搜索 — Viewer+ 且对 KB 有 read 权限 (read-only)
|
||||
kb.GET("/:id/hybrid-search", g.Viewer(), g.KBAccessRead("id"), handler.HybridSearch)
|
||||
// 拷贝知识库 — Contributor+ (副本归调用者所有;不需要原 KB 的所有权)
|
||||
|
||||
@@ -6,6 +6,7 @@ package interfaces
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/hibiken/asynq"
|
||||
@@ -218,4 +219,20 @@ type KnowledgeBaseRepository interface {
|
||||
// scope on KnowledgeBase; implementations MUST NOT add an explicit
|
||||
// `deleted_at IS NULL` predicate (avoids divergence with the auto-scope).
|
||||
CountByVectorStoreID(ctx context.Context, db *gorm.DB, tenantID uint64, storeID string) (int64, error)
|
||||
// SetUserKBPin inserts or removes a row in user_kb_pins for the given
|
||||
// (tenant, user, kb) triple. Returns the resulting pinned_at (nil when
|
||||
// pinned=false) and an error. The tenant_id is captured to support
|
||||
// efficient "wipe a tenant" cleanups even though (user_id, kb_id)
|
||||
// alone would be unique in practice.
|
||||
SetUserKBPin(
|
||||
ctx context.Context, tenantID uint64, userID string, kbID string, pinned bool,
|
||||
) (pinnedAt *time.Time, err error)
|
||||
|
||||
// ListUserKBPinIDs returns the kb_id → pinned_at map of every KB the
|
||||
// given user has personally pinned in this tenant. Used by the list
|
||||
// path to stamp KnowledgeBase.IsPinned / PinnedAt without a per-row
|
||||
// roundtrip.
|
||||
ListUserKBPinIDs(
|
||||
ctx context.Context, tenantID uint64, userID string,
|
||||
) (map[string]time.Time, error)
|
||||
}
|
||||
|
||||
@@ -91,10 +91,18 @@ type KnowledgeBase struct {
|
||||
// IndexingStrategy controls which indexing pipelines are active for this knowledge base.
|
||||
// Pipelines: vector search, keyword search, wiki generation, knowledge graph extraction.
|
||||
IndexingStrategy IndexingStrategy `yaml:"indexing_strategy" json:"indexing_strategy" gorm:"column:indexing_strategy;type:json"`
|
||||
// Whether this knowledge base is pinned to the top of the list
|
||||
IsPinned bool `yaml:"is_pinned" json:"is_pinned" gorm:"default:false"`
|
||||
// Time when the knowledge base was pinned (nil if not pinned)
|
||||
PinnedAt *time.Time `yaml:"pinned_at" json:"pinned_at"`
|
||||
// IsPinned and PinnedAt are computed per-caller from user_kb_pins
|
||||
// (see migration 000050). They used to be stored on the row itself,
|
||||
// which made pinning a tenant-wide ordering decision gated behind
|
||||
// the kb-edit RBAC guard. The columns are still present in legacy
|
||||
// schemas for rollback safety but are no longer read or written by
|
||||
// the application — both fields are tagged `gorm:"-"` so GORM
|
||||
// ignores them on every CRUD call and the list handler stamps them
|
||||
// after enriching with the caller's pin set.
|
||||
IsPinned bool `yaml:"is_pinned" json:"is_pinned" gorm:"-"`
|
||||
// PinnedAt records when the current caller pinned this knowledge
|
||||
// base; nil when they have not.
|
||||
PinnedAt *time.Time `yaml:"pinned_at" json:"pinned_at" gorm:"-"`
|
||||
// Creation time of the knowledge base
|
||||
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
|
||||
// Last updated time of the knowledge base
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
DROP TABLE IF EXISTS tenant_invitations;
|
||||
DROP TABLE IF EXISTS user_kb_pins;
|
||||
DROP TABLE IF EXISTS user_resource_favorites;
|
||||
DROP TABLE IF EXISTS tenant_disabled_shared_agents;
|
||||
DROP TABLE IF EXISTS agent_shares;
|
||||
|
||||
@@ -319,6 +319,21 @@ CREATE INDEX IF NOT EXISTS idx_user_resource_favorites_user_tenant_type_created_
|
||||
CREATE INDEX IF NOT EXISTS idx_user_resource_favorites_tenant_id
|
||||
ON user_resource_favorites(tenant_id);
|
||||
|
||||
-- user_kb_pins — sqlite mirror of migration 000050. Per-(user, tenant)
|
||||
-- pinned knowledge bases; replaces the tenant-wide knowledge_bases.is_pinned
|
||||
-- column for ordering purposes. The legacy column on knowledge_bases is
|
||||
-- still defined above for back-compat with existing rows but is no longer
|
||||
-- written by the application.
|
||||
CREATE TABLE IF NOT EXISTS user_kb_pins (
|
||||
tenant_id INTEGER NOT NULL,
|
||||
user_id VARCHAR(36) NOT NULL,
|
||||
kb_id VARCHAR(36) NOT NULL,
|
||||
pinned_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (tenant_id, user_id, kb_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_kb_pins_user_tenant_pinned_at
|
||||
ON user_kb_pins(tenant_id, user_id, pinned_at DESC);
|
||||
|
||||
-- tenant_invitations — sqlite mirror of migration 000048. SQLite supports
|
||||
-- partial unique indexes too, so the same "one pending per (tenant,
|
||||
-- invitee)" guard can be applied verbatim.
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
-- Rollback: drop per-user KB pin mapping. The tenant-wide is_pinned /
|
||||
-- pinned_at columns on knowledge_bases were not modified by the up
|
||||
-- migration and continue to drive the legacy pin behaviour after this
|
||||
-- rollback runs.
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000050] Rollback: dropping user_kb_pins'; END $$;
|
||||
|
||||
DROP INDEX IF EXISTS idx_user_kb_pins_user_tenant_pinned_at;
|
||||
DROP TABLE IF EXISTS user_kb_pins;
|
||||
@@ -0,0 +1,53 @@
|
||||
-- Migration: 000050_user_kb_pins
|
||||
-- Per-(user, tenant, kb) pin state for the knowledge-base list.
|
||||
--
|
||||
-- Previously KB pinning lived on the `knowledge_bases.is_pinned` /
|
||||
-- `pinned_at` columns and was therefore tenant-wide: one admin's pin
|
||||
-- reordered the list for every member of the tenant, and the RBAC guard
|
||||
-- on PUT /knowledge-bases/:id/pin (OwnedKBOrAdmin) hid the affordance
|
||||
-- entirely from Viewer / Contributor users who could see the KB but not
|
||||
-- edit it. Both behaviours were confusing and inconsistent with the
|
||||
-- session-pin model (which has always been per-user).
|
||||
--
|
||||
-- This migration introduces a dedicated mapping table and backfills
|
||||
-- existing tenant-wide pins onto the KB's CreatorID, so the admin who
|
||||
-- pinned a KB still sees it pinned after upgrade while other tenant
|
||||
-- members get a clean per-user starting point. The legacy columns on
|
||||
-- knowledge_bases are left in place for one release to keep rollback
|
||||
-- safe; new code stops writing them and reads pin state from this
|
||||
-- table instead.
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000050] Creating table: user_kb_pins'; END $$;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_kb_pins (
|
||||
tenant_id BIGINT NOT NULL,
|
||||
user_id VARCHAR(36) NOT NULL,
|
||||
kb_id VARCHAR(36) NOT NULL,
|
||||
pinned_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (tenant_id, user_id, kb_id)
|
||||
);
|
||||
|
||||
-- Primary read path: "give me this user's pinned KB ids in this tenant,
|
||||
-- newest pin first". The PK already covers equality on (tenant_id,
|
||||
-- user_id, kb_id); the secondary index lets us avoid an in-memory sort
|
||||
-- when stamping the list response.
|
||||
CREATE INDEX IF NOT EXISTS idx_user_kb_pins_user_tenant_pinned_at
|
||||
ON user_kb_pins (tenant_id, user_id, pinned_at DESC);
|
||||
|
||||
-- Backfill: every KB that is currently pinned at the tenant level gets
|
||||
-- carried over as a personal pin for its creator. KBs whose creator_id
|
||||
-- is empty / NULL (legacy rows that predate the RBAC migration) are
|
||||
-- intentionally skipped — we have no user to attribute the pin to, and
|
||||
-- silently dropping these is preferable to attributing them to a tenant
|
||||
-- owner who may not actually want the KB pinned in their view.
|
||||
INSERT INTO user_kb_pins (tenant_id, user_id, kb_id, pinned_at)
|
||||
SELECT kb.tenant_id,
|
||||
kb.creator_id,
|
||||
kb.id,
|
||||
COALESCE(kb.pinned_at, CURRENT_TIMESTAMP)
|
||||
FROM knowledge_bases kb
|
||||
WHERE kb.is_pinned = TRUE
|
||||
AND kb.creator_id IS NOT NULL
|
||||
AND kb.creator_id <> ''
|
||||
ON CONFLICT (tenant_id, user_id, kb_id) DO NOTHING;
|
||||
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000050] user_kb_pins table ready'; END $$;
|
||||
Reference in New Issue
Block a user