feat(sessions): add keyword search, user-scoped pinning, and IM source visibility

Sessions today are a flat list ordered by updated_at. Two gaps showed up in
practice:
- Users cannot find specific chats as the list grows beyond a screen.
- IM-created sessions (WeCom/Feishu/Slack/...) are indistinguishable:
  every title was "IM-<platform>" or "IM-<platform>-<username>" and the
  list API hid the underlying im_channel_sessions mapping, so admins had
  no way to tell which Feishu group a session came from.

Backend
- Migration 000039 adds sessions.user_id (owner), is_pinned, pinned_at
  plus a composite index for the list query. Existing rows keep user_id
  NULL and stay visible at the tenant level for backward compatibility.
- CreateSession now writes the caller's user_id from auth context.
- GET /sessions accepts keyword / source / agent_id. When any filter is
  set, the response switches to enriched items that LEFT JOIN
  im_channel_sessions and expose im_platform / im_chat_id / im_thread_id
  / im_user_id / im_agent_id / im_channel_id. No filters => legacy shape,
  existing clients unaffected.
- Ordering: is_pinned DESC, pinned_at DESC NULLS LAST, updated_at DESC.
- POST/DELETE /sessions/:id/pin for user-scoped pin/unpin.
- IM session titles: "[platform] <user|chat|thread>" with short ID
  suffixes so group/DM/thread sessions are visually distinct without
  needing a round-trip to fetch a display name from the IM adapter.

Frontend
- Search input debounced at 300ms drives the keyword filter.
- Pinned chats render in a dedicated group above the time-based groups,
  with a pin icon and a pin/unpin entry in the per-chat dropdown.
- IM chats get a short [platform] badge in the list.
- Pin toggle is optimistic and guards against double-clicks.
- zh/en/ko/ru i18n keys added for the new strings.
This commit is contained in:
wizardchen
2026-04-30 15:14:49 +08:00
committed by lyingbug
parent e029d31f86
commit dbd804d6e3
15 changed files with 564 additions and 38 deletions
+104
View File
@@ -2,6 +2,7 @@ package repository
import (
"context"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/types"
@@ -77,6 +78,109 @@ func (r *sessionRepository) GetPagedByTenantID(
return sessions, total, nil
}
// QueryPaged lists sessions for tenant/user with keyword/source/agent filters,
// pin-aware ordering, and IM origin fields from a LEFT JOIN.
func (r *sessionRepository) QueryPaged(
ctx context.Context, q *types.SessionListQuery,
) ([]*types.SessionListItem, int64, error) {
// Base filter shared by count and list queries.
applyBase := func(db *gorm.DB) *gorm.DB {
db = db.Where("s.tenant_id = ? AND s.deleted_at IS NULL", q.TenantID)
if q.UserID != "" {
db = db.Where("(s.user_id = ? OR s.user_id IS NULL OR s.user_id = '')", q.UserID)
}
if kw := strings.TrimSpace(q.Keyword); kw != "" {
db = db.Where("s.title ILIKE ?", "%"+kw+"%")
}
return db
}
// LEFT JOIN IM mappings to surface origin fields and support source/agent filters.
joinClause := "LEFT JOIN im_channel_sessions ics ON ics.session_id = s.id AND ics.deleted_at IS NULL"
applySource := func(db *gorm.DB) *gorm.DB {
switch strings.ToLower(strings.TrimSpace(q.Source)) {
case "":
return db
case "web":
return db.Where("ics.id IS NULL")
default:
return db.Where("ics.platform = ?", strings.ToLower(q.Source))
}
}
applyAgent := func(db *gorm.DB) *gorm.DB {
if q.AgentID != "" {
return db.Where("ics.agent_id = ?", q.AgentID)
}
return db
}
// Count distinct sessions to guard against fan-out from the join.
var total int64
countQ := applyAgent(applySource(applyBase(
r.db.WithContext(ctx).Table("sessions AS s").Joins(joinClause),
)))
if err := countQ.Distinct("s.id").Count(&total).Error; err != nil {
return nil, 0, err
}
page := q.Page
if page < 1 {
page = 1
}
size := q.PageSize
if size < 1 {
size = 20
}
items := make([]*types.SessionListItem, 0)
rowsQ := applyAgent(applySource(applyBase(
r.db.WithContext(ctx).Table("sessions AS s").Joins(joinClause),
))).
Select(`s.*,
ics.platform AS im_platform,
ics.chat_id AS im_chat_id,
ics.thread_id AS im_thread_id,
ics.user_id AS im_user_id,
ics.agent_id AS im_agent_id,
ics.im_channel_id AS im_channel_id`).
Order("s.is_pinned DESC, s.pinned_at DESC NULLS LAST, s.updated_at DESC").
Offset((page - 1) * size).
Limit(size)
if err := rowsQ.Find(&items).Error; err != nil {
return nil, 0, err
}
return items, total, nil
}
// SetPinned toggles is_pinned/pinned_at for a single session.
// Scope: must match tenant, and user_id (when provided) to prevent pinning
// other users' sessions. Legacy rows with user_id NULL/'' remain mutable
// at the tenant level (same visibility rule as QueryPaged).
func (r *sessionRepository) SetPinned(
ctx context.Context, tenantID uint64, userID string, id string, pinned bool,
) error {
now := time.Now()
updates := map[string]interface{}{
"is_pinned": pinned,
"updated_at": now,
}
if pinned {
updates["pinned_at"] = now
} else {
updates["pinned_at"] = nil
}
q := r.db.WithContext(ctx).
Model(&types.Session{}).
Where("tenant_id = ? AND id = ?", tenantID, id)
if userID != "" {
q = q.Where("(user_id = ? OR user_id IS NULL OR user_id = '')", userID)
}
return q.Updates(updates).Error
}
// Update updates a session
func (r *sessionRepository) Update(ctx context.Context, session *types.Session) error {
session.UpdatedAt = time.Now()
+41
View File
@@ -169,6 +169,47 @@ func (s *sessionService) GetPagedSessionsByTenant(ctx context.Context,
return types.NewPageResult(total, pagination, sessions), nil
}
// ListSessions returns a page of sessions with search/source filters, scoped to
// the current tenant (and user when the caller is an authenticated user).
func (s *sessionService) ListSessions(
ctx context.Context, query *types.SessionListQuery,
) (*types.PageResult, error) {
if query == nil {
query = &types.SessionListQuery{}
}
query.TenantID = types.MustTenantIDFromContext(ctx)
if uid, ok := types.UserIDFromContext(ctx); ok {
query.UserID = uid
}
items, total, err := s.sessionRepo.QueryPaged(ctx, query)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": query.TenantID,
"user_id": query.UserID,
"keyword": query.Keyword,
"source": query.Source,
"agent_id": query.AgentID,
})
return nil, err
}
pagination := &types.Pagination{Page: query.Page, PageSize: query.PageSize}
return types.NewPageResult(total, pagination, items), nil
}
// SetSessionPinned pins or unpins a session for the current user scope.
func (s *sessionService) SetSessionPinned(
ctx context.Context, sessionID string, pinned bool,
) error {
if sessionID == "" {
return errors.New("session id is required")
}
tenantID := types.MustTenantIDFromContext(ctx)
userID, _ := types.UserIDFromContext(ctx)
return s.sessionRepo.SetPinned(ctx, tenantID, userID, sessionID, pinned)
}
// UpdateSession updates an existing session's properties
func (s *sessionService) UpdateSession(ctx context.Context, session *types.Session) error {
// Validate session ID