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:
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -108,6 +108,11 @@ func (h *Handler) CreateSession(c *gin.Context) {
|
||||
Title: request.Title,
|
||||
Description: request.Description,
|
||||
}
|
||||
// Attach the calling user as the session owner when available.
|
||||
// API-key / legacy callers without a user id fall back to tenant-level visibility.
|
||||
if userID, ok := types.UserIDFromContext(ctx); ok {
|
||||
createdSession.UserID = userID
|
||||
}
|
||||
|
||||
// Call service to create session
|
||||
logger.Infof(ctx, "Calling session service to create session")
|
||||
@@ -175,12 +180,15 @@ func (h *Handler) GetSession(c *gin.Context) {
|
||||
|
||||
// GetSessionsByTenant godoc
|
||||
// @Summary 获取会话列表
|
||||
// @Description 获取当前租户的会话列表,支持分页
|
||||
// @Description 获取当前租户的会话列表,支持分页、关键字搜索、按来源/Agent 筛选
|
||||
// @Tags 会话
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param page query int false "页码"
|
||||
// @Param page_size query int false "每页数量"
|
||||
// @Param page query int false "页码"
|
||||
// @Param page_size query int false "每页数量"
|
||||
// @Param keyword query string false "标题模糊搜索"
|
||||
// @Param source query string false "来源过滤:web / feishu / wechat / slack / ..."
|
||||
// @Param agent_id query string false "按 Agent 过滤(仅对 IM 会话生效)"
|
||||
// @Success 200 {object} map[string]interface{} "会话列表"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Security Bearer
|
||||
@@ -197,6 +205,36 @@ func (h *Handler) GetSessionsByTenant(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
keyword := c.Query("keyword")
|
||||
source := c.Query("source")
|
||||
agentID := c.Query("agent_id")
|
||||
|
||||
// When the caller uses any of the new filter knobs, return enriched items
|
||||
// (with IM origin fields). Otherwise keep the legacy response so existing
|
||||
// clients are unaffected.
|
||||
if keyword != "" || source != "" || agentID != "" {
|
||||
result, err := h.sessionService.ListSessions(ctx, &types.SessionListQuery{
|
||||
Keyword: keyword,
|
||||
Source: source,
|
||||
AgentID: agentID,
|
||||
Page: pagination.Page,
|
||||
PageSize: pagination.PageSize,
|
||||
})
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": result.Data,
|
||||
"total": result.Total,
|
||||
"page": result.Page,
|
||||
"page_size": result.PageSize,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Use paginated query to get sessions
|
||||
result, err := h.sessionService.GetPagedSessionsByTenant(ctx, &pagination)
|
||||
if err != nil {
|
||||
@@ -441,3 +479,58 @@ func (h *Handler) BatchDeleteSessions(c *gin.Context) {
|
||||
"message": "Sessions deleted successfully",
|
||||
})
|
||||
}
|
||||
|
||||
// PinSession godoc
|
||||
// @Summary 置顶会话
|
||||
// @Description 将指定会话置顶(用户维度)
|
||||
// @Tags 会话
|
||||
// @Produce json
|
||||
// @Param id path string true "会话ID"
|
||||
// @Success 200 {object} map[string]interface{} "置顶成功"
|
||||
// @Failure 404 {object} errors.AppError "会话不存在"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /sessions/{id}/pin [post]
|
||||
func (h *Handler) PinSession(c *gin.Context) {
|
||||
h.setSessionPinned(c, true)
|
||||
}
|
||||
|
||||
// UnpinSession godoc
|
||||
// @Summary 取消置顶会话
|
||||
// @Description 取消指定会话的置顶
|
||||
// @Tags 会话
|
||||
// @Produce json
|
||||
// @Param id path string true "会话ID"
|
||||
// @Success 200 {object} map[string]interface{} "取消置顶成功"
|
||||
// @Failure 404 {object} errors.AppError "会话不存在"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /sessions/{id}/pin [delete]
|
||||
func (h *Handler) UnpinSession(c *gin.Context) {
|
||||
h.setSessionPinned(c, false)
|
||||
}
|
||||
|
||||
func (h *Handler) setSessionPinned(c *gin.Context, pinned bool) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Session ID is empty")
|
||||
c.Error(errors.NewBadRequestError(errors.ErrInvalidSessionID.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.sessionService.SetSessionPinned(ctx, id, pinned); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"session_id": id,
|
||||
"pinned": pinned,
|
||||
})
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"is_pinned": pinned,
|
||||
})
|
||||
}
|
||||
|
||||
+48
-10
@@ -1336,6 +1336,51 @@ func (s *Service) resolveSession(ctx context.Context, msg *IncomingMessage, tena
|
||||
}
|
||||
}
|
||||
|
||||
// buildUserSessionTitle produces a human-distinguishable title for a user-mode
|
||||
// IM session. Platform adapters only surface ChatID, not a readable chat name,
|
||||
// so we fall back to short ID suffixes to keep group/DM sessions visually distinct.
|
||||
func buildUserSessionTitle(msg *IncomingMessage) string {
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "[%s] ", msg.Platform)
|
||||
if msg.UserName != "" {
|
||||
b.WriteString(msg.UserName)
|
||||
} else if msg.UserID != "" {
|
||||
b.WriteString("user ")
|
||||
b.WriteString(shortID(msg.UserID))
|
||||
} else {
|
||||
b.WriteString("user")
|
||||
}
|
||||
if msg.ChatType == ChatTypeGroup && msg.ChatID != "" {
|
||||
fmt.Fprintf(&b, " · group %s", shortID(msg.ChatID))
|
||||
} else if msg.ChatType == ChatTypeDirect {
|
||||
b.WriteString(" · dm")
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// buildThreadSessionTitle produces a title for a thread-mode IM session.
|
||||
// In thread mode different users can share one session, so the user name is
|
||||
// omitted and chat/thread IDs carry the distinguishing information.
|
||||
func buildThreadSessionTitle(msg *IncomingMessage) string {
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "[%s] ", msg.Platform)
|
||||
if msg.ChatID != "" {
|
||||
fmt.Fprintf(&b, "chat %s · ", shortID(msg.ChatID))
|
||||
}
|
||||
b.WriteString("thread ")
|
||||
b.WriteString(shortID(msg.ThreadID))
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// shortID returns the last 8 characters of id, or id itself when shorter.
|
||||
// Used to keep long platform IDs readable inside titles without losing uniqueness.
|
||||
func shortID(id string) string {
|
||||
if len(id) > 8 {
|
||||
return id[len(id)-8:]
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// resolveUserSession finds or creates a ChannelSession keyed by (platform, user_id, chat_id, tenant_id, agent_id).
|
||||
// This is the original session resolution strategy.
|
||||
func (s *Service) resolveUserSession(ctx context.Context, msg *IncomingMessage, tenantID uint64, agentID string, imChannelID string) (*ChannelSession, error) {
|
||||
@@ -1353,10 +1398,7 @@ func (s *Service) resolveUserSession(ctx context.Context, msg *IncomingMessage,
|
||||
}
|
||||
|
||||
// Create a new WeKnora session
|
||||
title := fmt.Sprintf("IM-%s", msg.Platform)
|
||||
if msg.UserName != "" {
|
||||
title = fmt.Sprintf("IM-%s-%s", msg.Platform, msg.UserName)
|
||||
}
|
||||
title := buildUserSessionTitle(msg)
|
||||
|
||||
newSession := &types.Session{
|
||||
TenantID: tenantID,
|
||||
@@ -1427,12 +1469,8 @@ func (s *Service) resolveThreadSession(ctx context.Context, msg *IncomingMessage
|
||||
return nil, fmt.Errorf("query thread session: %w", result.Error)
|
||||
}
|
||||
|
||||
// Build a session title with thread ID suffix for traceability.
|
||||
threadSuffix := threadID
|
||||
if len(threadSuffix) > 8 {
|
||||
threadSuffix = threadSuffix[len(threadSuffix)-8:]
|
||||
}
|
||||
title := fmt.Sprintf("IM-%s-thread-%s", msg.Platform, threadSuffix)
|
||||
// Build a session title including chat + thread suffix for traceability.
|
||||
title := buildThreadSessionTitle(msg)
|
||||
|
||||
newSession := &types.Session{
|
||||
TenantID: tenantID,
|
||||
|
||||
@@ -336,6 +336,8 @@ func RegisterSessionRoutes(r *gin.RouterGroup, handler *session.Handler) {
|
||||
sessions.DELETE("/:id/messages", handler.ClearSessionMessages)
|
||||
sessions.POST("/:session_id/generate_title", handler.GenerateTitle)
|
||||
sessions.POST("/:session_id/stop", handler.StopSession)
|
||||
sessions.POST("/:id/pin", handler.PinSession)
|
||||
sessions.DELETE("/:id/pin", handler.UnpinSession)
|
||||
// 继续接收活跃流
|
||||
sessions.GET("/continue-stream/:session_id", handler.ContinueStream)
|
||||
}
|
||||
|
||||
@@ -25,6 +25,11 @@ type SessionService interface {
|
||||
BatchDeleteSessions(ctx context.Context, ids []string) error
|
||||
// DeleteAllSessions deletes all sessions for the current tenant
|
||||
DeleteAllSessions(ctx context.Context) error
|
||||
// ListSessions returns a page of sessions for the current tenant/user with
|
||||
// search/source filters and pin-aware ordering. User scope is pulled from ctx.
|
||||
ListSessions(ctx context.Context, query *types.SessionListQuery) (*types.PageResult, error)
|
||||
// SetSessionPinned pins or unpins the session for the current user scope.
|
||||
SetSessionPinned(ctx context.Context, sessionID string, pinned bool) error
|
||||
// GenerateTitle generates a title for the current conversation
|
||||
// modelID: optional model ID to use for title generation (if empty, uses first available KnowledgeQA model)
|
||||
GenerateTitle(ctx context.Context, session *types.Session, messages []types.Message, modelID string) (string, error)
|
||||
@@ -57,8 +62,13 @@ type SessionRepository interface {
|
||||
GetByTenantID(ctx context.Context, tenantID uint64) ([]*types.Session, error)
|
||||
// GetPagedByTenantID gets paged sessions of a tenant
|
||||
GetPagedByTenantID(ctx context.Context, tenantID uint64, page *types.Pagination) ([]*types.Session, int64, error)
|
||||
// QueryPaged lists sessions with filters, user-scoped ownership and pin-aware ordering.
|
||||
QueryPaged(ctx context.Context, q *types.SessionListQuery) ([]*types.SessionListItem, int64, error)
|
||||
// Update updates a session
|
||||
Update(ctx context.Context, session *types.Session) error
|
||||
// SetPinned pins or unpins a session row scoped by tenant.
|
||||
// userID, when non-empty, is enforced so users cannot pin sessions they don't own.
|
||||
SetPinned(ctx context.Context, tenantID uint64, userID string, id string, pinned bool) error
|
||||
// Delete deletes a session
|
||||
Delete(ctx context.Context, tenantID uint64, id string) error
|
||||
// BatchDelete deletes multiple sessions by IDs
|
||||
|
||||
@@ -81,6 +81,13 @@ type Session struct {
|
||||
Description string `json:"description"`
|
||||
// Tenant ID
|
||||
TenantID uint64 `json:"tenant_id" gorm:"index"`
|
||||
// UserID is the owner of the session. Empty for legacy rows (visible at
|
||||
// tenant level) and for IM-created sessions that do not map to a WeKnora user.
|
||||
UserID string `json:"user_id,omitempty" gorm:"type:varchar(36);index"`
|
||||
// IsPinned indicates whether the session is pinned in the list.
|
||||
IsPinned bool `json:"is_pinned" gorm:"default:false"`
|
||||
// PinnedAt records when the session was pinned; nil when not pinned.
|
||||
PinnedAt *time.Time `json:"pinned_at,omitempty"`
|
||||
|
||||
// // Strategy configuration
|
||||
// KnowledgeBaseID string `json:"knowledge_base_id"` // 关联的知识库ID
|
||||
@@ -112,6 +119,34 @@ func (s *Session) BeforeCreate(tx *gorm.DB) (err error) {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SessionListQuery bundles the parameters for listing sessions.
|
||||
// UserID empty means "tenant-wide" (used by API-key callers / legacy rows).
|
||||
// Keyword matches title ILIKE '%keyword%'.
|
||||
// Source values: "web" (no IM mapping) or an IM platform name (e.g. "feishu", "wechat").
|
||||
// AgentID currently only filters sessions that have an IM channel mapping.
|
||||
type SessionListQuery struct {
|
||||
TenantID uint64
|
||||
UserID string
|
||||
Keyword string
|
||||
Source string
|
||||
AgentID string
|
||||
Page int
|
||||
PageSize int
|
||||
}
|
||||
|
||||
// SessionListItem is a session row enriched with its IM origin (when any).
|
||||
// IM-related fields are populated from the im_channel_sessions table via LEFT JOIN
|
||||
// and are empty for Web-created sessions.
|
||||
type SessionListItem struct {
|
||||
Session
|
||||
IMPlatform string `json:"im_platform,omitempty" gorm:"column:im_platform"`
|
||||
IMChatID string `json:"im_chat_id,omitempty" gorm:"column:im_chat_id"`
|
||||
IMThreadID string `json:"im_thread_id,omitempty" gorm:"column:im_thread_id"`
|
||||
IMUserID string `json:"im_user_id,omitempty" gorm:"column:im_user_id"`
|
||||
IMAgentID string `json:"im_agent_id,omitempty" gorm:"column:im_agent_id"`
|
||||
IMChannelID string `json:"im_channel_id,omitempty" gorm:"column:im_channel_id"`
|
||||
}
|
||||
|
||||
// StringArray represents a list of strings
|
||||
type StringArray []string
|
||||
|
||||
|
||||
Reference in New Issue
Block a user