Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7585 feat(telegram): inline recent group context on @mentions (#8673)
pseudoyud31fcbc9b778
diff --git a/apps/docs/content/docs/telegram-bot-integration.ja.mdx b/apps/docs/content/docs/telegram-bot-integration.ja.mdxindex 82ae36878f..d181f75692 100644--- a/apps/docs/content/docs/telegram-bot-integration.ja.mdx+++ b/apps/docs/content/docs/telegram-bot-integration.ja.mdx@@ -20,7 +20,7 @@ Telegram 連携は[コミュニティメンテナンス](/community-maintained)1. [@BotFather](https://t.me/BotFather) を開き、`/newbot` を送信します。2. 表示名と、`bot` で終わる username を設定します。3. HTTP API token をコピーします。-4. **Group Privacy** は有効のままにします。グループではコマンド、明示的な @mention、Bot への返信だけを処理します。+4. 既定では **Group Privacy** を有効のままにします。これが可視範囲を最小にする構成で、Telegram はコマンド、明示的な @mention、Bot への返信だけを Bot に配信します。無効化は任意です。無効にすると Bot は周囲のグループ会話をコンテキストとして扱えるようになりますが、その代わりグループの全メッセージを受信します。詳細は「グループ」の項を参照してください。<Callout type="warning">token を issue、チャット、ログ、リポジトリに記録しないでください。漏えいした場合は @BotFather で失効させ、新しい token で再接続します。@@ -43,7 +43,7 @@ Multica は Telegram で Bot を検証し、long polling と競合する webhook## Bot を使う- **DM**: @mention なしでテキストを送信します。-- **グループ**: Bot を追加し、@mention するか Bot のメッセージに直接返信します。受理されたメッセージは継続中の Multica 会話に残りますが、Bot 宛てでない会話は収集されません。他のメンバーのメッセージへ返信する場合は Bot も明示的に @mention してください。その場合に限り、引用元の送信者とテキスト(または caption)が新しい指示の文脈に含まれます。@mention なしの人への返信は Bot を起動しません。forum topic は topic ごとにセッションが分離されます。+- **グループ**: Bot を追加し、@mention するか Bot のメッセージに直接返信します。受理されたメッセージは継続中の Multica 会話に残ります。Bot 宛てでないグループメッセージは、それ自体で会話やターンを開始することはありません。ただし小さなメモリ上のバッファに保持されます。グループ(または forum topic)ごとに Bot が受信した直近 10 件で、サーバーの再起動で消えます。その後メンバーが @mention または Bot のメッセージへの返信で Bot に指示すると、バッファ内のメッセージが読み取り専用のコンテキストとしてそのターンの前に添えられ、ターンと一緒に会話として保存されます。`/new` で始めた新しい会話にはこのコンテキストは付きません。バッファに入る内容は Telegram が何を配信するかで決まります。Group Privacy が有効ならコマンド、明示的な @mention、Bot への返信だけなので、コンテキストには以前 Bot 宛てだったメッセージだけが入ります。通常の会話も含めたい場合は @BotFather で Group Privacy を無効にし、Bot をグループから外して再追加してください。以後 Bot はグループの全メッセージを受信します。グループ管理者になっている Bot はプライバシー設定に関係なく全メッセージを受信するため、@BotFather を変更しなくても通常の会話がコンテキストに含まれます。他のメンバーのメッセージへ返信する場合は Bot も明示的に @mention してください。その場合に限り、引用元の送信者とテキスト(または caption)が新しい指示の文脈に含まれます。@mention なしの人への返信は Bot を起動しません。forum topic は topic ごとにセッションが分離されます。- **`/new` / `/new <message>`**: 空の新しい Multica Chat を作成し、その Telegram 会話の後続メッセージを新しい Chat にルーティングします。メッセージを付けた場合は新しい Chat の最初のターンになります。他のメンバーへの返信で Bot を明示的に @mention した場合、選択した引用内容も最初のターンに含まれます。- **`/clear` / `/clear <message>`**: 現在の Multica Chat を維持したまま、次の空でないメッセージに新しいエージェント可視コンテキストを適用します。メッセージを付けた場合は境界後の最初のターンになり、明示的に選択した返信の引用も保持されます。- **`/issue <title>`**: Multica issue を作成します。2 行目以降は任意の説明です。`/issue@your_bot` 形式も利用できます。diff --git a/apps/docs/content/docs/telegram-bot-integration.ko.mdx b/apps/docs/content/docs/telegram-bot-integration.ko.mdxindex 2a4f283323..08f5fe8c59 100644--- a/apps/docs/content/docs/telegram-bot-integration.ko.mdx+++ b/apps/docs/content/docs/telegram-bot-integration.ko.mdx@@ -20,7 +20,7 @@ Telegram 연동은 [커뮤니티가 유지관리](/community-maintained)합니1. [@BotFather](https://t.me/BotFather)를 열고 `/newbot`을 보냅니다.2. 표시 이름과 `bot`으로 끝나는 username을 정합니다.3. HTTP API token을 복사합니다.-4. **Group Privacy**를 켜 둡니다. 그룹에서는 명령, 명시적 @mention, Bot 메시지에 대한 답장만 처리합니다.+4. 기본값으로 **Group Privacy**를 켜 둡니다. 가시 범위가 가장 좁은 구성으로, Telegram은 명령, 명시적 @mention, Bot 메시지에 대한 답장만 Bot에 전달합니다. 끄는 것은 선택 사항입니다. 끄면 Bot이 주변 그룹 대화를 컨텍스트로 활용할 수 있지만, 대신 그룹의 모든 메시지를 받게 됩니다. 자세한 내용은 「그룹」 항목을 참고하세요.<Callout type="warning">token을 issue, 채팅, 로그, 코드 저장소에 남기지 마세요. 노출되었다면 @BotFather에서 폐기하고 새 token으로 다시 연결하세요.@@ -43,7 +43,7 @@ Multica는 Telegram에서 Bot을 검증하고 long polling과 충돌하는 webho## Bot 사용하기- **개인 채팅**: @mention 없이 텍스트를 보냅니다.-- **그룹**: Bot을 추가한 뒤 @mention하거나 Bot 메시지에 직접 답장합니다. 수락된 메시지는 이어지는 Multica 대화에 남지만 Bot을 지정하지 않은 그룹 대화는 수집하지 않습니다. 다른 사람의 메시지에 답장할 때는 Bot도 명시적으로 @mention해야 하며, 이 경우에만 인용한 발신자와 텍스트(또는 caption)가 새 지시의 맥락에 포함됩니다. Bot @mention 없이 사람에게 답장하면 Bot이 실행되지 않습니다. forum topic은 topic별로 세션이 분리됩니다.+- **그룹**: Bot을 추가한 뒤 @mention하거나 Bot 메시지에 직접 답장합니다. 수락된 메시지는 이어지는 Multica 대화에 남습니다. Bot을 지정하지 않은 그룹 메시지는 그 자체로 대화나 턴을 시작하지 않습니다. 다만 작은 메모리 버퍼에 보관됩니다. 그룹(또는 forum topic)별로 Bot이 받은 최근 10개이며, 서버가 재시작되면 지워집니다. 이후 구성원이 @mention이나 Bot 메시지에 대한 답장으로 Bot에게 지시하면, 버퍼의 메시지가 읽기 전용 컨텍스트로 그 턴 앞에 붙고 턴과 함께 대화의 일부로 저장됩니다. `/new`로 시작한 새 대화에는 이 컨텍스트가 붙지 않습니다. 버퍼에 무엇이 들어가는지는 Telegram이 무엇을 전달하느냐에 달려 있습니다. Group Privacy가 켜져 있으면 명령, 명시적 @mention, Bot에 대한 답장뿐이므로 컨텍스트에는 이전에 Bot에게 보낸 메시지만 남습니다. 일반 그룹 대화까지 포함하려면 @BotFather에서 Group Privacy를 끄고 Bot을 그룹에서 내보낸 뒤 다시 추가하세요. 그 뒤로 Bot은 그룹의 모든 메시지를 받습니다. 그룹 관리자인 Bot은 프라이버시 설정과 무관하게 모든 메시지를 받으므로, @BotFather를 바꾸지 않아도 일반 대화가 컨텍스트에 포함됩니다. 다른 사람의 메시지에 답장할 때는 Bot도 명시적으로 @mention해야 하며, 이 경우에만 인용한 발신자와 텍스트(또는 caption)가 새 지시의 맥락에 포함됩니다. Bot @mention 없이 사람에게 답장하면 Bot이 실행되지 않습니다. forum topic은 topic별로 세션이 분리됩니다.- **`/new` / `/new <message>`**: 비어 있는 새 Multica Chat을 만들고 해당 Telegram 대화의 이후 메시지를 새 Chat으로 라우팅합니다. 메시지를 함께 보내면 새 Chat의 첫 번째 대화가 됩니다. 다른 멤버에게 답장하면서 Bot을 명시적으로 @mention하면 선택한 인용 내용도 첫 번째 대화에 포함됩니다.- **`/clear` / `/clear <message>`**: 현재 Multica Chat을 유지하면서 다음 비어 있지 않은 메시지에 새 에이전트 컨텍스트를 적용합니다. 메시지를 함께 보내면 경계 이후의 첫 번째 대화가 되며 명시적으로 선택한 답장 인용도 유지됩니다.- **`/issue <title>`**: Multica issue를 만듭니다. 다음 줄은 선택 설명으로 사용됩니다. `/issue@your_bot` 형식도 지원합니다.diff --git a/apps/docs/content/docs/telegram-bot-integration.mdx b/apps/docs/content/docs/telegram-bot-integration.mdxindex 4a2b2982aa..b8639d0826 100644--- a/apps/docs/content/docs/telegram-bot-integration.mdx+++ b/apps/docs/content/docs/telegram-bot-integration.mdx@@ -20,7 +20,7 @@ Telegram support is [community-maintained](/community-maintained): it ships in e1. Open [@BotFather](https://t.me/BotFather) and send `/newbot`.2. Choose a display name and a username ending in `bot`.3. Copy the HTTP API token.-4. Keep **Group Privacy** enabled. Multica only needs commands, explicit @-mentions, and replies to the Bot in groups.+4. Leave **Group Privacy** enabled for the default, minimal-visibility setup: Telegram then delivers only commands, explicit @-mentions, and replies to the Bot in groups. Turning it off is optional. It lets the Bot include the surrounding group conversation as context, at the cost that the Bot then receives every message in the group — see [Groups and forum topics](#groups-and-forum-topics).<Callout type="warning">Never paste the token into an issue, chat message, log, or source repository. If it is exposed, use @BotFather to revoke it, then reconnect the Bot with the replacement token.@@ -50,7 +50,7 @@ Open the Bot and send text directly. No @-mention is required.### Groups and forum topics-Add the Bot to a group, then either @-mention it or reply directly to one of its messages. Accepted messages remain in the continued Multica conversation; unaddressed group chatter is not collected. When replying to another person's message, explicitly @-mention the Bot: only then are that quoted sender and text (or caption) included with your instruction. Replying to a human message without mentioning the Bot does not trigger it. Each ordinary group has its own continued Multica chat; forum topics are isolated into separate chats.+Add the Bot to a group, then either @-mention it or reply directly to one of its messages. Accepted messages remain in the continued Multica conversation. A group message that does not address the Bot never starts a conversation or a turn on its own. It is, however, held in a short in-memory buffer: the last 10 messages per group (or per forum topic) that the Bot has received, cleared whenever the server restarts. When a member then addresses the Bot — by @-mention or by replying to one of its messages — those buffered messages are prepended to that turn as read-only context, and they are saved together with the turn as part of the conversation. `/new` starts a fresh chat without that context. What reaches the buffer depends on what Telegram delivers: with Group Privacy enabled, that is only commands, explicit @-mentions, and replies to the Bot, so the context holds earlier addressed messages only. To include ordinary group chatter, turn Group Privacy off in @BotFather and then remove and re-add the Bot to the group; the Bot receives every group message from then on. A Bot that is a group admin receives every message regardless of the privacy setting, so its context includes ordinary chatter without any change in @BotFather. When replying to another person's message, explicitly @-mention the Bot: only then are that quoted sender and text (or caption) included with your instruction. Replying to a human message without mentioning the Bot does not trigger it. Each ordinary group has its own continued Multica chat; forum topics are isolated into separate chats.### Commandsdiff --git a/apps/docs/content/docs/telegram-bot-integration.zh.mdx b/apps/docs/content/docs/telegram-bot-integration.zh.mdxindex 74c14b5faa..b8f5420729 100644--- a/apps/docs/content/docs/telegram-bot-integration.zh.mdx+++ b/apps/docs/content/docs/telegram-bot-integration.zh.mdx@@ -20,7 +20,7 @@ Telegram 集成[由社区维护](/community-maintained):每个版本都会随1. 打开 [@BotFather](https://t.me/BotFather),发送 `/newbot`。2. 设置显示名称和一个以 `bot` 结尾的用户名。3. 复制 HTTP API token。-4. 保持 **Group Privacy** 开启。群聊里 Multica 只需要接收命令、明确的 @ 和对 Bot 消息的回复。+4. 默认保持 **Group Privacy** 开启,这是可见范围最小的配置:Telegram 只会把命令、明确的 @ 和对 Bot 消息的回复投递给 Bot。关闭它是可选项,能让 Bot 把群里周围的讨论作为上下文,代价是 Bot 会收到群里的每一条消息,详见[群聊与 forum topic](#群聊与-forum-topic)。<Callout type="warning">不要把 token 发到任务、聊天、日志或代码仓库。若已泄露,请在 @BotFather 中撤销,再用替换后的 token 重新连接。@@ -50,7 +50,7 @@ Multica 会实时请求 Telegram 验证 Bot,检查是否存在与长轮询冲### 群聊与 forum topic-把 Bot 加入群后,@它,或直接回复它发过的消息。被接受的消息会保留在持续的 Multica 对话中;未明确发给 Bot 的群聊内容不会被收集。回复其他成员的消息时必须同时 @ Bot,只有这种情况下,被引用消息的发送者及文字(或 caption)才会随新指令进入上下文;只回复成员而不 @ Bot 不会触发。普通群聊各自延续一段 Multica 对话;forum 的每个 topic 分别隔离。+把 Bot 加入群后,@它,或直接回复它发过的消息。被接受的消息会保留在持续的 Multica 对话中。未明确发给 Bot 的群消息本身不会开启对话,也不会单独形成一轮,但会被暂存在一个很小的内存缓冲里:每个群(或每个 forum topic)保留 Bot 收到的最近 10 条,服务器重启即清空。之后当有成员通过 @ 或回复 Bot 的消息向它发出指令时,这些暂存消息会作为只读上下文附在该轮指令之前,并随这一轮一起保存进对话记录。`/new` 开启的新对话不带这段上下文。缓冲里有什么取决于 Telegram 投递了什么:Group Privacy 开启时只有命令、明确的 @ 和对 Bot 的回复,所以上下文里只有之前明确发给它的消息。想让它看到普通群聊,请在 @BotFather 里关闭 Group Privacy,再把 Bot 移出群重新加入,此后 Bot 会收到群里的每一条消息。被设为群管理员的 Bot 无论隐私设置如何都会收到全部消息,因此不改 @BotFather 也会把普通群聊纳入上下文。回复其他成员的消息时必须同时 @ Bot,只有这种情况下,被引用消息的发送者及文字(或 caption)才会随新指令进入上下文;只回复成员而不 @ Bot 不会触发。普通群聊各自延续一段 Multica 对话;forum 的每个 topic 分别隔离。### 命令diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex e1e9992d6e..ea5e6db811 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1187,7 +1187,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// Per-installation inbound: the Supervisor builds + supervises one// long-polling loop per active Telegram installation.- telegram.RegisterTelegram(channelRegistry, telegram.ChannelDeps{Decrypt: box.Open, Logger: slog.Default()})+ telegram.RegisterTelegram(channelRegistry, telegram.ChannelDeps{+ Decrypt: box.Open,+ Logger: slog.Default(),+ RecentContextSize: telegram.DefaultRecentContextSize,+ })installSvc, ierr := telegram.NewInstallService(queries, pool, box, slog.Default())if ierr != nil {diff --git a/server/internal/integrations/telegram/inbound.go b/server/internal/integrations/telegram/inbound.goindex ce79b1d4db..6aaaa8eff4 100644--- a/server/internal/integrations/telegram/inbound.go+++ b/server/internal/integrations/telegram/inbound.go@@ -28,17 +28,33 @@ type telegramRawEvent struct {SenderName string `json:"sender_name,omitempty"`}-// inboundFromUpdate normalizes one Telegram update. ok=false means the update-// must not reach the core: bot/self messages, channel posts, edits (excluded-// via allowed_updates already), or unsupported media (the caller decides-// whether to send an "unsupported" notice for p2p).+// inboundFromUpdate normalizes one Telegram update without any recent group+// context. See inboundFromUpdateWithContext.+func inboundFromUpdate(u Update, botID int64, botUsername string) (channel.InboundMessage, bool) {+ return inboundFromUpdateWithContext(u, botID, botUsername, nil)+}++// inboundFromUpdateWithContext normalizes one Telegram update. ok=false means+// the update must not reach the core: bot/self messages, channel posts, edits+// (excluded via allowed_updates already), or unsupported media (the caller+// decides whether to send an "unsupported" notice for p2p).//// Group addressing policy mirrors Slack v1: a group message is addressed to// the bot only when it carries an explicit @bot mention or directly replies to-// one of the bot's messages. Privacy mode is left ON, so Telegram already-// withholds unaddressed group chatter from the bot; this check is the-// defense-in-depth for bots whose privacy mode was disabled in BotFather.-func inboundFromUpdate(u Update, botID int64, botUsername string) (channel.InboundMessage, bool) {+// one of the bot's messages. Telegram only withholds unaddressed group+// chatter while the bot's privacy mode is ON and the bot is not a group admin;+// the recent-context feature actively invites operators to turn privacy off,+// so this check — not Telegram — is what keeps unaddressed chatter from+// starting a turn.+//+// recent, when non-nil, supplies the preceding messages of the same+// chat/topic. They are inlined as a <recent_context> block ahead of an+// addressed group message (never p2p, never an unaddressed one, and never+// for /new — a new Chat must not inherit the previous Chat's ambient+// context), matching Lark's enricher composition: recent → quoted → own.+// Ambient context is not "selected" context: HasSelectedContext stays tied+// to the explicitly quoted reply.+func inboundFromUpdateWithContext(u Update, botID int64, botUsername string, recent recentContextSource) (channel.InboundMessage, bool) {m := u.Messageif m == nil || m.From == nil || m.From.IsBot || m.From.ID == botID {return channel.InboundMessage{}, false@@ -61,9 +77,11 @@ func inboundFromUpdate(u Update, botID int64, botUsername string) (channel.Inboucleaned := normalizeText(text, botUsername)commandText := cleanedforceFresh := false+ startChat := falseif control, ok := engine.ParseControlCommand(cleaned); ok {cleaned = control.BodyforceFresh = control.Kind == engine.ControlCommandFreshSession+ startChat = control.Kind == engine.ControlCommandNewChat}agentText := cleanedquotedHuman := m.ReplyToMessage != nil && m.ReplyToMessage.From != nil && !m.ReplyToMessage.From.IsBot@@ -71,6 +89,9 @@ func inboundFromUpdate(u Update, botID int64, botUsername string) (channel.Inbouif hasSelectedContext {agentText = enrichWithQuotedHumanMessage(cleaned, m.Chat.ID, m.ReplyToMessage)}+ if recent != nil && chatType == channel.ChatTypeGroup && addressed && !startChat {+ agentText = enrichWithRecentContext(agentText, m, recent)+ }senderID := strconv.FormatInt(m.From.ID, 10)chatID := strconv.FormatInt(m.Chat.ID, 10)@@ -228,6 +249,30 @@ func enrichWithQuotedHumanMessage(instruction string, chatID int64, quoted *Messreturn block + "\n\n" + instruction}+// enrichWithRecentContext prepends the chat/topic's preceding messages to the+// instruction. The trigger itself and an explicitly quoted parent are excluded+// from the window: the first is the instruction, the second is already+// rendered as <quoted_message>. An empty window leaves the text untouched.+func enrichWithRecentContext(instruction string, m *Message, recent recentContextSource) string {+ exclude := []int64{m.MessageID}+ if m.ReplyToMessage != nil {+ exclude = append(exclude, m.ReplyToMessage.MessageID)+ }+ var threadID int64+ if m.IsTopicMessage {+ threadID = m.MessageThreadID+ }+ entries := recent.Snapshot(m.Chat.ID, threadID, exclude...)+ if len(entries) == 0 {+ return instruction+ }+ block := renderRecentContextBlock(entries)+ if instruction == "" {+ return block+ }+ return block + "\n\n" + instruction+}+func commandTargetsBot(command, botUsername string) bool {at := strings.LastIndexByte(command, '@')return at >= 0 && strings.EqualFold(command[at+1:], botUsername)diff --git a/server/internal/integrations/telegram/recent_context.go b/server/internal/integrations/telegram/recent_context.gonew file mode 100644index 0000000000..598eac2b82--- /dev/null+++ b/server/internal/integrations/telegram/recent_context.go@@ -0,0 +1,203 @@+package telegram++import (+ "fmt"+ "strings"+ "sync"+)++// This file holds the Telegram counterpart of Lark's <recent_context>+// prefetch (lark/inbound_enricher.go, MUL-3084): when a member addresses the+// bot in a group (@-mention or a reply to one of its messages), the+// surrounding conversation is inlined ahead of their instruction so the agent+// sees more than the single addressed line.+//+// Lark can fetch that window on demand (im/v1/messages.list). The Telegram+// Bot API has no history endpoint — getUpdates is consume-once — so the+// polling loop keeps a small in-memory ring of the group messages it has+// already seen, per chat (and per forum topic), and reads the window back+// from that ring when an addressed message arrives. The ring is scoped to+// one installation's polling loop and lives only as long as the loop does: a+// restart starts empty, which is the accepted trade-off for keeping this out+// of the database.+//+// Retention contract: a non-addressed group message never creates a session+// or a turn on its own (MUL-2671). It is held in this in-memory ring, and once+// an addressed turn pulls it into its <recent_context> block it is persisted+// with that turn — the rewritten Text becomes the turn's+// chat_message.content, exactly as Lark's enricher documents for its own+// block. What the ring can hold depends on what Telegram delivers: with Group+// Privacy on, only commands, explicit @-mentions and replies to the bot; with+// it off, or for a bot that is a group admin, every group message.++// DefaultRecentContextSize is the window the production wiring uses: the+// number of preceding group messages kept per chat and inlined on an+// @-mention. Mirrors lark.DefaultRecentContextSize.+const DefaultRecentContextSize = 10++const (+ // maxRecentContextChats bounds the number of distinct chat/topic rings one+ // installation keeps; the least recently updated ring is evicted past it.+ maxRecentContextChats = 256+ // maxRecentContextTextRunes truncates one buffered message so a pasted wall+ // of text cannot dominate the prompt or the buffer.+ maxRecentContextTextRunes = 1000+)++// recentEntry is one buffered group message.+type recentEntry struct {+ MessageID int64+ Sender string+ Text string+}++// recentContextSource is what the inbound translation needs from the buffer:+// the preceding messages of one chat/topic, minus the ids the caller already+// renders elsewhere (the trigger itself and its quoted parent).+type recentContextSource interface {+ Snapshot(chatID, threadID int64, exclude ...int64) []recentEntry+}++// recentContextBuffer keeps the last N human group messages per chat/topic.+// Safe for concurrent use; the polling loop is single-goroutine but tests and+// future fan-out should not depend on that.+type recentContextBuffer struct {+ size int++ mu sync.Mutex+ rings map[recentKey]*recentRing+ clock uint64+}++type recentKey struct {+ chatID int64+ threadID int64+}++type recentRing struct {+ entries []recentEntry+ touched uint64+}++// newRecentContextBuffer returns nil when size <= 0, which disables the+// feature entirely (nil receivers are safe on every method).+func newRecentContextBuffer(size int) *recentContextBuffer {+ if size <= 0 {+ return nil+ }+ return &recentContextBuffer{size: size, rings: map[recentKey]*recentRing{}}+}++// Record appends one message to its chat/topic ring, dropping the oldest+// entry past the window and the least recently updated ring past the chat+// cap.+func (b *recentContextBuffer) Record(chatID, threadID int64, e recentEntry) {+ if b == nil {+ return+ }+ e.Text = truncateRunes(e.Text, maxRecentContextTextRunes)+ b.mu.Lock()+ defer b.mu.Unlock()+ b.clock+++ key := recentKey{chatID: chatID, threadID: threadID}+ ring, ok := b.rings[key]+ if !ok {+ if len(b.rings) >= maxRecentContextChats {+ b.evictOldestLocked()+ }+ ring = &recentRing{}+ b.rings[key] = ring+ }+ ring.touched = b.clock+ ring.entries = append(ring.entries, e)+ if extra := len(ring.entries) - b.size; extra > 0 {+ ring.entries = append([]recentEntry(nil), ring.entries[extra:]...)+ }+}++// Snapshot returns the ring's entries oldest-first, minus excluded ids. The+// returned slice is a copy the caller may keep.+func (b *recentContextBuffer) Snapshot(chatID, threadID int64, exclude ...int64) []recentEntry {+ if b == nil {+ return nil+ }+ b.mu.Lock()+ defer b.mu.Unlock()+ ring, ok := b.rings[recentKey{chatID: chatID, threadID: threadID}]+ if !ok {+ return nil+ }+ skip := make(map[int64]bool, len(exclude))+ for _, id := range exclude {+ skip[id] = true+ }+ out := make([]recentEntry, 0, len(ring.entries))+ for _, e := range ring.entries {+ if skip[e.MessageID] {+ continue+ }+ out = append(out, e)+ }+ return out+}++func (b *recentContextBuffer) evictOldestLocked() {+ var (+ oldestKey recentKey+ oldest uint64+ found bool+ )+ for k, r := range b.rings {+ if !found || r.touched < oldest {+ oldestKey, oldest, found = k, r.touched, true+ }+ }+ if found {+ delete(b.rings, oldestKey)+ }+}++// recentEntryFromMessage renders one Telegram message the way a group member+// saw it: raw text or caption (bot mentions included), or a typed placeholder+// for media without a caption. Never called for bot senders — the polling+// loop drops those before recording, and the bot's own replies never arrive+// through getUpdates anyway.+func recentEntryFromMessage(m *Message) recentEntry {+ text := m.Text+ if text == "" {+ text = m.Caption+ }+ if strings.TrimSpace(text) == "" {+ text = fmt.Sprintf("[%s message]", classifyMessage(m))+ }+ sender := "Unknown user"+ if m.From != nil {+ if name := senderDisplayName(m.From); name != "" {+ sender = name+ }+ }+ return recentEntry{MessageID: m.MessageID, Sender: sender, Text: text}+}++// renderRecentContextBlock formats the window exactly like Lark's enricher:+// one "[<speaker>]: <text>" line per message, oldest-first, so an agent+// prompt reads the same across channels. Callers pass a non-empty slice.+func renderRecentContextBlock(entries []recentEntry) string {+ lines := make([]string, 0, len(entries))+ for _, e := range entries {+ lines = append(lines, fmt.Sprintf("[%s]: %s", e.Sender, e.Text))+ }+ return fmt.Sprintf("<recent_context count=\"%d\">\n%s\n</recent_context>",+ len(entries), strings.Join(lines, "\n"))+}++func truncateRunes(s string, max int) string {+ if max <= 0 {+ return s+ }+ runes := []rune(s)+ if len(runes) <= max {+ return s+ }+ return string(runes[:max]) + "…"+}diff --git a/server/internal/integrations/telegram/recent_context_test.go b/server/internal/integrations/telegram/recent_context_test.gonew file mode 100644index 0000000000..52cd7f93ff--- /dev/null+++ b/server/internal/integrations/telegram/recent_context_test.go@@ -0,0 +1,237 @@+package telegram++import (+ "context"+ "fmt"+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/integrations/channel"+)++// groupUpdate builds one human message in a supergroup, optionally inside a+// forum topic and optionally replying to another message.+func groupUpdate(id int64, from *User, text string, reply *Message, topic int64) Update {+ m := &Message{+ MessageID: id,+ From: from,+ Chat: Chat{ID: -100200, Type: "supergroup"},+ Text: text,+ ReplyToMessage: reply,+ }+ if topic != 0 {+ m.IsTopicMessage = true+ m.MessageThreadID = topic+ }+ return Update{UpdateID: id, Message: m}+}++func TestRecentContextBufferKeepsWindowPerChatAndTopic(t *testing.T) {+ b := newRecentContextBuffer(3)+ for i := int64(1); i <= 5; i++ {+ b.Record(-1, 0, recentEntry{MessageID: i, Sender: "Ada", Text: fmt.Sprintf("m%d", i)})+ }+ b.Record(-1, 7, recentEntry{MessageID: 100, Sender: "Bob", Text: "topic only"})+ b.Record(-2, 0, recentEntry{MessageID: 200, Sender: "Cy", Text: "other chat"})++ got := b.Snapshot(-1, 0)+ if len(got) != 3 || got[0].MessageID != 3 || got[2].MessageID != 5 {+ t.Fatalf("window should keep the newest 3 oldest-first, got %+v", got)+ }+ if got := b.Snapshot(-1, 0, 4); len(got) != 2 || got[0].MessageID != 3 || got[1].MessageID != 5 {+ t.Fatalf("exclude should drop id 4, got %+v", got)+ }+ if got := b.Snapshot(-1, 7); len(got) != 1 || got[0].Text != "topic only" {+ t.Fatalf("topic ring must be isolated from the chat ring, got %+v", got)+ }+ if got := b.Snapshot(-3, 0); got != nil {+ t.Fatalf("unknown chat should snapshot nil, got %+v", got)+ }++ var nilBuf *recentContextBuffer+ nilBuf.Record(-1, 0, recentEntry{MessageID: 1})+ if got := nilBuf.Snapshot(-1, 0); got != nil {+ t.Fatalf("nil buffer must be inert, got %+v", got)+ }+ if newRecentContextBuffer(0) != nil {+ t.Fatal("size 0 must disable the buffer")+ }+}++func TestRecentContextBufferEvictsLeastRecentlyUpdatedChat(t *testing.T) {+ b := newRecentContextBuffer(2)+ for i := int64(1); i <= maxRecentContextChats; i++ {+ b.Record(i, 0, recentEntry{MessageID: 1, Text: "x"})+ }+ // Touch chat 1 so chat 2 becomes the stalest, then overflow by one.+ b.Record(1, 0, recentEntry{MessageID: 2, Text: "y"})+ b.Record(maxRecentContextChats+1, 0, recentEntry{MessageID: 1, Text: "z"})+ if got := b.Snapshot(2, 0); got != nil {+ t.Fatalf("stalest chat should be evicted, got %+v", got)+ }+ if got := b.Snapshot(1, 0); len(got) != 2 {+ t.Fatalf("recently touched chat must survive, got %+v", got)+ }+ if got := b.Snapshot(maxRecentContextChats+1, 0); len(got) != 1 {+ t.Fatalf("new chat must be recorded, got %+v", got)+ }+}++func TestRecentContextBufferTruncatesLongMessages(t *testing.T) {+ b := newRecentContextBuffer(1)+ long := strings.Repeat("字", maxRecentContextTextRunes+5)+ b.Record(-1, 0, recentEntry{MessageID: 1, Sender: "Ada", Text: long})+ got := b.Snapshot(-1, 0)+ if len(got) != 1 || len([]rune(got[0].Text)) != maxRecentContextTextRunes+1 || !strings.HasSuffix(got[0].Text, "…") {+ t.Fatalf("text should be cut to %d runes plus an ellipsis, got %d runes", maxRecentContextTextRunes, len([]rune(got[0].Text)))+ }+}++func TestRecentEntryFromMessageRendersMediaPlaceholder(t *testing.T) {+ e := recentEntryFromMessage(&Message{MessageID: 4, From: &User{ID: 1, FirstName: "Ada"}, Photo: []any{1}})+ if e.Sender != "Ada" || e.Text != "[image message]" {+ t.Fatalf("media without caption should render a typed placeholder, got %+v", e)+ }+ e = recentEntryFromMessage(&Message{MessageID: 5, Photo: []any{1}, Caption: "see this"})+ if e.Sender != "Unknown user" || e.Text != "see this" {+ t.Fatalf("caption should win and a missing sender should fall back, got %+v", e)+ }+}++func TestInboundGroupMentionInlinesRecentContext(t *testing.T) {+ ada := &User{ID: 111, FirstName: "Ada"}+ bob := &User{ID: 222, FirstName: "Bob"}+ b := newRecentContextBuffer(DefaultRecentContextSize)+ b.Record(-100200, 0, recentEntry{MessageID: 1, Sender: "Ada", Text: "deploy is failing on staging"})+ b.Record(-100200, 0, recentEntry{MessageID: 2, Sender: "Bob", Text: "I think it's the env file"})+ // The trigger itself is in the ring too (dispatch records every group+ // message) and must be filtered out of its own context.+ b.Record(-100200, 0, recentEntry{MessageID: 3, Sender: "Ada", Text: "@my_bot what should we check first?"})++ msg, ok := inboundFromUpdateWithContext(groupUpdate(3, ada, "@my_bot what should we check first?", nil, 0), 999, "my_bot", b)+ if !ok || !msg.AddressedToBot {+ t.Fatalf("mention must be addressed: ok=%v msg=%+v", ok, msg)+ }+ want := "<recent_context count=\"2\">\n[Ada]: deploy is failing on staging\n[Bob]: I think it's the env file\n</recent_context>\n\nwhat should we check first?"+ if msg.Text != want {+ t.Fatalf("Text =\n%s\nwant\n%s", msg.Text, want)+ }+ if msg.CommandText != "what should we check first?" {+ t.Fatalf("CommandText must stay the bare instruction, got %q", msg.CommandText)+ }+ if msg.HasSelectedContext {+ t.Fatal("ambient recent context is not selected context")+ }++ // Reply-to-human + mention: quoted parent is rendered once, as+ // <quoted_message>, and dropped from the recent window; composition is+ // recent → quoted → own.+ quoted := &Message{MessageID: 2, From: bob, Text: "I think it's the env file"}+ msg, ok = inboundFromUpdateWithContext(groupUpdate(3, ada, "@my_bot is he right?", quoted, 0), 999, "my_bot", b)+ if !ok || !msg.HasSelectedContext {+ t.Fatalf("quoted mention must be selected context: ok=%v msg=%+v", ok, msg)+ }+ recentIdx := strings.Index(msg.Text, "<recent_context count=\"1\">")+ quotedIdx := strings.Index(msg.Text, "<quoted_message")+ ownIdx := strings.Index(msg.Text, "is he right?")+ if recentIdx != 0 || quotedIdx < recentIdx || ownIdx < quotedIdx {+ t.Fatalf("blocks out of order:\n%s", msg.Text)+ }+ if strings.Count(msg.Text, "I think it's the env file") != 1 {+ t.Fatalf("quoted parent must not repeat inside recent context:\n%s", msg.Text)+ }+}++func TestInboundRecentContextScopedToTopic(t *testing.T) {+ ada := &User{ID: 111, FirstName: "Ada"}+ b := newRecentContextBuffer(DefaultRecentContextSize)+ b.Record(-100200, 0, recentEntry{MessageID: 1, Sender: "Ada", Text: "general chatter"})+ b.Record(-100200, 42, recentEntry{MessageID: 2, Sender: "Bob", Text: "topic chatter"})++ msg, ok := inboundFromUpdateWithContext(groupUpdate(3, ada, "@my_bot summarize", nil, 42), 999, "my_bot", b)+ if !ok || !strings.Contains(msg.Text, "[Bob]: topic chatter") || strings.Contains(msg.Text, "general chatter") {+ t.Fatalf("topic mention must only see its own topic:\n%s", msg.Text)+ }+}++func TestInboundRecentContextSkipped(t *testing.T) {+ ada := &User{ID: 111, FirstName: "Ada"}+ b := newRecentContextBuffer(DefaultRecentContextSize)+ b.Record(-100200, 0, recentEntry{MessageID: 1, Sender: "Bob", Text: "earlier"})+ b.Record(555, 0, recentEntry{MessageID: 1, Sender: "Bob", Text: "never buffered in practice"})++ cases := []struct {+ name string+ u Update+ }{+ {"unaddressed group message", groupUpdate(3, ada, "plain chatter", nil, 0)},+ {"/new starts a chat without ambient context", groupUpdate(3, ada, "@my_bot /new fresh topic", nil, 0)},+ {"p2p", Update{UpdateID: 3, Message: &Message{MessageID: 3, From: ada, Chat: Chat{ID: 555, Type: "private"}, Text: "hi"}}},+ }+ for _, c := range cases {+ msg, ok := inboundFromUpdateWithContext(c.u, 999, "my_bot", b)+ if !ok {+ t.Fatalf("%s: expected ok", c.name)+ }+ if strings.Contains(msg.Text, "<recent_context") {+ t.Fatalf("%s: must not carry recent context, got %q", c.name, msg.Text)+ }+ }+ // /clear keeps the window: it resets agent memory, not the conversation.+ msg, _ := inboundFromUpdateWithContext(groupUpdate(3, ada, "@my_bot /clear again", nil, 0), 999, "my_bot", b)+ if !msg.ForceFresh || !strings.Contains(msg.Text, "[Bob]: earlier") {+ t.Fatalf("/clear should keep recent context, got forceFresh=%v text=%q", msg.ForceFresh, msg.Text)+ }+ // nil source (feature disabled) leaves an addressed message untouched.+ msg, _ = inboundFromUpdateWithContext(groupUpdate(3, ada, "@my_bot hello", nil, 0), 999, "my_bot", nil)+ if msg.Text != "hello" {+ t.Fatalf("disabled buffer must not alter text, got %q", msg.Text)+ }+}++func TestDispatchBuffersGroupMessagesForLaterMentions(t *testing.T) {+ var seen []channel.InboundMessage+ c := &telegramChannel{+ botID: 999, botUsername: "my_bot",+ handler: func(_ context.Context, msg channel.InboundMessage) error {+ seen = append(seen, msg)+ return nil+ },+ logger: testLogger(),+ recent: newRecentContextBuffer(DefaultRecentContextSize),+ }+ ada := &User{ID: 111, FirstName: "Ada"}+ bob := &User{ID: 222, FirstName: "Bob"}+ ctx := context.Background()++ // Unaddressed chatter still reaches the handler (Router audits the drop)+ // and is buffered. Unaddressed media is buffered as a placeholder and+ // never sent an "unsupported" notice.+ if err := c.dispatch(ctx, groupUpdate(1, ada, "deploy is failing on staging", nil, 0)); err != nil {+ t.Fatal(err)+ }+ if err := c.dispatch(ctx, Update{UpdateID: 2, Message: &Message{MessageID: 2, From: bob, Chat: Chat{ID: -100200, Type: "supergroup"}, Photo: []any{1}}}); err != nil {+ t.Fatal(err)+ }+ // Another bot's message is never buffered.+ if err := c.dispatch(ctx, groupUpdate(3, &User{ID: 5, IsBot: true, FirstName: "Other"}, "beep", nil, 0)); err != nil {+ t.Fatal(err)+ }+ if err := c.dispatch(ctx, groupUpdate(4, ada, "@my_bot what should we check first?", nil, 0)); err != nil {+ t.Fatal(err)+ }+ if len(seen) != 2 || seen[0].AddressedToBot || !seen[1].AddressedToBot {+ t.Fatalf("handler calls = %+v", seen)+ }+ want := "<recent_context count=\"2\">\n[Ada]: deploy is failing on staging\n[Bob]: [image message]\n</recent_context>\n\nwhat should we check first?"+ if seen[1].Text != want {+ t.Fatalf("mention Text =\n%s\nwant\n%s", seen[1].Text, want)+ }+ // The mention itself is now part of the window for the next one.+ if err := c.dispatch(ctx, groupUpdate(5, bob, "@my_bot and then?", nil, 0)); err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(seen[2].Text, "[Ada]: @my_bot what should we check first?") {+ t.Fatalf("previous mention should appear as members saw it:\n%s", seen[2].Text)+ }+}diff --git a/server/internal/integrations/telegram/telegram_channel.go b/server/internal/integrations/telegram/telegram_channel.goindex 6a0ae47894..e795bb2f43 100644--- a/server/internal/integrations/telegram/telegram_channel.go+++ b/server/internal/integrations/telegram/telegram_channel.go@@ -26,6 +26,9 @@ type telegramChannel struct {api *botAPIhandler channel.InboundHandlerlogger *slog.Logger+ // recent buffers the group messages this loop has seen so an @-mention can+ // carry the surrounding conversation (see recent_context.go). Nil disables.+ recent *recentContextBuffer}// pollRetryDelay spaces retries after a transient getUpdates failure inside@@ -112,10 +115,11 @@ func (c *telegramChannel) Connect(ctx context.Context) error {// duplicates). Product drops return nil. Unsupported media in a private chat,// or explicitly addressed to the bot in a group, gets a courteous notice.func (c *telegramChannel) dispatch(ctx context.Context, u Update) error {- msg, ok := inboundFromUpdate(u, c.botID, c.botUsername)+ msg, ok := inboundFromUpdateWithContext(u, c.botID, c.botUsername, c.recent)if !ok {return nil}+ c.recordRecent(u.Message, msg)if msg.Type != channel.MsgTypeText {if msg.Source.ChatType == channel.ChatTypeP2P || msg.AddressedToBot {c.notifyUnsupported(ctx, u)@@ -132,6 +136,22 @@ func (c *telegramChannel) dispatch(ctx context.Context, u Update) error {return nil}+// recordRecent buffers a human group message after it has been translated,+// so the window an @-mention reads never contains the mention itself. Runs+// for every group message the loop sees — addressed or not, text or media —+// because the next @-mention wants the conversation as members saw it. p2p+// messages are never buffered: a 1:1 chat is already one continuous session.+func (c *telegramChannel) recordRecent(m *Message, msg channel.InboundMessage) {+ if c.recent == nil || m == nil || msg.Source.ChatType != channel.ChatTypeGroup {+ return+ }+ var threadID int64+ if m.IsTopicMessage {+ threadID = m.MessageThreadID+ }+ c.recent.Record(m.Chat.ID, threadID, recentEntryFromMessage(m))+}+const (issueErrorReplyTimeout = 5 * time.SecondissueDispatchFailedText = "⚠️ I couldn't create that issue because an internal error occurred. Please try again."@@ -211,6 +231,12 @@ type ChannelDeps struct {// HTTPClient overrides the polling client (tests). Nil uses a default with// a timeout sized for long polling.HTTPClient *http.Client+ // RecentContextSize caps how many preceding group messages each polling+ // loop buffers per chat/topic and inlines as a <recent_context> block when+ // a member @-mentions the bot. <=0 disables the feature; the production+ // wiring sets DefaultRecentContextSize. Mirrors+ // lark.InboundEnricherConfig.RecentContextSize.+ RecentContextSize int}// RegisterTelegram registers the per-installation Telegram Factory so the@@ -248,6 +274,7 @@ func newTelegramFactory(deps ChannelDeps) channel.Factory {api: newBotAPI(deps.APIBase, token, deps.HTTPClient),handler: cfg.Handler,logger: logger,+ recent: newRecentContextBuffer(deps.RecentContextSize),}, nil}}