feat: Phase 8.5 — ConversationSummary 查询优化,支持 SQL 聚合获取消息统计

This commit is contained in:
hhs
2026-06-14 17:58:42 +08:00
parent 7b745018c5
commit c3a32ce276
3 changed files with 77 additions and 6 deletions

View File

@@ -187,12 +187,13 @@ func (m *MemoryManager) UpdateTitle(_ context.Context, sessionID string, title s
}
// ListByUser 获取用户的对话列表(分页,按 UpdatedAt 降序)。
func (m *MemoryManager) ListByUser(_ context.Context, userID string, page, size int) ([]ConversationSummary, int, error) {
// 若配置了 MessageRepository消息统计从 PostgreSQL 聚合查询(更准确)。
func (m *MemoryManager) ListByUser(ctx context.Context, userID string, page, size int) ([]ConversationSummary, int, error) {
m.mu.RLock()
defer m.mu.RUnlock()
// 收集该用户的所有 session
var list []ConversationSummary
var sessionIDs []string
for _, entry := range m.sessions {
if entry.session.UserID != userID {
continue
@@ -201,15 +202,32 @@ func (m *MemoryManager) ListByUser(_ context.Context, userID string, page, size
continue
}
summary := ConversationSummary{
ID: entry.session.ID,
Title: entry.session.Title,
MessageCount: len(entry.history),
UpdatedAt: entry.lastActive,
ID: entry.session.ID,
Title: entry.session.Title,
UpdatedAt: entry.lastActive,
}
// 先用内存值填充,后续可能被 PG 统计覆盖
summary.MessageCount = len(entry.history)
if len(entry.history) > 0 {
summary.LastMessage = entry.history[len(entry.history)-1].Content
}
list = append(list, summary)
sessionIDs = append(sessionIDs, entry.session.ID)
}
m.mu.RUnlock()
// 若配置了 msgRepo从 PostgreSQL 获取更准确的消息统计
if m.msgRepo != nil && len(sessionIDs) > 0 {
if stats, err := m.msgRepo.GetSessionMessageStats(ctx, sessionIDs); err == nil {
for i := range list {
if s, ok := stats[list[i].ID]; ok {
list[i].LastMessage = s.LastMessage
list[i].MessageCount = s.MessageCount
}
}
} else {
logger.Log.Warnw("get session message stats failed, falling back to in-memory", "error", err)
}
}
// 按 UpdatedAt 降序排序