[NELO-1102] feat(im): add thread-based session mode for IM channels
Add session_mode ("user" | "thread") to IM channel config. In thread
mode, each message thread gets its own session, enabling multi-user
collaboration within the same thread context.
Backend:
- Add SessionMode type constants and validation
- Add ThreadID field to IncomingMessage and ChannelSession
- Split resolveSession into resolveUserSession/resolveThreadSession
- Update makeUserKey to include threadID only in thread mode
- Extract ThreadID in Slack, Mattermost, Feishu, Telegram adapters
- Add message_thread_id to Telegram SendReply/StartStream for Forums
- DB migration 000028: session_mode column + thread_id column + index
Frontend:
- Add session_mode radio group to IMChannelPanel dialog
- Auto-reset session_mode when switching to non-thread platform
- Show thread badge on channel card for thread-mode channels
- Add i18n keys for en-US, ko-KR, zh-CN, ru-RU
This commit is contained in:
+115
-13
@@ -151,7 +151,12 @@ type Service struct {
|
||||
|
||||
// makeUserKey builds the canonical key used to identify a user's request
|
||||
// across the queue, inflight map, and /stop command.
|
||||
func makeUserKey(channelID, userID, chatID string) string {
|
||||
// threadID should only be non-empty when channel.SessionMode == "thread";
|
||||
// callers must guard this to avoid leaking thread scope into user-mode keys.
|
||||
func makeUserKey(channelID, userID, chatID, threadID string) string {
|
||||
if threadID != "" {
|
||||
return fmt.Sprintf("%s:%s:%s:%s", channelID, userID, chatID, threadID)
|
||||
}
|
||||
return fmt.Sprintf("%s:%s:%s", channelID, userID, chatID)
|
||||
}
|
||||
|
||||
@@ -716,6 +721,7 @@ func (s *Service) HandleMessage(ctx context.Context, msg *IncomingMessage, chann
|
||||
attribute.String("im.platform", string(msg.Platform)),
|
||||
attribute.String("im.user_id", msg.UserID),
|
||||
attribute.String("im.chat_id", msg.ChatID),
|
||||
attribute.String("im.thread_id", msg.ThreadID),
|
||||
attribute.String("im.message_type", string(msg.MessageType)),
|
||||
)
|
||||
|
||||
@@ -752,12 +758,21 @@ func (s *Service) HandleMessage(ctx context.Context, msg *IncomingMessage, chann
|
||||
}
|
||||
}
|
||||
|
||||
span.SetAttributes(attribute.String("im.session_mode", channel.SessionMode))
|
||||
|
||||
// Resolve threadID for key building — only include in thread mode to avoid
|
||||
// leaking thread scope into user-mode rate limit / inflight keys.
|
||||
threadID := ""
|
||||
if channel.SessionMode == string(SessionModeThread) {
|
||||
threadID = msg.ThreadID
|
||||
}
|
||||
|
||||
// Rate limit: enforce per-user sliding window to prevent abuse.
|
||||
// Slash-commands (/stop, /clear, etc.) bypass rate limiting so the user
|
||||
// always retains control over the bot even under heavy messaging.
|
||||
isCommand := s.cmdRegistry.IsRegistered(msg.Content)
|
||||
if !isCommand {
|
||||
rateLimitKey := makeUserKey(channelID, msg.UserID, msg.ChatID)
|
||||
rateLimitKey := makeUserKey(channelID, msg.UserID, msg.ChatID, threadID)
|
||||
if !s.rateLimiter.Allow(rateLimitKey) {
|
||||
logger.Warnf(ctx, "[IM] Rate limited: channel=%s user=%s chat=%s", channelID, msg.UserID, msg.ChatID)
|
||||
_ = adapter.SendReply(ctx, msg, &ReplyMessage{
|
||||
@@ -792,7 +807,7 @@ func (s *Service) HandleMessage(ctx context.Context, msg *IncomingMessage, chann
|
||||
sessionCtx = context.WithValue(sessionCtx, types.TenantInfoContextKey, tenant)
|
||||
|
||||
// 2. Resolve or create a WeKnora session
|
||||
channelSession, err := s.resolveSession(sessionCtx, msg, tenantID, agentID, channelID)
|
||||
channelSession, err := s.resolveSession(sessionCtx, msg, tenantID, agentID, channelID, channel.SessionMode)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve session: %w", err)
|
||||
}
|
||||
@@ -831,7 +846,7 @@ func (s *Service) HandleMessage(ctx context.Context, msg *IncomingMessage, chann
|
||||
// 5. Enqueue the QA request into the bounded worker pool.
|
||||
// The worker pool controls LLM concurrency and provides backpressure.
|
||||
qaCtx, qaCancel := context.WithCancel(sessionCtx)
|
||||
userKey := makeUserKey(channelID, msg.UserID, msg.ChatID)
|
||||
userKey := makeUserKey(channelID, msg.UserID, msg.ChatID, threadID)
|
||||
|
||||
req := &qaRequest{
|
||||
ctx: qaCtx,
|
||||
@@ -1000,7 +1015,11 @@ func (s *Service) handleCommand(
|
||||
logger.Warnf(ctx, "[IM] Failed to clear session context: %v", err)
|
||||
}
|
||||
case ActionStop:
|
||||
inflightKey := makeUserKey(channel.ID, msg.UserID, msg.ChatID)
|
||||
stopThreadID := ""
|
||||
if channel.SessionMode == string(SessionModeThread) {
|
||||
stopThreadID = msg.ThreadID
|
||||
}
|
||||
inflightKey := makeUserKey(channel.ID, msg.UserID, msg.ChatID, stopThreadID)
|
||||
|
||||
// 1. Try local cancel: remove from queue or cancel in-flight.
|
||||
var localSessionID, localMessageID string
|
||||
@@ -1080,9 +1099,20 @@ func (s *Service) sendStreamReply(ctx context.Context, msg *IncomingMessage, str
|
||||
return nil
|
||||
}
|
||||
|
||||
// resolveSession finds or creates a ChannelSession for the given IM message.
|
||||
// ctx must already carry TenantIDContextKey and TenantInfoContextKey.
|
||||
func (s *Service) resolveSession(ctx context.Context, msg *IncomingMessage, tenantID uint64, agentID string, imChannelID string) (*ChannelSession, error) {
|
||||
// resolveSession dispatches to the appropriate session resolution strategy
|
||||
// based on the channel's session mode.
|
||||
func (s *Service) resolveSession(ctx context.Context, msg *IncomingMessage, tenantID uint64, agentID string, imChannelID string, sessionMode string) (*ChannelSession, error) {
|
||||
switch SessionMode(sessionMode) {
|
||||
case SessionModeThread:
|
||||
return s.resolveThreadSession(ctx, msg, tenantID, agentID, imChannelID)
|
||||
default: // SessionModeUser
|
||||
return s.resolveUserSession(ctx, msg, tenantID, agentID, imChannelID)
|
||||
}
|
||||
}
|
||||
|
||||
// resolveUserSession finds or creates a ChannelSession keyed by (platform, user_id, chat_id, tenant_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) {
|
||||
var cs ChannelSession
|
||||
result := s.db.Where("platform = ? AND user_id = ? AND chat_id = ? AND tenant_id = ? AND deleted_at IS NULL",
|
||||
string(msg.Platform), msg.UserID, msg.ChatID, tenantID).
|
||||
@@ -1125,14 +1155,9 @@ func (s *Service) resolveSession(ctx context.Context, msg *IncomingMessage, tena
|
||||
IMChannelID: imChannelID,
|
||||
}
|
||||
if err := s.db.Create(&cs).Error; err != nil {
|
||||
// The insert failed (likely unique constraint from a concurrent request on
|
||||
// another instance). Clean up the orphaned Session we just created — it has
|
||||
// no messages yet, so a direct delete is safe.
|
||||
if delErr := s.db.Where("id = ?", createdSession.ID).Delete(createdSession).Error; delErr != nil {
|
||||
logger.Warnf(ctx, "[IM] Failed to clean up orphaned session %s: %v", createdSession.ID, delErr)
|
||||
}
|
||||
|
||||
// Fetch the existing ChannelSession created by the winning instance.
|
||||
var existing ChannelSession
|
||||
if findErr := s.db.Where("platform = ? AND user_id = ? AND chat_id = ? AND tenant_id = ? AND deleted_at IS NULL",
|
||||
string(msg.Platform), msg.UserID, msg.ChatID, tenantID).
|
||||
@@ -1148,6 +1173,83 @@ func (s *Service) resolveSession(ctx context.Context, msg *IncomingMessage, tena
|
||||
return &cs, nil
|
||||
}
|
||||
|
||||
// resolveThreadSession finds or creates a ChannelSession keyed by (platform, chat_id, thread_id, tenant_id).
|
||||
// In thread mode, each message thread gets its own session. Multiple users in the
|
||||
// same thread share the same session. Top-level messages use their own ID as
|
||||
// ThreadID, creating a new session per top-level message.
|
||||
func (s *Service) resolveThreadSession(ctx context.Context, msg *IncomingMessage, tenantID uint64, agentID string, imChannelID string) (*ChannelSession, error) {
|
||||
threadID := msg.ThreadID
|
||||
if threadID == "" {
|
||||
// Defense-in-depth: frontend blocks thread mode for unsupported platforms,
|
||||
// but if ThreadID is somehow empty, fall back to user-mode resolution
|
||||
// to avoid creating a shared session for all empty-thread messages.
|
||||
logger.Warnf(ctx, "[IM] Thread mode but ThreadID is empty (platform=%s chat=%s), falling back to user session", msg.Platform, msg.ChatID)
|
||||
return s.resolveUserSession(ctx, msg, tenantID, agentID, imChannelID)
|
||||
}
|
||||
|
||||
var cs ChannelSession
|
||||
result := s.db.Where(
|
||||
"platform = ? AND chat_id = ? AND thread_id = ? AND tenant_id = ? AND deleted_at IS NULL",
|
||||
string(msg.Platform), threadID, msg.ChatID, tenantID,
|
||||
).First(&cs)
|
||||
|
||||
if result.Error == nil {
|
||||
return &cs, nil
|
||||
}
|
||||
|
||||
if result.Error != gorm.ErrRecordNotFound {
|
||||
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)
|
||||
|
||||
newSession := &types.Session{
|
||||
TenantID: tenantID,
|
||||
Title: title,
|
||||
Description: fmt.Sprintf("Thread-based session from %s IM", msg.Platform),
|
||||
}
|
||||
|
||||
createdSession, err := s.sessionService.CreateSession(ctx, newSession)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create session: %w", err)
|
||||
}
|
||||
|
||||
cs = ChannelSession{
|
||||
Platform: string(msg.Platform),
|
||||
UserID: msg.UserID, // record the first creator
|
||||
ChatID: msg.ChatID,
|
||||
ThreadID: threadID,
|
||||
SessionID: createdSession.ID,
|
||||
TenantID: tenantID,
|
||||
AgentID: agentID,
|
||||
IMChannelID: imChannelID,
|
||||
}
|
||||
|
||||
if err := s.db.Create(&cs).Error; err != nil {
|
||||
// Unique constraint fallback for concurrent creation.
|
||||
if delErr := s.db.Where("id = ?", createdSession.ID).Delete(createdSession).Error; delErr != nil {
|
||||
logger.Warnf(ctx, "[IM] Failed to clean up orphaned session %s: %v", createdSession.ID, delErr)
|
||||
}
|
||||
var existing ChannelSession
|
||||
if findErr := s.db.Where(
|
||||
"platform = ? AND chat_id = ? AND thread_id = ? AND tenant_id = ? AND deleted_at IS NULL",
|
||||
string(msg.Platform), msg.ChatID, threadID, tenantID,
|
||||
).First(&existing).Error; findErr != nil {
|
||||
return nil, fmt.Errorf("create thread session: %w (lookup fallback: %v)", err, findErr)
|
||||
}
|
||||
return &existing, nil
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[IM] Created new thread session: platform=%s thread=%s chat=%s -> session=%s",
|
||||
msg.Platform, threadID, msg.ChatID, createdSession.ID)
|
||||
return &cs, nil
|
||||
}
|
||||
|
||||
// ── Agent tool call progress formatting ──────────────────────────────
|
||||
// These helpers format tool-call / tool-result events as Markdown text
|
||||
// that is injected into the streaming reply so IM users can see the
|
||||
|
||||
Reference in New Issue
Block a user