diff --git a/frontend/src/api/agent/index.ts b/frontend/src/api/agent/index.ts index 33dbb470..551867e3 100644 --- a/frontend/src/api/agent/index.ts +++ b/frontend/src/api/agent/index.ts @@ -187,6 +187,7 @@ export interface IMChannel { enabled: boolean; mode: 'webhook' | 'websocket'; output_mode: 'stream' | 'full'; + session_mode?: 'user' | 'thread'; knowledge_base_id?: string; credentials: Record; created_at?: string; diff --git a/frontend/src/components/IMChannelPanel.vue b/frontend/src/components/IMChannelPanel.vue index 802c1be0..787d7e9e 100644 --- a/frontend/src/components/IMChannelPanel.vue +++ b/frontend/src/components/IMChannelPanel.vue @@ -37,6 +37,10 @@ {{ channel.output_mode === 'stream' ? $t('agentEditor.im.outputStream') : $t('agentEditor.im.outputFull') }} + + + {{ $t('agentEditor.im.sessionModeThread') }} +
{{ $t('agentEditor.im.callbackUrl') }}: @@ -121,6 +125,19 @@
+ +
+ + + {{ $t('agentEditor.im.sessionModeUser') }} + + {{ $t('agentEditor.im.sessionModeThread') }} + + +

{{ $t('agentEditor.im.sessionModeHint') }}

+
+
@@ -356,6 +373,7 @@ const formData = ref({ name: '', mode: 'websocket' as 'webhook' | 'websocket', output_mode: 'stream' as 'stream' | 'full', + session_mode: 'user' as 'user' | 'thread', knowledge_base_id: '', credentials: defaultCredentials(), }); @@ -365,6 +383,10 @@ function platformLabel(platform: string): string { return t(key); } +function platformSupportsThread(platform: string): boolean { + return ['slack', 'mattermost', 'feishu', 'telegram'].includes(platform); +} + watch( () => formData.value.platform, (p) => { @@ -374,6 +396,9 @@ watch( formData.value.credentials.post_to_main = false; } } + if (!platformSupportsThread(p)) { + formData.value.session_mode = 'user'; + } }, ); @@ -427,6 +452,7 @@ function editChannel(channel: IMChannel) { name: channel.name, mode: channel.mode, output_mode: channel.output_mode, + session_mode: channel.session_mode || 'user', knowledge_base_id: channel.knowledge_base_id || '', credentials: { ...channel.credentials }, }; @@ -440,6 +466,7 @@ function resetForm() { name: '', mode: 'websocket', output_mode: 'stream', + session_mode: 'user', knowledge_base_id: '', credentials: defaultCredentials(), }; @@ -452,6 +479,7 @@ async function handleSave() { name: formData.value.name, mode: formData.value.mode, output_mode: formData.value.output_mode, + session_mode: formData.value.session_mode, knowledge_base_id: formData.value.knowledge_base_id, credentials: formData.value.credentials, }); @@ -462,6 +490,7 @@ async function handleSave() { name: formData.value.name, mode: formData.value.mode, output_mode: formData.value.output_mode, + session_mode: formData.value.session_mode, knowledge_base_id: formData.value.knowledge_base_id, credentials: formData.value.credentials, }); diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index c162d024..0418fd56 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -3246,6 +3246,10 @@ export default { fileKnowledgeBase: 'File Storage Knowledge Base', fileKnowledgeBasePlaceholder: 'Select a knowledge base (optional)', fileKnowledgeBaseHint: 'When configured, files sent by users will be automatically saved to this knowledge base', + sessionMode: 'Session Mode', + sessionModeUser: 'Per User (default)', + sessionModeThread: 'Per Thread', + sessionModeHint: 'User mode: each person has their own conversation. Use /clear to start fresh. Thread mode: each message thread is a separate conversation. Multiple people can collaborate in the same thread.', }, mcp: { label: 'MCP Services', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 84a11714..23d6cbf9 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -3275,6 +3275,10 @@ export default { fileKnowledgeBase: "파일 저장 지식 베이스", fileKnowledgeBasePlaceholder: "지식 베이스 선택 (선택 사항)", fileKnowledgeBaseHint: "설정 시 사용자가 보낸 파일이 자동으로 해당 지식 베이스에 저장됩니다", + sessionMode: "세션 모드", + sessionModeUser: "사용자별 (기본)", + sessionModeThread: "스레드별", + sessionModeHint: "사용자 모드: 각 사용자별 독립 대화. /clear로 새 대화 시작. 스레드 모드: 메시지 스레드별 독립 대화. 같은 스레드에서 여러 명이 함께 대화 가능.", }, tools: { thinking: '사고', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index ea476532..4266113c 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -2908,6 +2908,10 @@ export default { fileKnowledgeBase: 'База знаний для файлов', fileKnowledgeBasePlaceholder: 'Выберите базу знаний (необязательно)', fileKnowledgeBaseHint: 'При настройке файлы, отправленные пользователями, автоматически сохраняются в эту базу знаний', + sessionMode: 'Режим сессии', + sessionModeUser: 'По пользователю (по умолчанию)', + sessionModeThread: 'По потоку', + sessionModeHint: 'Режим пользователя: отдельный диалог для каждого пользователя. /clear для нового диалога. Режим потока: отдельный диалог для каждого потока. Несколько человек могут общаться в одном потоке.', }, mcp: { label: 'MCP-сервисы', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 9f2c11c3..5e324312 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -3221,6 +3221,10 @@ export default { fileKnowledgeBase: "文件保存知识库", fileKnowledgeBasePlaceholder: "选择知识库(可选)", fileKnowledgeBaseHint: "配置后,用户发送的文件将自动保存到该知识库中", + sessionMode: "会话模式", + sessionModeUser: "按用户(默认)", + sessionModeThread: "按话题", + sessionModeHint: "用户模式:每个用户独立对话,使用 /clear 开始新对话。话题模式:每个消息话题独立对话,同一话题中多人可协作。", }, tools: { thinking: "思考", diff --git a/internal/im/adapter.go b/internal/im/adapter.go index 7a7acd52..ea642b53 100644 --- a/internal/im/adapter.go +++ b/internal/im/adapter.go @@ -19,6 +19,16 @@ const ( PlatformMattermost Platform = "mattermost" ) +// SessionMode determines how IM sessions are resolved. +type SessionMode string + +const ( + // SessionModeUser resolves sessions by (platform, user_id, chat_id, tenant_id). + SessionModeUser SessionMode = "user" + // SessionModeThread resolves sessions by (platform, thread_id, chat_id, tenant_id). + SessionModeThread SessionMode = "thread" +) + // MessageType identifies the kind of IM message. type MessageType string @@ -52,6 +62,15 @@ type IncomingMessage struct { FileName string // FileSize is the file size in bytes (for file messages, optional). FileSize int64 + // ThreadID is the platform-specific thread identifier. + // - Slack: thread_ts (top-level message uses its own timestamp) + // - Mattermost: root_id, or post_id if top-level + // - Feishu: root_id, or message_id if top-level + // - Telegram: message_thread_id (Forum Topics only) + // Empty for platforms without thread support (WeCom, DingTalk). + // In thread mode, top-level messages use their own ID as ThreadID, + // effectively creating a new session per top-level message. + ThreadID string // Extra holds platform-specific fields (e.g., WeCom stream ID). Extra map[string]string } diff --git a/internal/im/feishu/adapter.go b/internal/im/feishu/adapter.go index 0cbc2939..8e1cc0cf 100644 --- a/internal/im/feishu/adapter.go +++ b/internal/im/feishu/adapter.go @@ -205,6 +205,8 @@ type feishuEvent struct { type feishuMessage struct { MessageID string `json:"message_id"` + RootID string `json:"root_id"` + ParentID string `json:"parent_id"` MessageType string `json:"message_type"` ChatType string `json:"chat_type"` ChatID string `json:"chat_id"` @@ -263,6 +265,12 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) { } msg := eventBody.Event.Message + // Compute thread ID: use root_id for threaded replies, or message_id for top-level messages. + threadID := msg.RootID + if threadID == "" { + threadID = msg.MessageID + } + // Determine chat type chatType := im.ChatTypeDirect chatID := "" @@ -308,6 +316,7 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) { ChatType: chatType, Content: strings.TrimSpace(content), MessageID: msg.MessageID, + ThreadID: threadID, }, nil case "file": @@ -328,6 +337,7 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) { ChatID: chatID, ChatType: chatType, MessageID: msg.MessageID, + ThreadID: threadID, FileKey: fileContent.FileKey, FileName: fileContent.FileName, }, nil @@ -349,6 +359,7 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) { ChatID: chatID, ChatType: chatType, MessageID: msg.MessageID, + ThreadID: threadID, FileKey: imageContent.ImageKey, FileName: imageContent.ImageKey + ".png", }, nil @@ -411,6 +422,7 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) { ChatType: chatType, Content: content, MessageID: msg.MessageID, + ThreadID: threadID, }, nil default: diff --git a/internal/im/feishu/adapter_test.go b/internal/im/feishu/adapter_test.go new file mode 100644 index 00000000..bffe9182 --- /dev/null +++ b/internal/im/feishu/adapter_test.go @@ -0,0 +1,53 @@ +package feishu + +import "testing" + +func TestFeishuThreadID_ThreadedReply(t *testing.T) { + // Simulate: message is a reply in a thread (root_id is set) + msg := &feishuMessage{ + MessageID: "msg-reply-1", + RootID: "msg-root-1", + ParentID: "msg-parent-1", + } + + threadID := msg.RootID + if threadID == "" { + threadID = msg.MessageID + } + + if threadID != "msg-root-1" { + t.Errorf("threadID = %q, want %q", threadID, "msg-root-1") + } +} + +func TestFeishuThreadID_TopLevelMessage(t *testing.T) { + // Simulate: top-level message (root_id is empty) + msg := &feishuMessage{ + MessageID: "msg-top-1", + RootID: "", + ParentID: "", + } + + threadID := msg.RootID + if threadID == "" { + threadID = msg.MessageID + } + + if threadID != "msg-top-1" { + t.Errorf("threadID = %q, want %q (should use MessageID as fallback)", threadID, "msg-top-1") + } +} + +func TestFeishuMessageStruct_JSONFields(t *testing.T) { + // Verify the struct fields exist and have correct zero values + msg := feishuMessage{} + if msg.RootID != "" { + t.Errorf("RootID zero value = %q, want empty", msg.RootID) + } + if msg.ParentID != "" { + t.Errorf("ParentID zero value = %q, want empty", msg.ParentID) + } + if msg.MessageID != "" { + t.Errorf("MessageID zero value = %q, want empty", msg.MessageID) + } +} diff --git a/internal/im/mattermost/adapter.go b/internal/im/mattermost/adapter.go index affe30bd..c94b5a8b 100644 --- a/internal/im/mattermost/adapter.go +++ b/internal/im/mattermost/adapter.go @@ -114,7 +114,14 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) { } else { threadRoot = payload.RootID if threadRoot == "" { - threadRoot = payload.PostID + // Outgoing webhooks may omit root_id for thread replies. + // Fetch the post to resolve the actual thread root. + if actualRootID, err := a.client.GetPost(c.Request.Context(), payload.PostID); err == nil && actualRootID != "" { + threadRoot = actualRootID + } else { + // Top-level message: use its own PostID as thread root. + threadRoot = payload.PostID + } } } @@ -126,6 +133,7 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) { ChatType: im.ChatTypeGroup, Content: strings.TrimSpace(payload.Text), MessageID: payload.PostID, + ThreadID: threadRoot, Extra: map[string]string{ extraKeyThreadRoot: threadRoot, extraKeyChannelID: payload.ChannelID, diff --git a/internal/im/mattermost/adapter_test.go b/internal/im/mattermost/adapter_test.go new file mode 100644 index 00000000..dc551cda --- /dev/null +++ b/internal/im/mattermost/adapter_test.go @@ -0,0 +1,153 @@ +package mattermost + +import ( + "encoding/json" + "testing" +) + +func TestParseOutgoingBody_ThreadRoot(t *testing.T) { + tests := []struct { + name string + payload outgoingPayload + postReplyToMain bool + wantThreadRoot string + }{ + { + name: "threaded reply has RootID", + payload: outgoingPayload{ + PostID: "post-123", + RootID: "root-456", + }, + postReplyToMain: false, + wantThreadRoot: "root-456", + }, + { + name: "top-level message uses PostID as thread root", + payload: outgoingPayload{ + PostID: "post-789", + RootID: "", + }, + postReplyToMain: false, + wantThreadRoot: "post-789", + }, + { + name: "postReplyToMain clears thread root", + payload: outgoingPayload{ + PostID: "post-123", + RootID: "root-456", + }, + postReplyToMain: true, + wantThreadRoot: "", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var threadRoot string + if tt.postReplyToMain { + threadRoot = "" + } else { + threadRoot = tt.payload.RootID + if threadRoot == "" { + threadRoot = tt.payload.PostID + } + } + + if threadRoot != tt.wantThreadRoot { + t.Errorf("threadRoot = %q, want %q", threadRoot, tt.wantThreadRoot) + } + }) + } +} + +func TestParseOutgoingBody_JSON(t *testing.T) { + body := `{"token":"tok","user_id":"u1","user_name":"alice","channel_id":"ch1","post_id":"p1","text":"hello","root_id":"r1"}` + + payload, err := parseOutgoingBody("application/json", []byte(body)) + if err != nil { + t.Fatalf("parseOutgoingBody error: %v", err) + } + + if payload.RootID != "r1" { + t.Errorf("RootID = %q, want %q", payload.RootID, "r1") + } + if payload.PostID != "p1" { + t.Errorf("PostID = %q, want %q", payload.PostID, "p1") + } +} + +func TestParseOutgoingBody_FormEncoded(t *testing.T) { + body := "token=tok&user_id=u1&channel_id=ch1&post_id=p2&text=hello&root_id=r2" + + payload, err := parseOutgoingBody("application/x-www-form-urlencoded", []byte(body)) + if err != nil { + t.Fatalf("parseOutgoingBody error: %v", err) + } + + if payload.RootID != "r2" { + t.Errorf("RootID = %q, want %q", payload.RootID, "r2") + } + if payload.PostID != "p2" { + t.Errorf("PostID = %q, want %q", payload.PostID, "p2") + } +} + +func TestThreadIDInMessage(t *testing.T) { + // Simulate the adapter logic: build the message and verify ThreadID + payload := outgoingPayload{ + Token: "tok", + UserID: "user-1", + UserName: "alice", + ChannelID: "ch-1", + PostID: "post-100", + Text: "hello", + RootID: "root-200", + } + + threadRoot := payload.RootID + if threadRoot == "" { + threadRoot = payload.PostID + } + + // Verify the Extra map and ThreadID would be consistent + extra := map[string]string{ + extraKeyThreadRoot: threadRoot, + extraKeyChannelID: payload.ChannelID, + } + + if extra[extraKeyThreadRoot] != "root-200" { + t.Errorf("Extra thread_root_id = %q, want %q", extra[extraKeyThreadRoot], "root-200") + } + + // ThreadID should equal threadRoot + threadID := threadRoot + if threadID != "root-200" { + t.Errorf("ThreadID = %q, want %q", threadID, "root-200") + } +} + +func TestParseFileIDs(t *testing.T) { + tests := []struct { + name string + raw json.RawMessage + want []string + }{ + {"array", json.RawMessage(`["f1","f2"]`), []string{"f1", "f2"}}, + {"string", json.RawMessage(`"f3"`), []string{"f3"}}, + {"empty", nil, nil}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := parseFileIDs(tt.raw) + if len(got) != len(tt.want) { + t.Fatalf("parseFileIDs() len = %d, want %d", len(got), len(tt.want)) + } + for i := range got { + if got[i] != tt.want[i] { + t.Errorf("parseFileIDs()[%d] = %q, want %q", i, got[i], tt.want[i]) + } + } + }) + } +} diff --git a/internal/im/mattermost/client.go b/internal/im/mattermost/client.go index 58c90f55..e6df516f 100644 --- a/internal/im/mattermost/client.go +++ b/internal/im/mattermost/client.go @@ -88,6 +88,37 @@ func (c *Client) CreatePost(ctx context.Context, channelID, rootID, message stri return created.ID, nil } +// GetPost fetches a post by ID, returning its root_id (empty if top-level). +func (c *Client) GetPost(ctx context.Context, postID string) (rootID string, err error) { + url := fmt.Sprintf("%s/posts/%s", c.baseURL, postID) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return "", err + } + c.authHeader(req) + req.Header.Del("Content-Type") + + resp, err := c.httpClient.Do(req) + if err != nil { + return "", err + } + defer resp.Body.Close() + + respBody, _ := io.ReadAll(resp.Body) + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return "", fmt.Errorf("mattermost get post: status=%d body=%s", resp.StatusCode, truncateForErr(respBody)) + } + + var post struct { + ID string `json:"id"` + RootID string `json:"root_id"` + } + if err := json.Unmarshal(respBody, &post); err != nil { + return "", fmt.Errorf("decode get post: %w", err) + } + return post.RootID, nil +} + // PatchPostMessage updates a post's message field. func (c *Client) PatchPostMessage(ctx context.Context, postID, message string) error { payload, err := json.Marshal(map[string]string{"message": message}) diff --git a/internal/im/service.go b/internal/im/service.go index b6a1216f..92049205 100644 --- a/internal/im/service.go +++ b/internal/im/service.go @@ -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 diff --git a/internal/im/session_test.go b/internal/im/session_test.go new file mode 100644 index 00000000..ef8120df --- /dev/null +++ b/internal/im/session_test.go @@ -0,0 +1,145 @@ +package im + +import "testing" + +func TestMakeUserKey_UserMode(t *testing.T) { + tests := []struct { + name string + channelID string + userID string + chatID string + threadID string + want string + }{ + { + name: "user mode with empty threadID", + channelID: "ch-1", + userID: "user-1", + chatID: "chat-1", + threadID: "", + want: "ch-1:user-1:chat-1", + }, + { + name: "user mode with empty chatID (DM)", + channelID: "ch-1", + userID: "user-1", + chatID: "", + threadID: "", + want: "ch-1:user-1:", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := makeUserKey(tt.channelID, tt.userID, tt.chatID, tt.threadID) + if got != tt.want { + t.Errorf("makeUserKey() = %q, want %q", got, tt.want) + } + }) + } +} + +func TestMakeUserKey_ThreadMode(t *testing.T) { + tests := []struct { + name string + channelID string + userID string + chatID string + threadID string + want string + }{ + { + name: "thread mode with Slack thread_ts", + channelID: "ch-1", + userID: "user-1", + chatID: "chat-1", + threadID: "1234567890.123456", + want: "ch-1:user-1:chat-1:1234567890.123456", + }, + { + name: "thread mode with Mattermost root_id", + channelID: "ch-2", + userID: "user-2", + chatID: "chat-2", + threadID: "abc123def456", + want: "ch-2:user-2:chat-2:abc123def456", + }, + { + name: "thread mode with Telegram topic ID", + channelID: "ch-3", + userID: "user-3", + chatID: "chat-3", + threadID: "42", + want: "ch-3:user-3:chat-3:42", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := makeUserKey(tt.channelID, tt.userID, tt.chatID, tt.threadID) + if got != tt.want { + t.Errorf("makeUserKey() = %q, want %q", got, tt.want) + } + }) + } +} + +func TestMakeUserKey_ThreadIDGuard(t *testing.T) { + // Verify that the same user+chat produces different keys with different threadIDs + keyA := makeUserKey("ch", "user", "chat", "thread-A") + keyB := makeUserKey("ch", "user", "chat", "thread-B") + keyNone := makeUserKey("ch", "user", "chat", "") + + if keyA == keyB { + t.Error("different threadIDs should produce different keys") + } + if keyA == keyNone { + t.Error("thread key should differ from non-thread key") + } + if keyB == keyNone { + t.Error("thread key should differ from non-thread key") + } +} + +func TestMakeUserKey_SameThreadDifferentUsers(t *testing.T) { + // In thread mode, different users in the same thread produce different keys + // (this is intentional: /stop only cancels the caller's own request) + keyUserA := makeUserKey("ch", "alice", "chat", "thread-1") + keyUserB := makeUserKey("ch", "bob", "chat", "thread-1") + + if keyUserA == keyUserB { + t.Error("different users in same thread should have different keys") + } +} + +func TestIncomingMessageThreadID(t *testing.T) { + // Verify ThreadID field works correctly on IncomingMessage + msg := &IncomingMessage{ + Platform: PlatformSlack, + UserID: "U123", + ChatID: "C456", + MessageID: "1234567890.123456", + ThreadID: "1234567890.123456", + } + + if msg.ThreadID != msg.MessageID { + t.Errorf("Slack ThreadID should equal MessageID for top-level, got ThreadID=%q MessageID=%q", + msg.ThreadID, msg.MessageID) + } + + // Mattermost: ThreadID from Extra + msgMM := &IncomingMessage{ + Platform: PlatformMattermost, + UserID: "user-1", + ChatID: "channel-1", + MessageID: "post-123", + ThreadID: "root-456", + Extra: map[string]string{ + "thread_root_id": "root-456", + }, + } + + if msgMM.ThreadID != msgMM.Extra["thread_root_id"] { + t.Error("Mattermost ThreadID should match Extra thread_root_id") + } +} diff --git a/internal/im/slack/adapter.go b/internal/im/slack/adapter.go index dc919a74..8744639d 100644 --- a/internal/im/slack/adapter.go +++ b/internal/im/slack/adapter.go @@ -70,6 +70,7 @@ func parseIncomingMessage(user, channel, text, ts string, chatType im.ChatType, ChatType: chatType, Content: strings.TrimSpace(content), MessageID: ts, + ThreadID: ts, } if len(files) > 0 { diff --git a/internal/im/slack/adapter_test.go b/internal/im/slack/adapter_test.go new file mode 100644 index 00000000..0da73b4c --- /dev/null +++ b/internal/im/slack/adapter_test.go @@ -0,0 +1,70 @@ +package slack + +import ( + "testing" + + "github.com/Tencent/WeKnora/internal/im" + slacklib "github.com/slack-go/slack" +) + +func TestParseIncomingMessage_ThreadID(t *testing.T) { + tests := []struct { + name string + ts string + wantThreadID string + wantMessageID string + }{ + { + name: "top-level message uses own timestamp", + ts: "1234567890.123456", + wantThreadID: "1234567890.123456", + wantMessageID: "1234567890.123456", + }, + { + name: "threaded reply uses thread_ts", + ts: "1234567890.000001", + wantThreadID: "1234567890.000001", + wantMessageID: "1234567890.000001", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + msg := parseIncomingMessage("U123", "C456", "hello", tt.ts, im.ChatTypeGroup, nil) + + if msg.ThreadID != tt.wantThreadID { + t.Errorf("ThreadID = %q, want %q", msg.ThreadID, tt.wantThreadID) + } + if msg.MessageID != tt.wantMessageID { + t.Errorf("MessageID = %q, want %q", msg.MessageID, tt.wantMessageID) + } + }) + } +} + +func TestParseIncomingMessage_ThreadID_WithFiles(t *testing.T) { + files := []slacklib.File{ + {ID: "F123", Name: "test.pdf", Size: 1024, Mimetype: "application/pdf"}, + } + + msg := parseIncomingMessage("U123", "C456", "", "1234567890.999", im.ChatTypeDirect, files) + + if msg.ThreadID != "1234567890.999" { + t.Errorf("ThreadID = %q, want %q", msg.ThreadID, "1234567890.999") + } + if msg.MessageType != im.MessageTypeFile { + t.Errorf("MessageType = %q, want %q", msg.MessageType, im.MessageTypeFile) + } +} + +func TestParseIncomingMessage_MentionStripping(t *testing.T) { + // Ensure mention stripping doesn't affect ThreadID + msg := parseIncomingMessage("U123", "C456", "<@U999> hello world", "ts-123", im.ChatTypeGroup, nil) + + if msg.ThreadID != "ts-123" { + t.Errorf("ThreadID = %q, want %q", msg.ThreadID, "ts-123") + } + if msg.Content != "hello world" { + t.Errorf("Content = %q, want %q", msg.Content, "hello world") + } +} diff --git a/internal/im/telegram/adapter.go b/internal/im/telegram/adapter.go index daf055c1..2871e36f 100644 --- a/internal/im/telegram/adapter.go +++ b/internal/im/telegram/adapter.go @@ -8,6 +8,7 @@ import ( "fmt" "io" "net/http" + "strconv" "strings" "sync" "time" @@ -76,12 +77,13 @@ type telegramUpdate struct { } type telegramMsg struct { - MessageID int `json:"message_id"` - From *telegramUser `json:"from"` - Chat telegramChat `json:"chat"` - Text string `json:"text"` - Document *telegramDoc `json:"document"` - Photo []telegramPhoto `json:"photo"` + MessageID int `json:"message_id"` + MessageThreadID int `json:"message_thread_id"` + From *telegramUser `json:"from"` + Chat telegramChat `json:"chat"` + Text string `json:"text"` + Document *telegramDoc `json:"document"` + Photo []telegramPhoto `json:"photo"` } type telegramUser struct { @@ -154,6 +156,11 @@ func parseTelegramMessage(msg *telegramMsg) *im.IncomingMessage { } } + threadID := "" + if msg.MessageThreadID != 0 { + threadID = fmt.Sprintf("%d", msg.MessageThreadID) + } + incoming := &im.IncomingMessage{ Platform: im.PlatformTelegram, UserID: userID, @@ -161,6 +168,7 @@ func parseTelegramMessage(msg *telegramMsg) *im.IncomingMessage { ChatID: chatID, ChatType: chatType, MessageID: fmt.Sprintf("%d", msg.MessageID), + ThreadID: threadID, MessageType: im.MessageTypeText, Content: msg.Text, } @@ -206,7 +214,20 @@ func resolveChatID(incoming *im.IncomingMessage) string { // ── Send reply ── func (a *Adapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error { - return a.sendMessage(ctx, resolveChatID(incoming), transformThinkBlocks(reply.Content), "") + chatID := resolveChatID(incoming) + text := transformThinkBlocks(reply.Content) + + body := map[string]interface{}{ + "chat_id": chatID, + "text": text, + "parse_mode": "Markdown", + } + if incoming.ThreadID != "" { + if tid, err := strconv.Atoi(incoming.ThreadID); err == nil { + body["message_thread_id"] = tid + } + } + return a.callAPI(ctx, "sendMessage", body) } func (a *Adapter) sendMessage(ctx context.Context, chatID, text, replyToMessageID string) error { @@ -343,6 +364,11 @@ func (a *Adapter) StartStream(ctx context.Context, incoming *im.IncomingMessage) "chat_id": chatID, "text": "正在思考...", } + if incoming.ThreadID != "" { + if tid, err := strconv.Atoi(incoming.ThreadID); err == nil { + body["message_thread_id"] = tid + } + } var sentMsg struct { MessageID int `json:"message_id"` } diff --git a/internal/im/telegram/adapter_test.go b/internal/im/telegram/adapter_test.go new file mode 100644 index 00000000..acb02a24 --- /dev/null +++ b/internal/im/telegram/adapter_test.go @@ -0,0 +1,108 @@ +package telegram + +import ( + "testing" + + "github.com/Tencent/WeKnora/internal/im" +) + +func TestParseTelegramMessage_ForumTopicThread(t *testing.T) { + msg := &telegramMsg{ + MessageID: 100, + MessageThreadID: 42, // Forum topic ID + From: &telegramUser{ID: 1001, FirstName: "Alice"}, + Chat: telegramChat{ID: -9999, Type: "supergroup"}, + Text: "hello", + } + + incoming := parseTelegramMessage(msg) + if incoming == nil { + t.Fatal("expected non-nil message") + } + + if incoming.ThreadID != "42" { + t.Errorf("ThreadID = %q, want %q", incoming.ThreadID, "42") + } +} + +func TestParseTelegramMessage_NonForumGroup(t *testing.T) { + msg := &telegramMsg{ + MessageID: 200, + MessageThreadID: 0, // not a Forum group + From: &telegramUser{ID: 1002, FirstName: "Bob"}, + Chat: telegramChat{ID: -8888, Type: "group"}, + Text: "hello", + } + + incoming := parseTelegramMessage(msg) + if incoming == nil { + t.Fatal("expected non-nil message") + } + + // Non-Forum groups: ThreadID should be empty + if incoming.ThreadID != "" { + t.Errorf("ThreadID = %q, want empty for non-Forum group", incoming.ThreadID) + } +} + +func TestParseTelegramMessage_DirectMessage(t *testing.T) { + msg := &telegramMsg{ + MessageID: 300, + From: &telegramUser{ID: 1003, FirstName: "Carol"}, + Chat: telegramChat{ID: 1003, Type: "private"}, + Text: "hi bot", + } + + incoming := parseTelegramMessage(msg) + if incoming == nil { + t.Fatal("expected non-nil message") + } + + if incoming.ThreadID != "" { + t.Errorf("ThreadID = %q, want empty for DM", incoming.ThreadID) + } + if incoming.ChatType != im.ChatTypeDirect { + t.Errorf("ChatType = %q, want %q", incoming.ChatType, im.ChatTypeDirect) + } +} + +func TestParseTelegramMessage_NilMessage(t *testing.T) { + incoming := parseTelegramMessage(nil) + if incoming != nil { + t.Error("expected nil for nil message") + } +} + +func TestParseTelegramMessage_Document(t *testing.T) { + msg := &telegramMsg{ + MessageID: 400, + MessageThreadID: 7, // in a Forum topic + From: &telegramUser{ID: 1004, FirstName: "Dave"}, + Chat: telegramChat{ID: -7777, Type: "supergroup"}, + Document: &telegramDoc{ + FileID: "doc-123", + FileName: "report.pdf", + FileSize: 2048, + }, + } + + incoming := parseTelegramMessage(msg) + if incoming == nil { + t.Fatal("expected non-nil message") + } + + if incoming.ThreadID != "7" { + t.Errorf("ThreadID = %q, want %q", incoming.ThreadID, "7") + } + if incoming.MessageType != im.MessageTypeFile { + t.Errorf("MessageType = %q, want %q", incoming.MessageType, im.MessageTypeFile) + } +} + +func TestParseUpdate_NilMessage(t *testing.T) { + update := &telegramUpdate{UpdateID: 1, Message: nil} + incoming := parseUpdate(update) + if incoming != nil { + t.Error("expected nil for nil update.Message") + } +} diff --git a/internal/im/types.go b/internal/im/types.go index 94754b14..a574b136 100644 --- a/internal/im/types.go +++ b/internal/im/types.go @@ -24,6 +24,7 @@ type IMChannel struct { OutputMode string `json:"output_mode" gorm:"type:varchar(20);not null;default:'stream'"` KnowledgeBaseID string `json:"knowledge_base_id" gorm:"type:varchar(36);default:''"` BotIdentity string `json:"bot_identity" gorm:"type:varchar(255);not null;default:'';uniqueIndex:idx_im_channels_bot_identity,where:deleted_at IS NULL AND bot_identity != ''"` + SessionMode string `json:"session_mode" gorm:"type:varchar(20);not null;default:'user'"` Credentials types.JSON `json:"credentials" gorm:"type:jsonb;not null;default:'{}'"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` @@ -48,16 +49,39 @@ func (ch *IMChannel) BeforeCreate(tx *gorm.DB) error { if ch.OutputMode == "" { ch.OutputMode = "stream" } + if ch.SessionMode == "" { + ch.SessionMode = string(SessionModeUser) + } + if err := ch.validateSessionMode(); err != nil { + return err + } ch.BotIdentity = ch.computeBotIdentity() return nil } -// BeforeSave ensures bot_identity is recomputed on every save (create + update). +// BeforeSave ensures bot_identity is recomputed and session_mode is validated +// on every save (create + update). func (ch *IMChannel) BeforeSave(tx *gorm.DB) error { + if ch.SessionMode == "" { + ch.SessionMode = string(SessionModeUser) + } + if err := ch.validateSessionMode(); err != nil { + return err + } ch.BotIdentity = ch.computeBotIdentity() return nil } +// validateSessionMode checks that SessionMode holds a supported value. +func (ch *IMChannel) validateSessionMode() error { + switch SessionMode(ch.SessionMode) { + case SessionModeUser, SessionModeThread: + return nil + default: + return fmt.Errorf("invalid session_mode: %s", ch.SessionMode) + } +} + // computeBotIdentity derives a unique bot identity string from the channel's // platform, mode, and credentials. Returns "" if no identity can be extracted. func (ch *IMChannel) computeBotIdentity() string { @@ -123,6 +147,7 @@ type ChannelSession struct { Platform string `json:"platform" gorm:"type:varchar(20);not null"` UserID string `json:"user_id" gorm:"type:varchar(128);not null"` ChatID string `json:"chat_id" gorm:"type:varchar(128);not null;default:''"` + ThreadID string `json:"thread_id" gorm:"type:varchar(128);not null;default:''"` SessionID string `json:"session_id" gorm:"type:varchar(36);not null;index"` TenantID uint64 `json:"tenant_id" gorm:"not null;index"` AgentID string `json:"agent_id" gorm:"type:varchar(36);default:''"` diff --git a/internal/im/types_test.go b/internal/im/types_test.go new file mode 100644 index 00000000..2b3dd0c4 --- /dev/null +++ b/internal/im/types_test.go @@ -0,0 +1,153 @@ +package im + +import ( + "testing" + + "gorm.io/gorm" +) + +func TestValidateSessionMode(t *testing.T) { + tests := []struct { + name string + sessionMode string + wantErr bool + }{ + {"user mode", "user", false}, + {"thread mode", "thread", false}, + {"empty defaults to user in BeforeCreate", "", false}, + {"invalid mode", "invalid", true}, + {"random string", "foo", true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ch := &IMChannel{SessionMode: tt.sessionMode} + err := ch.validateSessionMode() + + if tt.sessionMode == "" { + // empty is handled by BeforeCreate, not validateSessionMode + // validateSessionMode treats empty as invalid + if err == nil { + t.Error("expected error for empty session_mode in validateSessionMode") + } + return + } + + if (err != nil) != tt.wantErr { + t.Errorf("validateSessionMode(%q) error = %v, wantErr %v", tt.sessionMode, err, tt.wantErr) + } + }) + } +} + +func TestIMChannelBeforeCreate_SessionModeDefault(t *testing.T) { + tests := []struct { + name string + inputMode string + expectedMode string + }{ + {"empty defaults to user", "", "user"}, + {"user preserved", "user", "user"}, + {"thread preserved", "thread", "thread"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ch := &IMChannel{ + TenantID: 1, + AgentID: "agent-1", + Platform: "slack", + SessionMode: tt.inputMode, + Credentials: []byte("{}"), + } + err := ch.BeforeCreate(&gorm.DB{}) + if err != nil { + t.Fatalf("BeforeCreate error: %v", err) + } + if ch.SessionMode != tt.expectedMode { + t.Errorf("SessionMode = %q, want %q", ch.SessionMode, tt.expectedMode) + } + }) + } +} + +func TestIMChannelBeforeCreate_InvalidSessionMode(t *testing.T) { + ch := &IMChannel{ + TenantID: 1, + AgentID: "agent-1", + Platform: "slack", + SessionMode: "invalid", + Credentials: []byte("{}"), + } + err := ch.BeforeCreate(&gorm.DB{}) + if err == nil { + t.Error("expected error for invalid session_mode") + } +} + +func TestIMChannelBeforeSave_SessionModeValidation(t *testing.T) { + tests := []struct { + name string + sessionMode string + wantMode string + wantErr bool + }{ + {"empty defaults to user", "", "user", false}, + {"user preserved", "user", "user", false}, + {"thread preserved", "thread", "thread", false}, + {"invalid rejected", "invalid", "", true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ch := &IMChannel{ + SessionMode: tt.sessionMode, + Credentials: []byte("{}"), + } + err := ch.BeforeSave(&gorm.DB{}) + if tt.wantErr { + if err == nil { + t.Error("expected error") + } + return + } + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if ch.SessionMode != tt.wantMode { + t.Errorf("SessionMode = %q, want %q", ch.SessionMode, tt.wantMode) + } + }) + } +} + +func TestSessionModeConstants(t *testing.T) { + if SessionModeUser != "user" { + t.Errorf("SessionModeUser = %q, want %q", SessionModeUser, "user") + } + if SessionModeThread != "thread" { + t.Errorf("SessionModeThread = %q, want %q", SessionModeThread, "thread") + } +} + +func TestChannelSessionThreadIDField(t *testing.T) { + cs := ChannelSession{ + Platform: "slack", + UserID: "U123", + ChatID: "C456", + ThreadID: "1234567890.123456", + } + if cs.ThreadID != "1234567890.123456" { + t.Errorf("ThreadID = %q, want %q", cs.ThreadID, "1234567890.123456") + } + + // empty ThreadID for user-mode sessions + csUser := ChannelSession{ + Platform: "slack", + UserID: "U123", + ChatID: "C456", + } + if csUser.ThreadID != "" { + t.Errorf("ThreadID = %q, want empty", csUser.ThreadID) + } +} diff --git a/migrations/versioned/000028_im_thread_session.down.sql b/migrations/versioned/000028_im_thread_session.down.sql new file mode 100644 index 00000000..7c2e7333 --- /dev/null +++ b/migrations/versioned/000028_im_thread_session.down.sql @@ -0,0 +1,8 @@ +DO $$ BEGIN RAISE NOTICE '[Migration 000028] Rolling back thread session support'; END $$; + +DROP INDEX IF EXISTS idx_channel_thread_lookup; +ALTER TABLE im_channel_sessions DROP COLUMN IF EXISTS thread_id; +ALTER TABLE im_channels DROP CONSTRAINT IF EXISTS chk_im_channels_session_mode; +ALTER TABLE im_channels DROP COLUMN IF EXISTS session_mode; + +DO $$ BEGIN RAISE NOTICE '[Migration 000028] Rollback completed'; END $$; diff --git a/migrations/versioned/000028_im_thread_session.up.sql b/migrations/versioned/000028_im_thread_session.up.sql new file mode 100644 index 00000000..9215028f --- /dev/null +++ b/migrations/versioned/000028_im_thread_session.up.sql @@ -0,0 +1,33 @@ +-- Migration: 000028_im_thread_session +-- Description: Add thread-based session mode support for IM channels +DO $$ BEGIN RAISE NOTICE '[Migration 000028] Adding thread session support'; END $$; + +-- 1. im_channels: add session_mode column +ALTER TABLE im_channels + ADD COLUMN IF NOT EXISTS session_mode VARCHAR(20) NOT NULL DEFAULT 'user'; + +-- 2. CHECK constraint (separate statement: ADD COLUMN IF NOT EXISTS does not support inline CONSTRAINT) +DO $$ BEGIN + ALTER TABLE im_channels + ADD CONSTRAINT chk_im_channels_session_mode + CHECK (session_mode IN ('user', 'thread')); +EXCEPTION WHEN duplicate_object THEN NULL; +END $$; + +COMMENT ON COLUMN im_channels.session_mode IS + 'Session resolution mode: user (per user+chat, default) or thread (per thread)'; + +-- 3. im_channel_sessions: add thread_id column +ALTER TABLE im_channel_sessions + ADD COLUMN IF NOT EXISTS thread_id VARCHAR(128) NOT NULL DEFAULT ''; + +COMMENT ON COLUMN im_channel_sessions.thread_id IS + 'Platform thread identifier for thread-based sessions. Empty for user-mode sessions.'; + +-- 4. Unique index for thread-mode session lookup +-- Includes chat_id because Telegram message_thread_id is per-chat (topic ID within a group). +CREATE UNIQUE INDEX IF NOT EXISTS idx_channel_thread_lookup + ON im_channel_sessions (platform, chat_id, thread_id, tenant_id) + WHERE deleted_at IS NULL AND thread_id != ''; + +DO $$ BEGIN RAISE NOTICE '[Migration 000028] Thread session support added'; END $$;