Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6166: feat(telegram): add Telegram channel integration (#6944)

Reiser Xu67c6aa05c4ac
diff --git a/HANDOFF-telegram.md b/HANDOFF-telegram.md
new file mode 100644
index 0000000000..cee9ec9072
--- /dev/null
+++ b/HANDOFF-telegram.md
@@ -0,0 +1,101 @@
+# Telegram integration implementation notes
+
+Status: complete for the text-message scope described below.
+
+This document records the architecture and operating contract of Multica's
+Telegram channel. Setup instructions for operators live in the localized
+Telegram Bot integration guides under `apps/docs/content/docs/`.
+
+## Product contract
+
+| Area | Behavior |
+| --- | --- |
+| Transport | Telegram Bot API `getUpdates` long polling; no public callback URL is required |
+| Installation | One Telegram bot token belongs to one active Multica workspace and agent |
+| Identity | Every Telegram sender completes a one-time private account binding |
+| Private chat | Text and slash commands are accepted directly |
+| Group chat | A message is accepted when it mentions or replies to the bot; replying to a human additionally requires an explicit bot mention and includes that quoted sender/text |
+| Forum topic | Session and reply routing retain the Telegram topic ID |
+| Conversation | `/new` and `/issue` follow the shared channel command contract; accepted messages persist while unaddressed group chatter is not collected |
+| Replies | The triggering Telegram message is quoted; task output is streamed by editing the first reply |
+| Media | Text-only in this release; addressed non-text input receives an explicit unsupported-message response and creates no task |
+| Token storage | Bot tokens are encrypted with `MULTICA_TELEGRAM_SECRET_KEY` and never returned by management APIs |
+
+## Architecture
+
+The implementation uses the shared channel framework rather than a parallel
+Telegram-specific execution path:
+
+- `channel.Channel`, `channel.Registry`, and `engine.Supervisor` own lifecycle,
+ retries, routing, and task dispatch.
+- `server/internal/integrations/telegram/` owns Bot API transport, installation,
+ binding, inbound parsing, outbound delivery, Markdown conversion, and reply
+ streaming.
+- The generic channel installation, binding, session, and identity tables are
+ reused with `channel_type = 'telegram'`.
+- Migrations 349 and 350 extend the issue-origin constraint with
+ `telegram_chat` using the repository's two-phase `NOT VALID` / `VALIDATE`
+ pattern.
+- `packages/core/` provides the typed management client and React Query keys;
+ `packages/views/` provides shared settings, agent integration, and binding
+ views; `apps/web/` provides the bind route.
+
+## Safety boundaries
+
+- Installation verifies the token with `getMe` before persistence. Transport
+ failures and credential rejection remain distinct so a network outage does
+ not encourage unnecessary credential rotation.
+- Long polling refuses bots with an active outgoing webhook and never deletes
+ another system's webhook automatically.
+- Group binding links are never posted publicly. A group sender is directed to
+ start a private bot chat to complete binding.
+- Human-message quote context is included only when a group member replies and
+ explicitly mentions the bot. The quoted sender and text/caption are persisted
+ with the accepted instruction; `/new` starts a fresh session without dropping
+ that selected quote. Ambient group chatter is never collected.
+- Chat-level edit cooldown and `retry_after` state survive sequential tasks in
+ a hard-bounded cache. When capacity pressure compresses an active chat entry,
+ its deadline is merged into a conservative per-installation fallback so a
+ recreated chat never calls Telegram before the mandatory wait expires.
+- `EventChatDone` only enqueues in-process terminal delivery, so Telegram HTTP
+ latency and repeated `retry_after` waits cannot block the synchronous event
+ bus or realtime clients. A keyed scheduler preserves per-session FIFO order;
+ normally one chat's backoff consumes no worker. If cache pressure compresses
+ exact backoff state, other chats under the same Bot installation may be
+ conservatively delayed. The terminal queue has fixed count, per-session, and
+ byte limits; overflow is rejected and logged without blocking the event bus.
+ Per-reply chunk progress prevents successful chunks from being repeated after
+ a 429. Non-429 errors remain non-retriable.
+- On shutdown, queued, retry-waiting, and in-flight terminal jobs are abandoned
+ after request cancellation, and their local stream/schedule references are
+ released. The fixed-capacity in-process queue is not restart-durable.
+- Retry-pending task failures clear the superseded stream without showing a
+ terminal failure notice; only a terminal failure changes or sends that notice.
+- Outbound delivery requires authoritative Telegram task provenance and fails
+ closed when task or origin lookup cannot be completed.
+- Telegram API errors are sanitized so bot tokens cannot enter logs or API
+ responses.
+
+## Verification
+
+The implementation is covered by Go protocol, lifecycle, security, migration,
+and race tests; TypeScript API-schema, query, settings, binding-page, locale,
+and UI tests; production Web/Docs/Desktop builds; and a real private-chat
+Telegram regression covering binding, commands, task execution, issue origin,
+streamed quoted replies, reconnect behavior, UTF-16 content, long replies, and
+the text-only media response.
+
+The detailed evidence and channel capability comparison are maintained in
+`docs/telegram-channel-review-2026-08-08.md`.
+
+## Deployment prerequisites
+
+- Set a 32-byte base64 `MULTICA_TELEGRAM_SECRET_KEY` in the server environment.
+- Ensure the server can reach `https://api.telegram.org/`; the standard Go
+ transport honors `HTTPS_PROXY` when a deployment requires one.
+- Apply repository migrations before enabling the integration.
+- Keep Telegram privacy mode enabled unless a deployment deliberately wants
+ the bot to receive every group message.
+
+No production deployment, production configuration change, or real-user data
+operation is part of this contribution.
diff --git a/apps/docs/content/docs/channels.ja.mdx b/apps/docs/content/docs/channels.ja.mdx
index 30afa8ef52..800304545d 100644
--- a/apps/docs/content/docs/channels.ja.mdx
+++ b/apps/docs/content/docs/channels.ja.mdx
@@ -1,37 +1,40 @@
---
title: チャット連携
-description: Multica のエージェントを Feishu、Lark、Slack、DingTalk、WeCom に接続し、チームが普段使っているチャットツールから利用する方法を説明します。
+description: Multica のエージェントを Feishu、Lark、Slack、DingTalk、WeCom、Telegram に接続し、チームが普段使っているチャットツールから利用する方法を説明します。
---
import { Callout } from "fumadocs-ui/components/callout";
チャット連携を使うと、Multica を開かなくても、エージェントへの質問、グループチャットでの @メンション、チャット画面からのイシュー作成ができます。
-現在は Feishu/Lark、Slack、DingTalk、WeCom に対応しています。セッション、ユーザー識別、実行の仕組みは共通ですが、インストール方法が異なります。
+現在は Feishu/Lark、Slack、DingTalk、WeCom、Telegram に対応しています。セッション、ユーザー識別、実行の仕組みは共通ですが、インストール方法が異なります。
## プラットフォームを選ぶ
-| | Feishu / Lark | Slack | DingTalk | WeCom |
-|---|---|---|---|---|
-| インストール | Multica で QR コードを生成し、Feishu でスキャンして認証 | Slack でアプリを作成し、2 つのトークンを Multica に入力 | 社内アプリと Stream モードのロボットを作成し、AppKey と AppSecret を Multica に入力 | WeCom 管理コンソールで常時接続を有効にしたスマートボットを作成し、Bot ID と Secret を Multica に入力 |
-| エージェントとの DM | 対応 | 対応 | 対応 | 対応 |
-| グループまたはチャンネル | Bot を @メンションするとトリガー | Bot を @メンションするとトリガー | Bot を @メンションするとトリガー | Bot を @メンションするとトリガー |
-| イシューの作成 | `/issue` メッセージコマンド。入力内容からそのまま作成 | `/issue` スラッシュコマンド。エージェントが説明を整理してから作成 | `/issue` メッセージコマンド。入力内容からそのまま作成 | `/issue` メッセージコマンド。入力内容からそのまま作成 |
-| 接続方式 | プラットフォームの常時接続 | Socket Mode | Stream モード | プラットフォームの常時接続 |
+| | Feishu / Lark | Slack | DingTalk | WeCom | Telegram |
+|---|---|---|---|---|---|
+| インストール | Multica で QR コードを生成し、Feishu でスキャンして認証 | Slack でアプリを作成し、2 つのトークンを Multica に入力 | 社内アプリと Stream モードのロボットを作成し、AppKey と AppSecret を Multica に入力 | WeCom 管理コンソールで常時接続を有効にしたスマートボットを作成し、Bot ID と Secret を Multica に入力 | @BotFather で Bot を作成し、token を Multica に入力 |
+| エージェントとの DM | 対応 | 対応 | 対応 | 対応 | 対応 |
+| グループまたはチャンネル | Bot を @メンションするとトリガー | Bot を @メンションするとトリガー | Bot を @メンションするとトリガー | Bot を @メンションするとトリガー | Bot を @メンション、または Bot に返信するとトリガー |
+| イシューの作成 | `/issue` メッセージコマンド。入力内容からそのまま作成 | `/issue` スラッシュコマンド。エージェントが説明を整理してから作成 | `/issue` メッセージコマンド。入力内容からそのまま作成 | `/issue` メッセージコマンド。入力内容からそのまま作成 | `/issue` メッセージコマンド。入力内容からそのまま作成 |
+| 接続方式 | プラットフォームの常時接続 | Socket Mode | Stream モード | プラットフォームの常時接続 | `getUpdates` long polling |
新規接続は現在、中国本土版の Feishu でのみ利用できます。既存の国際版 Lark 接続は、引き続き利用および管理できます。
各 Bot は 1 つの Multica エージェントに紐づきます。同じチャットプラットフォームで複数のエージェントを使う場合は、エージェントごとに Bot を接続してください。
-DingTalk と WeCom はコミュニティメンテナンスです。各リリースに含まれますが、公式サポート SLA はありません。問題は [GitHub issues](https://github.com/multica-ai/multica/issues) で報告してください。
+DingTalk、WeCom、Telegram はコミュニティメンテナンスです。各リリースに含まれますが、公式サポート SLA はありません。問題は [GitHub issues](https://github.com/multica-ai/multica/issues) で報告してください。
WeCom が現在扱えるのはテキストメッセージのみです。音声、画像、ファイルのメッセージにはその旨の短い返信が返り、エージェントには渡されません。
+Telegram が現在扱えるのはテキストメッセージのみです。未対応のメディアにはその旨の短い返信が返り、エージェントには渡されません。
+
詳しい手順:
- [Feishu / Lark Bot 連携](/lark-bot-integration)
- [Slack Bot 連携](/slack-bot-integration)
- [DingTalk Bot 連携](/dingtalk-bot-integration)
+- [Telegram Bot 連携](/telegram-bot-integration)
## メッセージが処理される流れ
@@ -51,6 +54,7 @@ Bot を @メンションしていないチャンネルメッセージは、エ
- Slack は DM をチャンネルごとに分けます。チャンネル内では、スレッドごとに独立したセッションが保持されます。
- DingTalk は conversation ごとにセッションを分けます。DM とグループはそれぞれのセッションを継続します。
- WeCom はチャットごとにセッションを分けます。DM とグループチャットはそれぞれのセッションを継続します。
+- Telegram はチャットごとにセッションを分け、forum topic は topic ごとに分離します。
チャンネルで追加の依頼を送る場合も、Bot を再度 @メンションする必要があります。エージェントが受け取るのは自分宛てのメッセージだけで、チャンネルの履歴全体を自動的に読み取ることはありません。
@@ -79,6 +83,7 @@ MULTICA_LARK_SECRET_KEY=<base64-encoded 32-byte key>
MULTICA_SLACK_SECRET_KEY=<base64-encoded 32-byte key>
MULTICA_DINGTALK_SECRET_KEY=<base64-encoded 32-byte key>
MULTICA_WECOM_SECRET_KEY=<base64-encoded 32-byte key>
+MULTICA_TELEGRAM_SECRET_KEY=<base64-encoded 32-byte key>
```
これらのキーは、保存された Bot の認証情報を暗号化します。生成、保管、ローテーションの方法は[環境変数](/environment-variables)を参照してください。Multica Cloud ではすでに設定済みです。
@@ -90,4 +95,5 @@ WeCom はさらにバックエンドを**単一レプリカ**で運用する必
- [Feishu / Lark Bot 連携](/lark-bot-integration)
- [Slack Bot 連携](/slack-bot-integration)
- [DingTalk Bot 連携](/dingtalk-bot-integration)
+- [Telegram Bot 連携](/telegram-bot-integration)
- [エージェントとチャットする](/chat)
diff --git a/apps/docs/content/docs/channels.ko.mdx b/apps/docs/content/docs/channels.ko.mdx
index 8eac47d8ed..f60f44cd3b 100644
--- a/apps/docs/content/docs/channels.ko.mdx
+++ b/apps/docs/content/docs/channels.ko.mdx
@@ -1,37 +1,40 @@
---
title: 채팅 연동
-description: Multica 에이전트를 Feishu, Lark, Slack, DingTalk 또는 WeCom에 연결해 팀이 이미 사용하는 채팅 도구에서 활용합니다.
+description: Multica 에이전트를 Feishu, Lark, Slack, DingTalk, WeCom 또는 Telegram에 연결해 팀이 이미 사용하는 채팅 도구에서 활용합니다.
---
import { Callout } from "fumadocs-ui/components/callout";
채팅 연동을 사용하면 팀이 Multica를 열지 않고도 에이전트에게 바로 질문하고, 그룹 채팅에서 @멘션하거나, 채팅 창에서 이슈를 만들 수 있습니다.
-현재 Feishu/Lark, Slack, DingTalk, WeCom을 지원합니다. 같은 대화, 신원, 실행 메커니즘을 사용하지만 설치 방법은 다릅니다.
+현재 Feishu/Lark, Slack, DingTalk, WeCom, Telegram을 지원합니다. 같은 대화, 신원, 실행 메커니즘을 사용하지만 설치 방법은 다릅니다.
## 플랫폼 선택
-| | Feishu / Lark | Slack | DingTalk | WeCom |
-|---|---|---|---|---|
-| 설치 방법 | Multica에서 QR 코드를 만든 뒤 Feishu로 스캔해 승인 | Slack에서 app을 만든 뒤 두 token을 Multica에 입력 | 사내 app과 Stream 모드 로봇을 만든 뒤 AppKey와 AppSecret을 Multica에 입력 | WeCom 관리자 콘솔에서 장기 연결을 켠 스마트 봇을 만든 뒤 Bot ID와 Secret을 Multica에 입력 |
-| 에이전트와 DM | 지원 | 지원 | 지원 | 지원 |
-| 그룹 채팅 또는 채널 | Bot을 @멘션하면 트리거 | Bot을 @멘션하면 트리거 | Bot을 @멘션하면 트리거 | Bot을 @멘션하면 트리거 |
-| 이슈 만들기 | `/issue` 메시지 명령으로 입력 내용을 바로 생성 | `/issue` slash 명령으로 에이전트가 설명을 정리한 뒤 생성 | `/issue` 메시지 명령으로 입력 내용을 바로 생성 | `/issue` 메시지 명령으로 입력 내용을 바로 생성 |
-| 연결 방식 | 플랫폼 장기 연결 | Socket Mode | Stream 모드 | 플랫폼 장기 연결 |
+| | Feishu / Lark | Slack | DingTalk | WeCom | Telegram |
+|---|---|---|---|---|---|
+| 설치 방법 | Multica에서 QR 코드를 만든 뒤 Feishu로 스캔해 승인 | Slack에서 app을 만든 뒤 두 token을 Multica에 입력 | 사내 app과 Stream 모드 로봇을 만든 뒤 AppKey와 AppSecret을 Multica에 입력 | WeCom 관리자 콘솔에서 장기 연결을 켠 스마트 봇을 만든 뒤 Bot ID와 Secret을 Multica에 입력 | @BotFather에서 Bot을 만든 뒤 token을 Multica에 입력 |
+| 에이전트와 DM | 지원 | 지원 | 지원 | 지원 | 지원 |
+| 그룹 채팅 또는 채널 | Bot을 @멘션하면 트리거 | Bot을 @멘션하면 트리거 | Bot을 @멘션하면 트리거 | Bot을 @멘션하면 트리거 | Bot을 @멘션하거나 Bot에 답장하면 트리거 |
+| 이슈 만들기 | `/issue` 메시지 명령으로 입력 내용을 바로 생성 | `/issue` slash 명령으로 에이전트가 설명을 정리한 뒤 생성 | `/issue` 메시지 명령으로 입력 내용을 바로 생성 | `/issue` 메시지 명령으로 입력 내용을 바로 생성 | `/issue` 메시지 명령으로 입력 내용을 바로 생성 |
+| 연결 방식 | 플랫폼 장기 연결 | Socket Mode | Stream 모드 | 플랫폼 장기 연결 | `getUpdates` long polling |
새 연결은 현재 중국 본토 버전 Feishu에서만 만들 수 있습니다. 기존 국제 버전 Lark 연결은 계속 사용하고 관리할 수 있습니다.
Bot 하나는 Multica 에이전트 하나에 연결됩니다. 같은 채팅 플랫폼에서 여러 에이전트를 사용하려면 각각 별도의 Bot을 연결해야 합니다.
-DingTalk과 WeCom은 커뮤니티에서 유지 관리합니다. 모든 릴리스에 포함되지만 공식 지원 SLA는 없습니다. 문제는 [GitHub issues](https://github.com/multica-ai/multica/issues)에 알려주세요.
+DingTalk, WeCom, Telegram은 커뮤니티에서 유지 관리합니다. 모든 릴리스에 포함되지만 공식 지원 SLA는 없습니다. 문제는 [GitHub issues](https://github.com/multica-ai/multica/issues)에 알려주세요.
WeCom은 현재 텍스트 메시지만 처리합니다. 음성, 이미지, 파일 메시지에는 안내 문구만 회신하며 에이전트로 전달하지 않습니다.
+Telegram은 현재 텍스트 메시지만 처리합니다. 미지원 미디어에는 안내 문구만 회신하며 에이전트로 전달하지 않습니다.
+
자세한 단계는 다음 문서를 참고하세요.
- [Feishu / Lark Bot 연결](/lark-bot-integration)
- [Slack Bot 연결](/slack-bot-integration)
- [DingTalk Bot 연결](/dingtalk-bot-integration)
+- [Telegram Bot 연결](/telegram-bot-integration)
## 메시지 실행 과정
@@ -51,6 +54,7 @@ Bot을 @멘션하지 않은 채널 메시지는 에이전트를 트리거하지
- Slack DM은 채널별로 구분하고, 채널 안에서는 각 thread가 별도 대화를 저장합니다.
- DingTalk는 conversation별로 대화를 구분하며 각 DM 또는 그룹이 자체 대화를 이어갑니다.
- WeCom은 채팅별로 대화를 구분하며 각 DM 또는 그룹 채팅이 자체 대화를 이어갑니다.
+- Telegram은 채팅별로 대화를 구분하며 forum topic은 topic별로 분리합니다.
채널에서 후속 질문을 할 때도 Bot을 다시 @멘션해야 합니다. 에이전트는 자신에게 보낸 메시지만 받으며 전체 채널 기록을 자동으로 읽지 않습니다.
@@ -79,6 +83,7 @@ MULTICA_LARK_SECRET_KEY=<base64로 인코딩한 32바이트 키>
MULTICA_SLACK_SECRET_KEY=<base64로 인코딩한 32바이트 키>
MULTICA_DINGTALK_SECRET_KEY=<base64로 인코딩한 32바이트 키>
MULTICA_WECOM_SECRET_KEY=<base64로 인코딩한 32바이트 키>
+MULTICA_TELEGRAM_SECRET_KEY=<base64로 인코딩한 32바이트 키>
```
이 키는 Bot 자격 증명을 암호화해 저장하는 데 사용됩니다. 생성, 보관, 교체 방법은 [환경 변수](/environment-variables)를 참고하세요. Multica Cloud에는 이미 설정되어 있습니다.
@@ -90,4 +95,5 @@ WeCom은 추가로 백엔드를 **단일 레플리카**로 운영해야 합니
- [Feishu / Lark Bot 연결](/lark-bot-integration)
- [Slack Bot 연결](/slack-bot-integration)
- [DingTalk Bot 연결](/dingtalk-bot-integration)
+- [Telegram Bot 연결](/telegram-bot-integration)
- [에이전트와 대화](/chat)
diff --git a/apps/docs/content/docs/channels.mdx b/apps/docs/content/docs/channels.mdx
index 936cebb438..8906049517 100644
--- a/apps/docs/content/docs/channels.mdx
+++ b/apps/docs/content/docs/channels.mdx
@@ -1,37 +1,40 @@
---
title: Chat integrations
-description: Connect Multica agents to Feishu, Lark, Slack, DingTalk, or WeCom and use them from the chat tools your team already uses.
+description: Connect Multica agents to Feishu, Lark, Slack, DingTalk, WeCom, or Telegram and use them from the chat tools your team already uses.
---
import { Callout } from "fumadocs-ui/components/callout";
Chat integrations let the team ask an agent questions, @-mention it in a group chat, or create issues from the chat window — without opening Multica.
-Feishu/Lark, Slack, DingTalk, and WeCom are supported today. They share the same session, identity, and execution mechanics but install differently.
+Feishu/Lark, Slack, DingTalk, WeCom, and Telegram are supported today. They share the same session, identity, and execution mechanics but install differently.
## Choose a platform
-| | Feishu / Lark | Slack | DingTalk | WeCom |
-|---|---|---|---|---|
-| Installation | Generate a QR code in Multica and authorize by scanning it with Feishu | Create an app in Slack, then paste two tokens into Multica | Create an internal app and Stream-mode robot, then paste its AppKey and AppSecret into Multica | Create a smart bot with the long connection enabled in the WeCom admin console, then paste its Bot ID and Secret into Multica |
-| DM the agent | Supported | Supported | Supported | Supported |
-| Groups or channels | Triggered by @-mentioning the Bot | Triggered by @-mentioning the Bot | Triggered by @-mentioning the Bot | Triggered by @-mentioning the Bot |
-| Create issues | `/issue` message command; creates the issue from your input as-is | `/issue` slash command; the agent writes up the description before creating | `/issue` message command; creates the issue from your input as-is | `/issue` message command; creates the issue from your input as-is |
-| Connection | Platform long connection | Socket Mode | Stream mode | Platform long connection |
+| | Feishu / Lark | Slack | DingTalk | WeCom | Telegram |
+|---|---|---|---|---|---|
+| Installation | Generate a QR code in Multica and authorize by scanning it with Feishu | Create an app in Slack, then paste two tokens into Multica | Create an internal app and Stream-mode robot, then paste its AppKey and AppSecret into Multica | Create a smart bot with the long connection enabled in the WeCom admin console, then paste its Bot ID and Secret into Multica | Create a Bot with @BotFather, then paste its token into Multica |
+| DM the agent | Supported | Supported | Supported | Supported | Supported |
+| Groups or channels | Triggered by @-mentioning the Bot | Triggered by @-mentioning the Bot | Triggered by @-mentioning the Bot | Triggered by @-mentioning the Bot | Triggered by @-mentioning or replying to the Bot |
+| Create issues | `/issue` message command; creates the issue from your input as-is | `/issue` slash command; the agent writes up the description before creating | `/issue` message command; creates the issue from your input as-is | `/issue` message command; creates the issue from your input as-is | `/issue` message command; creates the issue from your input as-is |
+| Connection | Platform long connection | Socket Mode | Stream mode | Platform long connection | `getUpdates` long polling |
New connections are currently open only for mainland-China Feishu; existing international Lark connections keep working and can still be managed.
Each Bot is bound to one Multica agent. To use several agents on the same chat platform, connect a separate Bot for each.
-DingTalk and WeCom are community-maintained: they ship in every release, but carry no official support SLA. Report problems in [GitHub issues](https://github.com/multica-ai/multica/issues).
+DingTalk, WeCom, and Telegram are community-maintained: they ship in every release, but carry no official support SLA. Report problems in [GitHub issues](https://github.com/multica-ai/multica/issues).
WeCom handles text messages today. Voice, image, and file messages get a short reply explaining that, and are not passed to the agent.
+Telegram handles text messages today. Unsupported media gets a short reply explaining that, and is not passed to the agent.
+
Step-by-step guides:
- [Feishu / Lark Bot integration](/lark-bot-integration)
- [Slack Bot integration](/slack-bot-integration)
- [DingTalk Bot integration](/dingtalk-bot-integration)
+- [Telegram Bot integration](/telegram-bot-integration)
## How a message is processed
@@ -51,6 +54,7 @@ Ordinary messages follow this flow. `/issue` is a command, not a chat turn: Mult
- Slack separates DMs by channel; in a channel, each thread holds its own session.
- DingTalk separates sessions by conversation; each DM or group continues its own session.
- WeCom separates sessions by chat; each DM or group chat continues its own session.
+- Telegram separates sessions by chat; forum topics are isolated by topic.
Follow-ups in a channel still need a fresh @-mention. The agent only receives messages addressed to it — it never reads the whole channel history automatically.
@@ -79,6 +83,7 @@ MULTICA_LARK_SECRET_KEY=<base64-encoded 32-byte key>
MULTICA_SLACK_SECRET_KEY=<base64-encoded 32-byte key>
MULTICA_DINGTALK_SECRET_KEY=<base64-encoded 32-byte key>
MULTICA_WECOM_SECRET_KEY=<base64-encoded 32-byte key>
+MULTICA_TELEGRAM_SECRET_KEY=<base64-encoded 32-byte key>
```
These keys encrypt stored Bot credentials. See [Environment variables](/environment-variables) for how to generate, store, and rotate them. Multica Cloud already has this configured.
@@ -90,4 +95,5 @@ WeCom additionally requires a **single backend replica**: its only outbound path
- [Feishu / Lark Bot integration](/lark-bot-integration) — connect an agent by scanning a QR code.
- [Slack Bot integration](/slack-bot-integration) — create a Slack app and paste its tokens into Multica.
- [DingTalk Bot integration](/dingtalk-bot-integration) — create a Stream-mode robot and paste its credentials into Multica.
+- [Telegram Bot integration](/telegram-bot-integration) — create a Bot with @BotFather and paste its token into Multica.
- [Chat](/chat) — the conversation and execution model behind every Bot.
diff --git a/apps/docs/content/docs/channels.zh.mdx b/apps/docs/content/docs/channels.zh.mdx
index c71d8afb73..e538be0c51 100644
--- a/apps/docs/content/docs/channels.zh.mdx
+++ b/apps/docs/content/docs/channels.zh.mdx
@@ -1,37 +1,40 @@
---
title: 聊天集成
-description: 把 Multica 智能体接入飞书、Lark、Slack、钉钉或企业微信,在团队已有的聊天工具中使用。
+description: 把 Multica 智能体接入飞书、Lark、Slack、钉钉、企业微信或 Telegram,在团队已有的聊天工具中使用。
---
import { Callout } from "fumadocs-ui/components/callout";
聊天集成让团队不用打开 Multica,也能直接向智能体提问、在群聊中 @它,或从聊天窗口创建 issue。
-目前支持飞书/Lark、Slack、钉钉和企业微信。它们使用相同的会话、身份和执行机制,但安装方式不同。
+目前支持飞书/Lark、Slack、钉钉、企业微信和 Telegram。它们使用相同的会话、身份和执行机制,但安装方式不同。
## 选择平台
-| | 飞书 / Lark | Slack | 钉钉 | 企业微信 |
-|---|---|---|---|---|
-| 安装方式 | 在 Multica 中生成二维码,用飞书扫码授权 | 在 Slack 创建 app,再把两个 token 填入 Multica | 创建企业内部应用和 Stream 模式机器人,再把 AppKey 与 AppSecret 填入 Multica | 在企业微信管理后台创建智能机器人并开启长连接,再把 Bot ID 与 Secret 填入 Multica |
-| 私聊智能体 | 支持 | 支持 | 支持 | 支持 |
-| 群聊或频道 | @ Bot 后触发 | @ Bot 后触发 | @ Bot 后触发 | @ Bot 后触发 |
-| 创建 issue | `/issue` 消息命令,按输入直接创建 | `/issue` slash 命令,智能体整理描述后创建 | `/issue` 消息命令,按输入直接创建 | `/issue` 消息命令,按输入直接创建 |
-| 连接方式 | 平台长连接 | Socket Mode | Stream 模式 | 平台长连接 |
+| | 飞书 / Lark | Slack | 钉钉 | 企业微信 | Telegram |
+|---|---|---|---|---|---|
+| 安装方式 | 在 Multica 中生成二维码,用飞书扫码授权 | 在 Slack 创建 app,再把两个 token 填入 Multica | 创建企业内部应用和 Stream 模式机器人,再把 AppKey 与 AppSecret 填入 Multica | 在企业微信管理后台创建智能机器人并开启长连接,再把 Bot ID 与 Secret 填入 Multica | 用 @BotFather 创建 Bot,再把 token 填入 Multica |
+| 私聊智能体 | 支持 | 支持 | 支持 | 支持 | 支持 |
+| 群聊或频道 | @ Bot 后触发 | @ Bot 后触发 | @ Bot 后触发 | @ Bot 后触发 | @ Bot 或回复 Bot 后触发 |
+| 创建 issue | `/issue` 消息命令,按输入直接创建 | `/issue` slash 命令,智能体整理描述后创建 | `/issue` 消息命令,按输入直接创建 | `/issue` 消息命令,按输入直接创建 | `/issue` 消息命令,按输入直接创建 |
+| 连接方式 | 平台长连接 | Socket Mode | Stream 模式 | 平台长连接 | `getUpdates` 长轮询 |
新连接目前只开放中国大陆版飞书;已有的国际版 Lark 连接仍可继续使用和管理。
每个 Bot 绑定一个 Multica 智能体。需要在同一个聊天平台中使用多个智能体时,要分别连接多个 Bot。
-钉钉和企业微信由社区维护:随每个版本发布,但没有官方支持 SLA。遇到问题请提交 [GitHub issue](https://github.com/multica-ai/multica/issues)。
+钉钉、企业微信和 Telegram 由社区维护:随每个版本发布,但没有官方支持 SLA。遇到问题请提交 [GitHub issue](https://github.com/multica-ai/multica/issues)。
企业微信目前只处理文字消息。语音、图片和文件消息会收到一句说明,不会转交给智能体。
+Telegram 目前只处理文字消息。不支持的媒体消息会收到一句说明,不会转交给智能体。
+
详细步骤:
- [飞书 / Lark Bot 接入](/lark-bot-integration)
- [Slack Bot 接入](/slack-bot-integration)
- [钉钉 Bot 接入](/dingtalk-bot-integration)
+- [Telegram Bot 接入](/telegram-bot-integration)
## 消息的执行流程
@@ -51,6 +54,7 @@ import { Callout } from "fumadocs-ui/components/callout";
- Slack 私聊按频道区分;频道中的每个 thread 分别保存一段会话。
- 钉钉按 conversation 区分会话;每个单聊或群聊分别延续自己的会话。
- 企业微信按聊天区分会话;每个单聊或群聊分别延续自己的会话。
+- Telegram 按聊天区分会话;forum 的每个 topic 分别隔离。
在频道中继续追问时仍需再次 @ Bot。智能体只收到发给自己的消息,不会自动读取整个频道的历史。
@@ -79,6 +83,7 @@ MULTICA_LARK_SECRET_KEY=<base64 编码的 32 字节密钥>
MULTICA_SLACK_SECRET_KEY=<base64 编码的 32 字节密钥>
MULTICA_DINGTALK_SECRET_KEY=<base64 编码的 32 字节密钥>
MULTICA_WECOM_SECRET_KEY=<base64 编码的 32 字节密钥>
+MULTICA_TELEGRAM_SECRET_KEY=<base64 编码的 32 字节密钥>
```
这些密钥用于加密保存 Bot 凭据。生成、保存和轮换方法见[环境变量](/environment-variables)。Multica Cloud 已完成这项配置。
@@ -90,4 +95,5 @@ MULTICA_WECOM_SECRET_KEY=<base64 编码的 32 字节密钥>
- [飞书 / Lark Bot 接入](/lark-bot-integration)
- [Slack Bot 接入](/slack-bot-integration)
- [钉钉 Bot 接入](/dingtalk-bot-integration)
+- [Telegram Bot 接入](/telegram-bot-integration)
- [与智能体对话](/chat)
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdx
index 5fc0c1e674..ce6748019f 100644
--- a/apps/docs/content/docs/environment-variables.ja.mdx
+++ b/apps/docs/content/docs/environment-variables.ja.mdx
@@ -167,6 +167,7 @@ allowlist の正確な判定順序は[ログインとサインアップ](/auth-s
| GitHub | `GITHUB_APP_PRIVATE_KEY` | App ID と対になる完全な PEM 秘密鍵。用途は同上 |
| Lark | `MULTICA_LARK_SECRET_KEY` | base64 エンコードされた 32 バイトの資格情報暗号化キー |
| Slack | `MULTICA_SLACK_SECRET_KEY` | base64 エンコードされた 32 バイトの token 暗号化キー |
+| Telegram | `MULTICA_TELEGRAM_SECRET_KEY` | base64 エンコードされた 32 バイトの Bot token 暗号化キー |
| Composio | `COMPOSIO_API_KEY` | Composio ツール接続を有効化 |
| Composio | `COMPOSIO_CALLBACK_BASE_URL` | コールバック API アドレス。`MULTICA_PUBLIC_URL` にフォールバック可能 |
| Composio | `COMPOSIO_STATE_SECRET` | OAuth state の署名シークレット。`JWT_SECRET` から派生可能 |
@@ -175,7 +176,7 @@ allowlist の正確な判定順序は[ログインとサインアップ](/auth-s
`GITHUB_APP_ID` と秘密鍵を設定しなくても、PR の関連付け・ミラー・マージによる done への遷移は通常どおり動きますが、カードに CI とマージ可否のステータスが表示されず、「GitHub から選択」のリポジトリ入口も無効になります。
-設定手順は [GitHub 連携](/github-integration#セルフホスト設定)、[Lark Bot](/lark-bot-integration#セルフホスト設定)、[Slack Bot](/slack-bot-integration#セルフホスト設定)を参照してください。
+設定手順は [GitHub 連携](/github-integration#セルフホスト設定)、[Lark Bot](/lark-bot-integration#セルフホスト設定)、[Slack Bot](/slack-bot-integration#セルフホスト設定)、[Telegram Bot](/telegram-bot-integration#管理とセルフホスティング)を参照してください。
## サーバーサイド LLM
diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdx
index 643c9dd2b5..ab03ea5a98 100644
--- a/apps/docs/content/docs/environment-variables.ko.mdx
+++ b/apps/docs/content/docs/environment-variables.ko.mdx
@@ -167,6 +167,7 @@ reverse proxy 뒤에 배포한다면 실제 proxy 네트워크를 입력해야
| GitHub | `GITHUB_APP_PRIVATE_KEY` | App ID와 짝을 이루는 전체 PEM private key. 용도는 위와 같음 |
| Feishu | `MULTICA_LARK_SECRET_KEY` | base64로 인코딩한 32바이트 자격 증명 암호화 키 |
| Slack | `MULTICA_SLACK_SECRET_KEY` | base64로 인코딩한 32바이트 token 암호화 키 |
+| Telegram | `MULTICA_TELEGRAM_SECRET_KEY` | base64로 인코딩한 32바이트 Bot token 암호화 키 |
| Composio | `COMPOSIO_API_KEY` | Composio 도구 연결 활성화 |
| Composio | `COMPOSIO_CALLBACK_BASE_URL` | callback API 주소. `MULTICA_PUBLIC_URL`로 fallback 가능 |
| Composio | `COMPOSIO_STATE_SECRET` | OAuth state 서명 키. `JWT_SECRET`에서 파생 가능 |
@@ -175,7 +176,7 @@ reverse proxy 뒤에 배포한다면 실제 proxy 네트워크를 입력해야
`GITHUB_APP_ID`와 private key를 설정하지 않아도 PR 연결, 미러링, merge 시 done 전환은 정상적으로 작동합니다. 다만 카드에 CI와 merge 가능 상태가 표시되지 않고 "GitHub에서 선택" 저장소 메뉴도 비활성화됩니다.
-설정 단계는 [GitHub 연동](/github-integration#자체-호스팅-설정), [Feishu Bot](/lark-bot-integration#자체-호스팅-설정), [Slack Bot](/slack-bot-integration#자체-호스팅-설정)을 참고하세요.
+설정 단계는 [GitHub 연동](/github-integration#자체-호스팅-설정), [Feishu Bot](/lark-bot-integration#자체-호스팅-설정), [Slack Bot](/slack-bot-integration#자체-호스팅-설정), [Telegram Bot](/telegram-bot-integration#관리-및-자체-호스팅)을 참고하세요.
## 서버 측 LLM
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index ea502d30be..8bd840ce56 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -167,6 +167,7 @@ The auth rate limits require `REDIS_URL`; without it, the startup log notes that
| GitHub | `GITHUB_APP_PRIVATE_KEY` | Full PEM private key paired with the App ID; same uses as above |
| Lark | `MULTICA_LARK_SECRET_KEY` | Base64-encoded 32-byte credential encryption key |
| Slack | `MULTICA_SLACK_SECRET_KEY` | Base64-encoded 32-byte token encryption key |
+| Telegram | `MULTICA_TELEGRAM_SECRET_KEY` | Base64-encoded 32-byte Bot token encryption key |
| Composio | `COMPOSIO_API_KEY` | Enables Composio tool connections |
| Composio | `COMPOSIO_CALLBACK_BASE_URL` | Callback API URL; can fall back to `MULTICA_PUBLIC_URL` |
| Composio | `COMPOSIO_STATE_SECRET` | OAuth state signing secret; can be derived from `JWT_SECRET` |
@@ -175,7 +176,7 @@ The auth rate limits require `REDIS_URL`; without it, the startup log notes that
Without `GITHUB_APP_ID` and the private key, PRs still link, mirror, and trigger merge-to-done normally, but cards show no CI or mergeability status, and the "pick from GitHub" repository entry is disabled.
-For setup steps, see [GitHub integration](/github-integration#self-hosting-setup), [Lark bot](/lark-bot-integration#self-hosting-setup), and [Slack bot](/slack-bot-integration#self-hosting-setup).
+For setup steps, see [GitHub integration](/github-integration#self-hosting-setup), [Lark bot](/lark-bot-integration#self-hosting-setup), [Slack bot](/slack-bot-integration#self-hosting-setup), and [Telegram bot](/telegram-bot-integration#self-hosting-setup).
## Server-side LLM
diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdx
index 95c3c22de1..e961f8b608 100644
--- a/apps/docs/content/docs/environment-variables.zh.mdx
+++ b/apps/docs/content/docs/environment-variables.zh.mdx
@@ -167,6 +167,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
| GitHub | `GITHUB_APP_PRIVATE_KEY` | 与 App ID 配套的完整 PEM 私钥,用途同上 |
| 飞书 | `MULTICA_LARK_SECRET_KEY` | base64 编码的 32 字节凭据加密密钥 |
| Slack | `MULTICA_SLACK_SECRET_KEY` | base64 编码的 32 字节 token 加密密钥 |
+| Telegram | `MULTICA_TELEGRAM_SECRET_KEY` | base64 编码的 32 字节 Bot token 加密密钥 |
| Composio | `COMPOSIO_API_KEY` | 启用 Composio 工具连接 |
| Composio | `COMPOSIO_CALLBACK_BASE_URL` | 回调 API 地址;可回退到 `MULTICA_PUBLIC_URL` |
| Composio | `COMPOSIO_STATE_SECRET` | OAuth state 签名密钥;可从 `JWT_SECRET` 派生 |
@@ -175,7 +176,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
不配置 `GITHUB_APP_ID` 和私钥时,PR 仍会正常关联、镜像和触发合并转 done,但卡片上不显示 CI 与可合并状态,"从 GitHub 选择"仓库入口也会禁用。
-配置步骤见 [GitHub 集成](/github-integration#自托管配置)、[飞书 Bot](/lark-bot-integration#自托管配置)和 [Slack Bot](/slack-bot-integration#自托管配置)。
+配置步骤见 [GitHub 集成](/github-integration#自托管配置)、[飞书 Bot](/lark-bot-integration#自托管配置)、[Slack Bot](/slack-bot-integration#自托管配置)和 [Telegram Bot](/telegram-bot-integration#自托管配置)。
## 服务端 LLM
diff --git a/apps/docs/content/docs/meta.ja.json b/apps/docs/content/docs/meta.ja.json
index 839b1e4a6b..de8e4a6246 100644
--- a/apps/docs/content/docs/meta.ja.json
+++ b/apps/docs/content/docs/meta.ja.json
@@ -39,6 +39,7 @@
"lark-bot-integration",
"slack-bot-integration",
"dingtalk-bot-integration",
+ "telegram-bot-integration",
"github-integration",
"vcs-integration",
"---アプリ---",
diff --git a/apps/docs/content/docs/meta.json b/apps/docs/content/docs/meta.json
index 3aae89fe15..5720e16ed4 100644
--- a/apps/docs/content/docs/meta.json
+++ b/apps/docs/content/docs/meta.json
@@ -39,6 +39,7 @@
"lark-bot-integration",
"slack-bot-integration",
"dingtalk-bot-integration",
+ "telegram-bot-integration",
"github-integration",
"vcs-integration",
"---Apps---",
diff --git a/apps/docs/content/docs/meta.ko.json b/apps/docs/content/docs/meta.ko.json
index 3926622e47..5ec555e8f1 100644
--- a/apps/docs/content/docs/meta.ko.json
+++ b/apps/docs/content/docs/meta.ko.json
@@ -39,6 +39,7 @@
"lark-bot-integration",
"slack-bot-integration",
"dingtalk-bot-integration",
+ "telegram-bot-integration",
"github-integration",
"vcs-integration",
"---앱---",
diff --git a/apps/docs/content/docs/meta.zh.json b/apps/docs/content/docs/meta.zh.json
index 1669f6456b..1b0fa6a4ad 100644
--- a/apps/docs/content/docs/meta.zh.json
+++ b/apps/docs/content/docs/meta.zh.json
@@ -39,6 +39,7 @@
"lark-bot-integration",
"slack-bot-integration",
"dingtalk-bot-integration",
+ "telegram-bot-integration",
"github-integration",
"vcs-integration",
"---客户端---",
diff --git a/apps/docs/content/docs/telegram-bot-integration.ja.mdx b/apps/docs/content/docs/telegram-bot-integration.ja.mdx
new file mode 100644
index 0000000000..f697d3e0b3
--- /dev/null
+++ b/apps/docs/content/docs/telegram-bot-integration.ja.mdx
@@ -0,0 +1,79 @@
+---
+title: Telegram Bot 連携
+description: 独自の Telegram Bot を Multica エージェントに接続し、DM、グループ、forum topic、/issue で利用します。
+---
+
+import { Callout } from "fumadocs-ui/components/callout";
+
+Multica は Telegram 公式の [@BotFather](https://t.me/BotFather) で作成した Bot を使用します。1 つの Bot は 1 つの Multica エージェントに対応します。
+
+Telegram 連携はコミュニティによってメンテナンスされています。毎リリースに同梱されますが、公式のサポート SLA は付きません。問題があれば [GitHub issues](https://github.com/multica-ai/multica/issues) に報告してください。
+
+## 準備
+
+- 接続できるのはワークスペースの owner または admin です。
+- API サーバーから `https://api.telegram.org` に接続できる必要があります。
+- @BotFather が発行した Bot token が必要です。パスワードと同様に扱ってください。
+
+## 1. Bot を作成する
+
+1. [@BotFather](https://t.me/BotFather) を開き、`/newbot` を送信します。
+2. 表示名と、`bot` で終わる username を設定します。
+3. HTTP API token をコピーします。
+4. **Group Privacy** は有効のままにします。グループではコマンド、明示的な @mention、Bot への返信だけを処理します。
+
+<Callout type="warning">
+token を issue、チャット、ログ、リポジトリに記録しないでください。漏えいした場合は @BotFather で失効させ、新しい token で再接続します。
+</Callout>
+
+## 2. エージェントに接続する
+
+1. Multica の **Agents** で対象エージェントを開き、**Integrations** を選びます。
+2. **Connect Telegram** をクリックします。
+3. Bot token を貼り付け、**Connect** をクリックします。
+
+Multica は Telegram で Bot を検証し、long polling と競合する webhook がないことを確認して token を暗号化保存し、監視された `getUpdates` 接続を開始します。他のエージェントやワークスペースに接続済みの Bot は、先に元の接続を解除してください。
+
+## 初回利用とアカウント連携
+
+メンバーが初めて Bot にメッセージを送ると、1 回だけ使える Multica アカウント連携リンクが届きます。同じワークスペースの Multica アカウントでサインインし、Telegram に戻ってメッセージを再送してください。リンクは 15 分で期限切れになります。
+
+グループには bearer link を公開しません。Bot は送信者に、先に DM を開始するよう案内します。利用できるのは現在のワークスペースメンバーだけです。
+
+## Bot を使う
+
+- **DM**: @mention なしでテキストを送信します。
+- **グループ**: Bot を追加し、@mention するか Bot のメッセージに直接返信します。受理されたメッセージは継続中の Multica 会話に残りますが、Bot 宛てでない会話は収集されません。他のメンバーのメッセージへ返信する場合は Bot も明示的に @mention してください。その場合に限り、引用元の送信者とテキスト(または caption)が新しい指示の文脈に含まれます。@mention なしの人への返信は Bot を起動しません。forum topic は topic ごとにセッションが分離されます。
+- **`/new <message>`**: 過去の文脈なしで実行します。他のメンバーへの返信で Bot を明示的に @mention した場合、選択した引用内容はこの新しい指示にも含まれます。`/new` だけなら次の空でないメッセージに適用されます。
+- **`/issue <title>`**: Multica issue を作成します。2 行目以降は任意の説明です。`/issue@your_bot` 形式も利用できます。
+
+Bot は Telegram メッセージを送信・編集してテキストをストリーミング表示し、元メッセージを引用して forum topic を維持します。長い返信は自動分割されます。最終返信はプロセス内で非同期に配信されます。通常、あるチャットのバックオフ待機は worker を占有しません。キャッシュが上限に達してバックオフ状態が圧縮されると、同じ Bot installation の他のチャットも安全側に遅延する場合があります。終端キューの容量は固定で、上限超過は明示的に拒否されてエラーとして記録されます。キューはサービス再起動後に復元されません。
+
+現在はテキストのみ対応しています。画像、ファイル、動画、音声、sticker などは、DM または Bot 宛てのグループメッセージで明確な非対応通知を返します。
+
+## 管理とセルフホスティング
+
+**Settings → Integrations → Telegram** で接続済み Bot を確認できます。owner と admin は接続を解除できます。会話と監査履歴は保持されます。
+
+セルフホスト環境では、API 起動前に固定の 32-byte 暗号鍵を設定します。
+
+```dotenv
+MULTICA_TELEGRAM_SECRET_KEY=<base64-encoded 32-byte key>
+```
+
+`openssl rand -base64 32` で生成できます。連携リンクは `MULTICA_APP_URL`(未設定時は `FRONTEND_ORIGIN`)を使用します。サーバーから `api.telegram.org` への HTTPS 接続も必要で、標準の `HTTPS_PROXY` / `NO_PROXY` を利用できます。
+
+## トラブルシューティング
+
+- **Bot を検証できない**: まずサーバーのネットワークと proxy を確認します。Telegram が token を拒否した場合だけ再発行します。
+- **webhook conflict**: 接続前に既存 webhook を削除します。
+- **409 polling conflict**: 同じ Bot を polling している別プロセスを停止するか、環境ごとに Bot を分けます。
+- **グループで返信しない**: Bot が参加していて、@mention または Bot への返信になっていることを確認します。
+- **連携リンクが期限切れ**: Bot に新しい DM を送り、最新リンクを使用します。
+- **実行されない**: エージェントの archive 状態と[ランタイム](/daemon-runtimes)を確認します。
+
+## 次のステップ
+
+- [チャット連携](/channels)
+- [チャット](/chat)
+- [Issues](/issues)
diff --git a/apps/docs/content/docs/telegram-bot-integration.ko.mdx b/apps/docs/content/docs/telegram-bot-integration.ko.mdx
new file mode 100644
index 0000000000..cc2e29a14c
--- /dev/null
+++ b/apps/docs/content/docs/telegram-bot-integration.ko.mdx
@@ -0,0 +1,79 @@
+---
+title: Telegram Bot 연동
+description: 직접 만든 Telegram Bot을 Multica 에이전트에 연결해 DM, 그룹, forum topic, /issue에서 사용합니다.
+---
+
+import { Callout } from "fumadocs-ui/components/callout";
+
+Multica는 Telegram 공식 [@BotFather](https://t.me/BotFather)에서 만든 Bot을 사용합니다. Bot 하나는 Multica 에이전트 하나에 연결됩니다.
+
+Telegram 연동은 커뮤니티가 유지관리합니다. 매 릴리스에 포함되지만 공식 지원 SLA는 제공되지 않습니다. 문제가 있으면 [GitHub issues](https://github.com/multica-ai/multica/issues)에 보고해 주세요.
+
+## 시작하기 전에
+
+- 워크스페이스 owner 또는 admin만 Bot을 연결할 수 있습니다.
+- API 서버에서 `https://api.telegram.org`에 접속할 수 있어야 합니다.
+- @BotFather가 발급한 Bot token이 필요합니다. 비밀번호처럼 보호하세요.
+
+## 1. Bot 만들기
+
+1. [@BotFather](https://t.me/BotFather)를 열고 `/newbot`을 보냅니다.
+2. 표시 이름과 `bot`으로 끝나는 username을 정합니다.
+3. HTTP API token을 복사합니다.
+4. **Group Privacy**를 켜 둡니다. 그룹에서는 명령, 명시적 @mention, Bot 메시지에 대한 답장만 처리합니다.
+
+<Callout type="warning">
+token을 issue, 채팅, 로그, 코드 저장소에 남기지 마세요. 노출되었다면 @BotFather에서 폐기하고 새 token으로 다시 연결하세요.
+</Callout>
+
+## 2. 에이전트에 연결하기
+
+1. Multica의 **Agents**에서 에이전트를 선택하고 **Integrations**를 엽니다.
+2. **Connect Telegram**을 클릭합니다.
+3. Bot token을 붙여 넣고 **Connect**를 클릭합니다.
+
+Multica는 Telegram에서 Bot을 검증하고 long polling과 충돌하는 webhook이 없는지 확인한 뒤 token을 암호화해 저장하고 감독되는 `getUpdates` 연결을 시작합니다. 다른 에이전트나 워크스페이스에 연결된 Bot은 먼저 기존 연결을 해제해야 합니다.
+
+## 최초 사용과 계정 바인딩
+
+멤버가 처음 Bot에 메시지를 보내면 일회용 Multica 계정 바인딩 링크를 받습니다. 같은 워크스페이스의 Multica 계정으로 로그인한 뒤 Telegram으로 돌아가 메시지를 다시 보내세요. 링크는 15분 후 만료됩니다.
+
+그룹에는 bearer link를 공개하지 않습니다. Bot은 먼저 개인 채팅을 시작하라고 안내합니다. 현재 워크스페이스 멤버만 Bot을 사용할 수 있습니다.
+
+## Bot 사용하기
+
+- **개인 채팅**: @mention 없이 텍스트를 보냅니다.
+- **그룹**: Bot을 추가한 뒤 @mention하거나 Bot 메시지에 직접 답장합니다. 수락된 메시지는 이어지는 Multica 대화에 남지만 Bot을 지정하지 않은 그룹 대화는 수집하지 않습니다. 다른 사람의 메시지에 답장할 때는 Bot도 명시적으로 @mention해야 하며, 이 경우에만 인용한 발신자와 텍스트(또는 caption)가 새 지시의 맥락에 포함됩니다. Bot @mention 없이 사람에게 답장하면 Bot이 실행되지 않습니다. forum topic은 topic별로 세션이 분리됩니다.
+- **`/new <message>`**: 이전 대화 맥락 없이 실행합니다. 다른 멤버의 메시지에 답장하면서 Bot을 명시적으로 @mention하면 선택한 인용 내용도 이 새 지시에 포함됩니다. `/new`만 보내면 다음 비어 있지 않은 메시지에 적용됩니다.
+- **`/issue <title>`**: Multica issue를 만듭니다. 다음 줄은 선택 설명으로 사용됩니다. `/issue@your_bot` 형식도 지원합니다.
+
+Bot은 Telegram 메시지를 보내고 편집해 텍스트 응답을 스트리밍하며, 원래 메시지를 인용하고 forum topic을 유지합니다. 긴 응답은 자동으로 나뉩니다. 최종 응답은 프로세스 내에서 비동기로 전달됩니다. 일반적으로 한 채팅의 백오프 대기는 worker를 점유하지 않습니다. 캐시가 용량 한계에 도달해 백오프 상태를 압축하면 같은 Bot installation의 다른 채팅도 안전을 위해 지연될 수 있습니다. 최종 응답 큐의 용량은 고정되어 있으며 한도를 넘은 작업은 명시적으로 거부되고 오류로 기록됩니다. 큐는 서비스 재시작 후 복구되지 않습니다.
+
+현재 버전은 텍스트만 받습니다. 이미지, 파일, 영상, 음성, sticker 등은 개인 채팅 또는 Bot에게 보낸 그룹 메시지에서 명확한 미지원 안내를 반환합니다.
+
+## 관리 및 자체 호스팅
+
+**Settings → Integrations → Telegram**에서 연결된 Bot을 확인할 수 있습니다. owner와 admin은 연결을 해제할 수 있으며, 기존 대화와 감사 기록은 유지됩니다.
+
+자체 호스팅 환경에서는 API 서버 시작 전에 고정된 32-byte 암호화 키를 설정합니다.
+
+```dotenv
+MULTICA_TELEGRAM_SECRET_KEY=<base64-encoded 32-byte key>
+```
+
+`openssl rand -base64 32`로 생성할 수 있습니다. 바인딩 링크는 `MULTICA_APP_URL`을 사용하며, 없으면 `FRONTEND_ORIGIN`으로 대체합니다. 서버는 `api.telegram.org`에 HTTPS로 접속할 수 있어야 하며 표준 `HTTPS_PROXY` / `NO_PROXY`를 사용할 수 있습니다.
+
+## 문제 해결
+
+- **Bot 검증 실패**: 먼저 서버 네트워크와 proxy를 확인합니다. Telegram이 token을 거부한 경우에만 재발급하세요.
+- **webhook conflict**: 연결 전에 기존 webhook을 제거합니다.
+- **409 polling conflict**: 같은 Bot을 polling하는 다른 프로세스를 중지하거나 환경별로 Bot을 분리합니다.
+- **그룹에서 답장 없음**: Bot이 그룹에 있고 메시지가 @mention 또는 Bot에 대한 답장인지 확인합니다.
+- **바인딩 링크 만료**: Bot에 새 DM을 보내 최신 링크를 사용합니다.
+- **실행되지 않음**: 에이전트의 archive 상태와 [runtime](/daemon-runtimes)을 확인합니다.
+
+## 다음 단계
+
+- [채팅 연동](/channels)
+- [채팅](/chat)
+- [Issues](/issues)
diff --git a/apps/docs/content/docs/telegram-bot-integration.mdx b/apps/docs/content/docs/telegram-bot-integration.mdx
new file mode 100644
index 0000000000..f722a68e28
--- /dev/null
+++ b/apps/docs/content/docs/telegram-bot-integration.mdx
@@ -0,0 +1,96 @@
+---
+title: Telegram Bot
+description: Connect a Multica agent to your own Telegram Bot for private chats, group mentions, topics, and /issue.
+---
+
+import { Callout } from "fumadocs-ui/components/callout";
+
+Multica uses a Bot that you create with Telegram's official [@BotFather](https://t.me/BotFather). One Bot maps to one Multica agent. Create a separate Bot for each agent that needs its own Telegram identity.
+
+Telegram support is community-maintained: it ships in every release, but it carries no official support SLA. Report problems in [GitHub issues](https://github.com/multica-ai/multica/issues).
+
+## Before you start
+
+- A Multica workspace owner or admin must connect the Bot.
+- The API server must be able to reach `https://api.telegram.org`.
+- You need the Bot token issued by @BotFather. Treat it as a password.
+
+## 1. Create the Bot
+
+1. 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.
+
+<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.
+</Callout>
+
+## 2. Connect it to an agent
+
+1. In Multica, open **Agents**, select an agent, and open **Integrations**.
+2. Click **Connect Telegram**.
+3. Paste the Bot token and click **Connect**.
+
+Multica calls Telegram to verify the Bot, checks that no outgoing webhook conflicts with long polling, encrypts the token, and starts one supervised `getUpdates` connection. A Bot already connected to another agent or workspace must be disconnected there first.
+
+## First use and account binding
+
+The first time a member messages the Bot, it sends a single-use Multica account-binding link. Open it, sign in to the same Multica workspace, then return to Telegram and send the message again. The link expires after 15 minutes; message the Bot again to get a new link.
+
+In a group, the Bot never posts the bearer link publicly. It asks the sender to start a private chat first.
+
+Only current workspace members can use the Bot. Membership is checked again for every message.
+
+## Use the Bot
+
+### Private chats
+
+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.
+
+### Commands
+
+- `/new <message>` runs the message without previous chat context. In an explicitly mentioned reply to another person, the selected quote remains attached to that fresh instruction. Sending `/new` by itself applies the fresh start to the next non-empty message.
+- `/issue <title>` creates a Multica issue; following lines are used as its optional description. `/issue` without a title returns usage guidance.
+- Telegram command suffixes such as `/issue@your_bot` are supported in groups.
+
+### Replies and supported content
+
+The Bot streams text by posting and editing a Telegram message, quotes the triggering message, preserves forum topics, and splits long replies under Telegram's message limit. Final replies are delivered asynchronously by an in-process queue. Normally, one chat's backoff does not occupy a worker; if cache pressure compacts exact backoff state, other chats under the same Bot installation may be conservatively delayed. The terminal queue has fixed capacity: overflow is rejected and logged, and queued replies are not recovered after a service restart.
+
+This version accepts text only. Photos, files, video, voice, stickers, and other non-text messages receive a clear unsupported-message response in private chats; addressed group media receives the same response, while unaddressed group media remains silent.
+
+## Manage connections
+
+Open **Settings → Integrations → Telegram** to view connected Bots. Owners and admins can disconnect one. Disconnecting stops long polling and outbound replies but preserves Multica conversations and audit records.
+
+## Self-hosting setup
+
+Set a stable 32-byte encryption key before starting the API server:
+
+```dotenv
+MULTICA_TELEGRAM_SECRET_KEY=<base64-encoded 32-byte key>
+```
+
+Generate one with `openssl rand -base64 32`. Keep it long-term: losing or rotating it makes existing Bot tokens unreadable and requires reconnecting each Bot.
+
+Binding links use `MULTICA_APP_URL`, falling back to `FRONTEND_ORIGIN`. The resulting address must be reachable by members. The server's network or proxy must allow HTTPS access to `api.telegram.org`; Go honors standard `HTTPS_PROXY` and `NO_PROXY` environment variables.
+
+## Troubleshooting
+
+- **Bot cannot be verified**: first check server connectivity and proxy settings. Generate a new token only when Telegram itself rejects the current one.
+- **Webhook conflict**: remove the Bot's existing webhook before connecting it. Telegram does not allow `getUpdates` while a webhook is active.
+- **409 polling conflict**: another Multica instance or process is polling the same Bot. Stop the other consumer or use a separate Bot per environment.
+- **No group reply**: confirm the Bot is in the group and the message @-mentions it or replies to its message.
+- **Binding link expired**: send the Bot another private message and use the newest link.
+- **Bot does not run**: check whether the agent is archived and whether its [runtime](/daemon-runtimes) is online.
+
+## Next steps
+
+- [Chat integrations](/channels) — compare platforms and understand session and identity handling.
+- [Chat](/chat) — how Bot messages become agent runs.
+- [Issues](/issues) — the work created by `/issue`.
diff --git a/apps/docs/content/docs/telegram-bot-integration.zh.mdx b/apps/docs/content/docs/telegram-bot-integration.zh.mdx
new file mode 100644
index 0000000000..770bfc55f1
--- /dev/null
+++ b/apps/docs/content/docs/telegram-bot-integration.zh.mdx
@@ -0,0 +1,96 @@
+---
+title: Telegram Bot 接入
+description: 把 Multica 智能体接入你自己的 Telegram Bot,支持私聊、群聊 @、forum topic 和 /issue。
+---
+
+import { Callout } from "fumadocs-ui/components/callout";
+
+Multica 使用你通过 Telegram 官方 [@BotFather](https://t.me/BotFather) 创建的 Bot。一个 Bot 对应一个 Multica 智能体;需要多个独立 Bot 身份时,为每个智能体分别创建。
+
+Telegram 集成由社区维护:每个版本都会随包发布,但不附带官方支持 SLA。遇到问题请提到 [GitHub issues](https://github.com/multica-ai/multica/issues)。
+
+## 开始前
+
+- 连接操作需要工作区 owner 或 admin 权限。
+- API 服务器必须能够访问 `https://api.telegram.org`。
+- 你需要 @BotFather 签发的 Bot token;它等同于密码。
+
+## 1. 创建 Bot
+
+1. 打开 [@BotFather](https://t.me/BotFather),发送 `/newbot`。
+2. 设置显示名称和一个以 `bot` 结尾的用户名。
+3. 复制 HTTP API token。
+4. 保持 **Group Privacy** 开启。群聊里 Multica 只需要接收命令、明确的 @ 和对 Bot 消息的回复。
+
+<Callout type="warning">
+不要把 token 发到 issue、聊天、日志或代码仓库。若已泄露,请在 @BotFather 中撤销,再用替换后的 token 重新连接。
+</Callout>
+
+## 2. 连接到智能体
+
+1. 在 Multica 打开 **智能体**,选择目标智能体并进入 **集成**。
+2. 点击 **连接 Telegram**。
+3. 粘贴 Bot token,然后点击 **连接**。
+
+Multica 会实时请求 Telegram 验证 Bot,检查是否存在与长轮询冲突的 webhook,加密保存 token,并启动一条受监督的 `getUpdates` 连接。一个 Bot 若已连接到其他智能体或工作区,必须先在原处断开。
+
+## 首次使用与账号绑定
+
+成员第一次向 Bot 发消息时,会收到一次性 Multica 账号绑定链接。打开链接,登录同一工作区的 Multica 账号,再回到 Telegram 重新发送消息。链接 15 分钟后过期;再私聊 Bot 即可获取新链接。
+
+在群里,Bot 不会公开发送带凭据性质的绑定链接,只会让发送者先私聊 Bot。
+
+只有当前工作区成员能使用 Bot;每条消息都会重新校验成员身份。
+
+## 使用 Bot
+
+### 私聊
+
+直接打开 Bot 发送文字,不需要 @。
+
+### 群聊与 forum topic
+
+把 Bot 加入群后,@它,或直接回复它发过的消息。被接受的消息会保留在持续的 Multica 对话中;未明确发给 Bot 的群聊内容不会被收集。回复其他成员的消息时必须同时 @ Bot,只有这种情况下,被引用消息的发送者及文字(或 caption)才会随新指令进入上下文;只回复成员而不 @ Bot 不会触发。普通群聊各自延续一段 Multica 对话;forum 的每个 topic 分别隔离。
+
+### 命令
+
+- `/new <消息>` 让这条消息不带旧上下文运行;在回复其他成员并明确 @ Bot 时,被选中的引用内容仍会随这条 fresh 指令进入上下文。单独发送 `/new` 会把 fresh 意图应用到下一条非空消息。
+- `/issue <标题>` 创建 Multica issue,后续行作为可选描述;不带标题时返回用法提示。
+- 群聊支持 `/issue@your_bot` 这种 Telegram 命令后缀。
+
+### 回复与内容范围
+
+Bot 通过发送并编辑 Telegram 消息来流式展示文字回复,引用触发消息、保留 forum topic,并按 Telegram 长度限制自动分段。最终回复在进程内异步投递。正常情况下,某个聊天的退避等待不会占用 worker;缓存达到容量上限并压缩退避状态时,同一 Bot installation 下的其他聊天可能被保守延迟。终态队列有固定容量,超限任务会被明确拒绝并记录错误;队列不会跨服务重启恢复。
+
+当前版本只接收文字。图片、文件、视频、语音、贴纸等非文字消息在私聊中会收到明确的不支持提示;群里明确 @ Bot 的媒体消息也会收到提示,未 @ 的媒体消息保持静默。
+
+## 管理与断开
+
+在 **设置 → 集成 → Telegram** 查看所有已连接 Bot。owner 和 admin 可以断开。断开会停止长轮询和后续回复,但保留 Multica 对话与审计记录。
+
+## 自托管配置
+
+启动 API 服务器前配置一个长期稳定的 32 字节加密密钥:
+
+```dotenv
+MULTICA_TELEGRAM_SECRET_KEY=<base64 编码的 32 字节密钥>
+```
+
+可用 `openssl rand -base64 32` 生成。丢失或轮换此密钥后,已有 Bot token 无法解密,需要逐个重新连接。
+
+绑定链接使用 `MULTICA_APP_URL`,未设置时回退到 `FRONTEND_ORIGIN`;生成的地址必须能被成员访问。服务器网络或代理还必须允许 HTTPS 访问 `api.telegram.org`;Go 会读取标准的 `HTTPS_PROXY` 和 `NO_PROXY` 环境变量。
+
+## 故障排查
+
+- **无法验证 Bot**:先检查服务器网络和代理。只有 Telegram 明确拒绝 token 时才需要重新生成。
+- **webhook 冲突**:连接前移除这个 Bot 已有的 webhook;Telegram 不允许 webhook 与 `getUpdates` 同时使用。
+- **409 轮询冲突**:另一个 Multica 实例或进程正在轮询同一个 Bot。停止另一个消费者,或为不同环境使用不同 Bot。
+- **群里不回复**:确认 Bot 已入群,并且消息 @ 了它或回复了它的消息。
+- **绑定链接过期**:重新私聊 Bot,并使用最新链接。
+- **Bot 不执行**:检查智能体是否已归档,以及它使用的[运行时](/daemon-runtimes)是否在线。
+
+## 接下来
+
+- [聊天集成](/channels) — 比较平台并理解会话与身份机制。
+- [与智能体对话](/chat) — Bot 消息如何变成智能体执行。
+- [Issues](/issues) — `/issue` 创建的工作项。
diff --git a/apps/web/app/telegram/bind/page.tsx b/apps/web/app/telegram/bind/page.tsx
new file mode 100644
index 0000000000..1f49548659
--- /dev/null
+++ b/apps/web/app/telegram/bind/page.tsx
@@ -0,0 +1,21 @@
+"use client";
+
+import { Suspense } from "react";
+import { useSearchParams } from "next/navigation";
+import { TelegramBindPage } from "@multica/views/telegram";
+
+// /telegram/bind?token=<raw> is the bot's "link your account" destination.
+// Suspense wraps useSearchParams per Next.js 15's CSR-bailout rule.
+function TelegramBindPageContent() {
+ const searchParams = useSearchParams();
+ const token = searchParams.get("token");
+ return <TelegramBindPage token={token} />;
+}
+
+export default function Page() {
+ return (
+ <Suspense fallback={null}>
+ <TelegramBindPageContent />
+ </Suspense>
+ );
+}
diff --git a/apps/web/features/landing/i18n/en.ts b/apps/web/features/landing/i18n/en.ts
index 57797c73a6..6beec9f3c8 100644
--- a/apps/web/features/landing/i18n/en.ts
+++ b/apps/web/features/landing/i18n/en.ts
@@ -429,6 +429,7 @@ export function createEnDict(allowSignup: boolean): LandingDict {
"Parallel local-folder mode, per-group DingTalk routing, and one-click skill updates",
changes: [],
features: [
+ "Your agents can now live in Telegram — DM them or @-mention them in a group or forum topic.",
"A local folder can now run tasks in parallel, each delivering its own branch.",
"One DingTalk bot can now serve each group with its own agent.",
"Imported skills can now be updated from their source in one click.",
diff --git a/apps/web/features/landing/i18n/ja.ts b/apps/web/features/landing/i18n/ja.ts
index d8707db1e7..8eb442b556 100644
--- a/apps/web/features/landing/i18n/ja.ts
+++ b/apps/web/features/landing/i18n/ja.ts
@@ -405,6 +405,7 @@ export function createJaDict(allowSignup: boolean): LandingDict {
"ローカル フォルダーの並列モード、DingTalk のグループ振り分け、スキルの更新",
changes: [],
features: [
+ "エージェントを Telegram に接続し、DM、グループのメンション、フォーラム トピックで対話できます。",
"ローカル フォルダーでタスクを並列に実行し、それぞれがブランチで成果を返します。",
"1 つの DingTalk ボットで、グループごとに別のエージェントを割り当てられます。",
"インポートしたスキルを、元のソースからワンクリックで更新できます。",
diff --git a/apps/web/features/landing/i18n/ko.ts b/apps/web/features/landing/i18n/ko.ts
index f2d6cea217..b159192f75 100644
--- a/apps/web/features/landing/i18n/ko.ts
+++ b/apps/web/features/landing/i18n/ko.ts
@@ -400,6 +400,7 @@ export function createKoDict(allowSignup: boolean): LandingDict {
title: "로컬 폴더 병렬 모드, DingTalk 그룹별 라우팅, 스킬 원클릭 업데이트",
changes: [],
features: [
+ "에이전트를 Telegram에 연결해 DM, 그룹 멘션, 포럼 토픽에서 대화할 수 있어요.",
"로컬 폴더에서 여러 태스크를 병렬로 돌리고, 각각 브랜치로 결과를 받습니다.",
"DingTalk 봇 하나로 그룹마다 다른 에이전트를 지정할 수 있어요.",
"가져온 스킬을 원본에서 원클릭으로 업데이트할 수 있어요.",
diff --git a/apps/web/features/landing/i18n/zh.ts b/apps/web/features/landing/i18n/zh.ts
index 1cc34ea459..f4b6afa1b0 100644
--- a/apps/web/features/landing/i18n/zh.ts
+++ b/apps/web/features/landing/i18n/zh.ts
@@ -425,6 +425,7 @@ export function createZhDict(allowSignup: boolean): LandingDict {
title: "本地目录并行模式、钉钉分群路由、技能一键更新",
changes: [],
features: [
+ "现在可以把智能体接入 Telegram,在私聊、群组或论坛话题中与它对话。",
"本地目录可以选并行模式,多个任务同时跑,各自交一个分支。",
"一个钉钉机器人可以给不同群指定不同的智能体。",
"导入的技能可以一键更新到最新版,智能体绑定照旧保留。",
diff --git a/docs/telegram-channel-review-2026-08-08.md b/docs/telegram-channel-review-2026-08-08.md
new file mode 100644
index 0000000000..47c8dbfe9e
--- /dev/null
+++ b/docs/telegram-channel-review-2026-08-08.md
@@ -0,0 +1,170 @@
+# Telegram channel review and validation
+
+Final validation: 2026-08-18
+
+Baseline: `multica-ai/multica` `upstream/main` at `c670e0549`
+
+Contribution branch: `codex/telegram-integration`
+
+## Outcome
+
+Telegram is implemented as a first-class Multica channel for text-message
+workflows. The contribution includes backend transport and lifecycle, secure
+installation and account binding, private/group/forum-topic routing, streamed
+quoted replies, slash commands, issue provenance, settings and agent UI,
+localized setup documentation, landing copy, migrations, and regression tests.
+
+The review found and corrected integration, security, transport, UI, and data
+provenance gaps before this contribution was prepared. External review was
+used as advisory input; all acceptance decisions were made from the current
+source and local verification evidence.
+
+## Completed corrections
+
+- Reject long-polling installation when Telegram has an outgoing webhook;
+ Multica does not silently delete another integration's webhook.
+- Sanitize Bot API transport errors so a bot token cannot enter logs or client
+ responses.
+- Require authoritative task and channel provenance before sending Telegram
+ output, with fail-closed behavior on lookup errors.
+- Keep bearer binding links out of groups and validate the binding token's
+ channel type during redemption.
+- Distinguish invalid credentials from network/proxy failure and bound
+ credential verification to 15 seconds.
+- Use Telegram's current `reply_parameters` request shape and retain the
+ triggering message ID through streamed delivery.
+- Parse mention and command entities with Telegram UTF-16 offsets and exact bot
+ username matching.
+- Key streamed output by immutable task ID so simultaneous tasks in one chat
+ cannot share accumulated output.
+- Preserve explicitly quoted human-message text/caption and sender attribution
+ in group context while keeping the sender's own instruction isolated in
+ `CommandText`; `/new` is stripped before enrichment so the selected quote
+ remains attached to the fresh instruction, and unaddressed group chatter
+ remains uncollected.
+- Share stream throttling and Telegram `retry_after` state per chat in a
+ hard-bounded schedule cache. Capacity compression merges active deadlines
+ into a conservative per-installation fallback before deleting exact state.
+- Enqueue `EventChatDone` into a fixed-capacity in-process keyed scheduler that
+ preserves per-session FIFO order. Fixed workers execute one request step,
+ while edit throttles and arbitrary/continuous 429 waits return to a retry
+ heap without occupying a worker. If cache pressure compresses exact backoff
+ state, other chats under the same Bot installation may be conservatively
+ delayed. Global count, per-session count, and total-byte limits reject and
+ log overflow without blocking the event bus. Saved chunk progress avoids
+ repeating successful sends; ambiguous non-429 transport failures remain
+ non-retriable to avoid duplicates.
+- Shutdown cancels in-flight requests, abandons queued and retry-waiting jobs,
+ and releases their local stream/schedule references; restart durability
+ remains outside the in-process scheduler's contract.
+- Release task stream state on cancellation and retry-pending failures without
+ emitting a false terminal failure notice; terminal failures still notify.
+- Enforce Telegram's UTF-16 message size limit, restrict plain-text fallback to
+ entity-parsing errors, and prevent duplicate delivery after ambiguous
+ transport failures.
+- Provide `/new` and `/issue`, including `@botname` command suffixes, usage
+ replies, duplicate-issue handling, and explicit failure responses.
+- Preserve forum-topic IDs for typing indicators, unsupported-media notices,
+ session routing, and outbound replies.
+- Fail closed on malformed management responses instead of rendering false
+ install or account-binding success.
+- Add Telegram to agent integration visibility, settings, realtime cache
+ invalidation, all four product locales, setup documentation, and landing
+ release copy.
+- Extend issue-origin validation with `telegram_chat` through migrations 349
+ and 350 and verify both migration directions and catalog state.
+
+## Capability comparison
+
+| Channel | Text | Thread/topic | Quote | Typing | Edit/stream | Attachment | Rich card |
+| --- | --- | --- | --- | --- | --- | --- | --- |
+| Lark | yes | yes | yes | yes | yes | yes | yes |
+| Slack | yes | yes | no | no | no | no | no |
+| DingTalk | yes | no | no | no | no | yes | no |
+| WeCom | yes | no | no | no | no | yes | no |
+| Telegram | yes | yes | yes | yes | yes | text-only | no |
+
+Telegram's media behavior is an explicit product boundary, not an accidental
+omission. Addressed non-text input receives a documented response and creates
+no task. Rich cards are Lark-specific and are not a cross-channel requirement.
+
+## Automated verification
+
+The following change-scoped checks passed on the contribution:
+
+- `pnpm typecheck`
+- `pnpm lint` with zero errors (repository warnings unchanged)
+- `pnpm build` for Web, Docs, and Desktop
+- `go test ./internal/migrations -count=1`
+- `go test -race ./internal/integrations/telegram -count=1`
+- `go test ./internal/handler -count=1`
+- focused Telegram settings, binding-page, API-schema, locale-parity, migration,
+ install-management, routing, UTF-16, quote, reconnect, and streaming tests
+- `git diff --check`
+- credential-pattern and archive-path scans over the contribution source
+
+The repository-wide TypeScript suite was also exercised in serial mode. It
+completed 364 Views files / 4,325 tests with one unrelated Autopilot dialog
+test timing out; that file then passed 4/4 in an isolated rerun. Focused final
+parity runs covered agent/Telegram settings, locale parity, Telegram binding,
+and core API schemas.
+
+The repository-wide race suite was exercised through `make test`. Every
+Telegram and migration test passed. Five unrelated timing/host-process cases
+in repocache, GitHub snapshot refresh, and channel-media reconciliation failed
+in the concurrent run; all five passed with `-race` in isolated reruns. No
+repository Playwright spec targets Telegram, so the deterministic Bot API
+protocol suite is the relevant E2E boundary for these review corrections.
+
+## Real Telegram verification
+
+Using a local Multica server, migrated local database, local runtime, and an
+existing test bot, the following behaviors were observed against the live
+Telegram Bot API:
+
+- Bot installation and one-time private account binding.
+- Private inbound message -> Multica task -> runtime execution -> streamed
+ outbound Telegram reply.
+- `/new` and `/issue`, including bare commands and
+ `@multica_channel_bot` suffix forms. The incomplete `/fresh` alias was removed
+ in favor of the shared, persisted `/new` contract.
+- Reply quoting through `reply_parameters` for command verdicts and normal
+ agent output.
+- A 20-line response, reconnect after server restart, rapid sequential input,
+ and a supplementary-plane Emoji response (`TG_UTF16_😀_OK`).
+- A real `/issue TG_ORIGIN_MIGRATION_REAL_20260814` created issue `SYCO-1`; its
+ persisted row has `origin_type = 'telegram_chat'` and a non-null `origin_id`.
+- A real 26-byte text-file upload received the documented unsupported-media
+ response and created no task.
+- The Desktop agent integration page displayed Telegram with open and
+ disconnect actions; “Open in Telegram” launched the configured bot chat.
+
+Private-chat behavior is covered by both live E2E and automated tests.
+Group mention/reply, quoted human-message context, command isolation, and
+forum-topic behavior are covered by deterministic Bot API protocol tests. The
+live account's group chooser contained no isolated test group, so the regression
+deliberately avoided modifying unrelated groups or participants.
+
+## Security and release boundaries
+
+- No bot token, binding URL, Telegram sender/chat ID, API key, private key,
+ cookie, browser state, environment file, or database content is stored in
+ this contribution or its source archive.
+- The first release is intentionally text-only; unsupported media follows an
+ explicit, tested response path.
+- Telegram availability requires deployment reachability to
+ `api.telegram.org`; the adapter uses the standard proxy-aware Go transport.
+- A bot token has one active workspace owner, preventing competing long-poll
+ consumers.
+- Migrations were applied only to the authorized local test database. No
+ production deployment, production configuration, or real-user data action
+ was performed.
+
+## Review provenance
+
+External advisory review:
+https://chatgpt.com/c/6a773603-2798-83ec-a368-e298da9da653
+
+The external response was not treated as acceptance evidence. Codex reviewed
+the implementation, applied corrections, and independently ran the checks and
+real Telegram regression recorded above.
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 73ee37602b..a0548eb512 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -186,6 +186,10 @@ import type {
ListWecomInstallationsResponse,
RegisterWecomBYORequest,
RedeemWecomBindingTokenResponse,
+ TelegramInstallation,
+ ListTelegramInstallationsResponse,
+ RegisterTelegramRequest,
+ RedeemTelegramBindingTokenResponse,
Squad,
SquadMember,
SquadMemberStatusListResponse,
@@ -331,6 +335,12 @@ import {
EMPTY_WECOM_INSTALLATION,
EMPTY_LIST_WECOM_INSTALLATIONS_RESPONSE,
EMPTY_REDEEM_WECOM_BINDING_TOKEN_RESPONSE,
+ TelegramInstallationSchema,
+ ListTelegramInstallationsResponseSchema,
+ RedeemTelegramBindingTokenResponseSchema,
+ EMPTY_TELEGRAM_INSTALLATION,
+ EMPTY_LIST_TELEGRAM_INSTALLATIONS_RESPONSE,
+ EMPTY_REDEEM_TELEGRAM_BINDING_TOKEN_RESPONSE,
EMPTY_BILLING_BALANCE,
EMPTY_BILLING_TRANSACTIONS_PAGE,
EMPTY_BILLING_BATCHES_PAGE,
@@ -4252,4 +4262,53 @@ export class ApiClient {
{ endpoint: "POST /api/wecom/binding/redeem" },
);
}
+
+ async listTelegramInstallations(
+ workspaceId: string,
+ ): Promise<ListTelegramInstallationsResponse> {
+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/telegram/installations`);
+ return parseWithFallback(
+ raw,
+ ListTelegramInstallationsResponseSchema,
+ EMPTY_LIST_TELEGRAM_INSTALLATIONS_RESPONSE,
+ { endpoint: "GET /api/workspaces/:id/telegram/installations" },
+ );
+ }
+
+ async registerTelegramBot(
+ workspaceId: string,
+ agentId: string,
+ body: RegisterTelegramRequest,
+ ): Promise<TelegramInstallation> {
+ const search = new URLSearchParams({ agent_id: agentId });
+ const raw = await this.fetch<unknown>(
+ `/api/workspaces/${workspaceId}/telegram/install?${search.toString()}`,
+ {
+ method: "POST",
+ body: JSON.stringify(body),
+ },
+ );
+ return parseWithFallback(raw, TelegramInstallationSchema, EMPTY_TELEGRAM_INSTALLATION, {
+ endpoint: "POST /api/workspaces/:id/telegram/install",
+ });
+ }
+
+ async deleteTelegramInstallation(workspaceId: string, installationId: string): Promise<void> {
+ await this.fetch(`/api/workspaces/${workspaceId}/telegram/installations/${installationId}`, {
+ method: "DELETE",
+ });
+ }
+
+ async redeemTelegramBindingToken(token: string): Promise<RedeemTelegramBindingTokenResponse> {
+ const raw = await this.fetch<unknown>(`/api/telegram/binding/redeem`, {
+ method: "POST",
+ body: JSON.stringify({ token }),
+ });
+ return parseWithFallback(
+ raw,
+ RedeemTelegramBindingTokenResponseSchema,
+ EMPTY_REDEEM_TELEGRAM_BINDING_TOKEN_RESPONSE,
+ { endpoint: "POST /api/telegram/binding/redeem" },
+ );
+ }
}
diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.ts
index fbbf4d28ac..52f5818672 100644
--- a/packages/core/api/schema.test.ts
+++ b/packages/core/api/schema.test.ts
@@ -463,6 +463,49 @@ describe("ApiClient schema fallback", () => {
});
});
+ describe("Telegram integration", () => {
+ it("falls back to a safe empty installation list when the response is malformed", async () => {
+ stubFetchJson({ installations: "not-an-array", configured: true });
+ const client = new ApiClient("https://api.example.test");
+ await expect(client.listTelegramInstallations("ws-1")).resolves.toEqual({
+ installations: [],
+ configured: false,
+ });
+ });
+
+ it("defaults fields omitted by an older server", async () => {
+ stubFetchJson({
+ installations: [{ id: "tg-1", status: "active" }],
+ configured: true,
+ });
+ const client = new ApiClient("https://api.example.test");
+ const res = await client.listTelegramInstallations("ws-1");
+ expect(res.installations[0]).toMatchObject({
+ id: "tg-1",
+ workspace_id: "",
+ agent_id: "",
+ bot_id: "",
+ bot_username: "",
+ });
+ expect(res.install_supported).toBeUndefined();
+ });
+
+ it("falls back safely when register and redeem responses are malformed", async () => {
+ stubFetchJson({ id: 123 });
+ const client = new ApiClient("https://api.example.test");
+ await expect(
+ client.registerTelegramBot("ws-1", "agent-1", { bot_token: "token" }),
+ ).resolves.toMatchObject({ id: "", status: "revoked" });
+
+ stubFetchJson({ workspace_id: 123 });
+ await expect(client.redeemTelegramBindingToken("bind-token")).resolves.toEqual({
+ workspace_id: "",
+ installation_id: "",
+ telegram_user_id: "",
+ });
+ });
+ });
+
describe("getConfig", () => {
it("drops malformed daemon setup URLs instead of throwing", async () => {
stubFetchJson({
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index 8c4286138d..dbe06cc886 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -7,6 +7,12 @@ import {
EMPTY_WECOM_INSTALLATION,
EMPTY_LIST_WECOM_INSTALLATIONS_RESPONSE,
EMPTY_REDEEM_WECOM_BINDING_TOKEN_RESPONSE,
+ TelegramInstallationSchema,
+ ListTelegramInstallationsResponseSchema,
+ RedeemTelegramBindingTokenResponseSchema,
+ EMPTY_TELEGRAM_INSTALLATION,
+ EMPTY_LIST_TELEGRAM_INSTALLATIONS_RESPONSE,
+ EMPTY_REDEEM_TELEGRAM_BINDING_TOKEN_RESPONSE,
AgentTaskListSchema,
AutopilotQuotaUsageSchema,
AutopilotRunSchema,
@@ -1450,6 +1456,66 @@ describe("WeCom installation schemas", () => {
});
});
+// Telegram drives the same connect/disabled/revoked UI decisions as WeCom.
+// Keep its wire-contract fallbacks explicit so malformed or older responses
+// cannot render a bot as connected or report a binding success.
+describe("Telegram installation schemas", () => {
+ it("parses a well-formed installation", () => {
+ const parsed = TelegramInstallationSchema.parse({
+ id: "i1",
+ workspace_id: "w1",
+ agent_id: "a1",
+ bot_id: "12345",
+ bot_username: "multica_test_bot",
+ installer_user_id: "u1",
+ status: "active",
+ });
+ expect(parsed.bot_username).toBe("multica_test_bot");
+ expect(parsed.status).toBe("active");
+ });
+
+ it("defaults incomplete data to the disconnected state", () => {
+ const parsed = TelegramInstallationSchema.parse({ id: "i1" });
+ expect(parsed.status).toBe("revoked");
+ expect(parsed.bot_id).toBe("");
+ expect(parsed.bot_username).toBe("");
+
+ const list = ListTelegramInstallationsResponseSchema.parse({});
+ expect(list).toEqual({ installations: [], configured: false });
+ });
+
+ it("keeps unknown forward-compatible installation fields", () => {
+ const parsed = TelegramInstallationSchema.parse({ id: "i1", future_field: "keep" });
+ expect((parsed as unknown as { future_field?: string }).future_field).toBe("keep");
+ });
+
+ it("falls back safely for malformed list, install, and redeem responses", () => {
+ expect(
+ parseWithFallback(
+ "not json",
+ ListTelegramInstallationsResponseSchema,
+ EMPTY_LIST_TELEGRAM_INSTALLATIONS_RESPONSE,
+ { endpoint: "GET /api/workspaces/:id/telegram/installations" },
+ ),
+ ).toEqual(EMPTY_LIST_TELEGRAM_INSTALLATIONS_RESPONSE);
+
+ expect(
+ parseWithFallback(42, TelegramInstallationSchema, EMPTY_TELEGRAM_INSTALLATION, {
+ endpoint: "POST /api/workspaces/:id/telegram/install",
+ }),
+ ).toEqual(EMPTY_TELEGRAM_INSTALLATION);
+
+ expect(
+ parseWithFallback(
+ null,
+ RedeemTelegramBindingTokenResponseSchema,
+ EMPTY_REDEEM_TELEGRAM_BINDING_TOKEN_RESPONSE,
+ { endpoint: "POST /api/telegram/binding/redeem" },
+ ),
+ ).toEqual(EMPTY_REDEEM_TELEGRAM_BINDING_TOKEN_RESPONSE);
+ });
+});
+
describe("Plugin schemas", () => {
it("defaults every missing installation field to an inert, disabled shape", () => {
const parsed = PluginInstallationSchema.parse({ id: "installation-1" });
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 876e07c091..3a85602905 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -37,6 +37,9 @@ import type {
WecomInstallation,
ListWecomInstallationsResponse,
RedeemWecomBindingTokenResponse,
+ TelegramInstallation,
+ ListTelegramInstallationsResponse,
+ RedeemTelegramBindingTokenResponse,
GroupedIssuesResponse,
GitHubConnectResponse,
GitHubPullRequest,
@@ -2648,6 +2651,55 @@ export const EMPTY_REDEEM_WECOM_BINDING_TOKEN_RESPONSE: RedeemWecomBindingTokenR
wecom_user_id: "",
};
+export const TelegramInstallationSchema = z.object({
+ id: z.string(),
+ workspace_id: z.string().default(""),
+ agent_id: z.string().default(""),
+ bot_id: z.string().default(""),
+ bot_username: z.string().default(""),
+ installer_user_id: z.string().default(""),
+ status: z.string().default("revoked"),
+ installed_at: z.string().default(""),
+ created_at: z.string().default(""),
+ updated_at: z.string().default(""),
+}).loose();
+
+export const EMPTY_TELEGRAM_INSTALLATION: TelegramInstallation = {
+ id: "",
+ workspace_id: "",
+ agent_id: "",
+ bot_id: "",
+ bot_username: "",
+ installer_user_id: "",
+ status: "revoked",
+ installed_at: "",
+ created_at: "",
+ updated_at: "",
+};
+
+export const ListTelegramInstallationsResponseSchema = z.object({
+ installations: z.array(TelegramInstallationSchema).default([]),
+ configured: z.boolean().default(false),
+ install_supported: z.boolean().optional(),
+}).loose();
+
+export const EMPTY_LIST_TELEGRAM_INSTALLATIONS_RESPONSE: ListTelegramInstallationsResponse = {
+ installations: [],
+ configured: false,
+};
+
+export const RedeemTelegramBindingTokenResponseSchema = z.object({
+ workspace_id: z.string().default(""),
+ installation_id: z.string().default(""),
+ telegram_user_id: z.string().default(""),
+}).loose();
+
+export const EMPTY_REDEEM_TELEGRAM_BINDING_TOKEN_RESPONSE: RedeemTelegramBindingTokenResponse = {
+ workspace_id: "",
+ installation_id: "",
+ telegram_user_id: "",
+};
+
// Skills. Introduced for `POST /api/skills/:id/refresh` (update a skill from
// its imported source). `config` stays a loose record: the server owns the
// `origin` provenance shape and may extend it freely.
diff --git a/packages/core/package.json b/packages/core/package.json
index e09368a6bd..ce4523f6ea 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -126,6 +126,8 @@
"./dingtalk/queries": "./dingtalk/queries.ts",
"./wecom": "./wecom/index.ts",
"./wecom/queries": "./wecom/queries.ts",
+ "./telegram": "./telegram/index.ts",
+ "./telegram/queries": "./telegram/queries.ts",
"./feedback": "./feedback/index.ts",
"./feedback/mutations": "./feedback/mutations.ts",
"./realtime": "./realtime/index.ts",
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 402ba760fe..5e506b81ed 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -28,6 +28,7 @@ import { larkKeys } from "../lark/queries";
import { slackKeys } from "../slack/queries";
import { dingtalkKeys } from "../dingtalk/queries";
import { wecomKeys } from "../wecom/queries";
+import { telegramKeys } from "../telegram/queries";
import {
onIssueCreated,
onIssueUpdated,
@@ -856,6 +857,10 @@ export function useRealtimeSync(
const wsId = getCurrentWsId();
if (wsId) qc.invalidateQueries({ queryKey: wecomKeys.installations(wsId) });
},
+ telegram_installation: () => {
+ const wsId = getCurrentWsId();
+ if (wsId) qc.invalidateQueries({ queryKey: telegramKeys.installations(wsId) });
+ },
pull_request: () => {
// PR list is keyed by issue id, not workspace, so we invalidate all
// PR queries — the open issue detail page will refetch its own list.
diff --git a/packages/core/telegram/index.ts b/packages/core/telegram/index.ts
new file mode 100644
index 0000000000..14bd79b2e7
--- /dev/null
+++ b/packages/core/telegram/index.ts
@@ -0,0 +1 @@
+export { telegramKeys, telegramInstallationsOptions } from "./queries";
diff --git a/packages/core/telegram/queries.ts b/packages/core/telegram/queries.ts
new file mode 100644
index 0000000000..af721e5250
--- /dev/null
+++ b/packages/core/telegram/queries.ts
@@ -0,0 +1,17 @@
+import { queryOptions } from "@tanstack/react-query";
+import { api } from "../api";
+
+/** Query key namespace for everything Telegram-installation-related. Realtime
+ * sync invalidates `installations(wsId)` on `telegram_installation:*` events
+ * so the Settings panel updates without a manual refetch. */
+export const telegramKeys = {
+ all: (wsId: string) => ["telegram", wsId] as const,
+ installations: (wsId: string) => [...telegramKeys.all(wsId), "installations"] as const,
+};
+
+export const telegramInstallationsOptions = (wsId: string) =>
+ queryOptions({
+ queryKey: telegramKeys.installations(wsId),
+ queryFn: () => api.listTelegramInstallations(wsId),
+ enabled: !!wsId,
+ });
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 3cacd641ce..164acd6cb0 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -232,6 +232,12 @@ export type {
RegisterWecomBYORequest,
RedeemWecomBindingTokenResponse,
} from "./wecom";
+export type {
+ TelegramInstallation,
+ ListTelegramInstallationsResponse,
+ RegisterTelegramRequest,
+ RedeemTelegramBindingTokenResponse,
+} from "./telegram";
export type {
Autopilot,
AutopilotStatus,
diff --git a/packages/core/types/telegram.ts b/packages/core/types/telegram.ts
new file mode 100644
index 0000000000..d4d9bd75a1
--- /dev/null
+++ b/packages/core/types/telegram.ts
@@ -0,0 +1,46 @@
+/** A Telegram bot installation bound to a single Multica agent.
+ *
+ * Wire shape mirrors `TelegramInstallationResponse` in
+ * `server/internal/handler/telegram.go`. New fields the backend adds in the
+ * future MUST default to optional so older desktop builds keep parsing the
+ * response — see CLAUDE.md → API Compatibility. */
+export interface TelegramInstallation {
+ id: string;
+ workspace_id: string;
+ agent_id: string;
+ /** The bot's numeric Telegram id (the token prefix), as a string. */
+ bot_id: string;
+ /** The bot's Telegram username (without the @). */
+ bot_username: string;
+ installer_user_id: string;
+ status: "active" | "revoked" | string;
+ installed_at: string;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface ListTelegramInstallationsResponse {
+ installations: TelegramInstallation[];
+ /** Whether the deployment has the at-rest secret key configured. When false
+ * the connect entry points are hidden and the panel renders an "ask the
+ * operator to enable Telegram" state. */
+ configured: boolean;
+ /** Whether the install path is available (true whenever Telegram is
+ * configured — a pasted BotFather token needs no hosted credential).
+ * Optional so an older desktop build that predates it treats it as off. */
+ install_supported?: boolean;
+}
+
+/** Request body for a bot install: the token the admin pastes from
+ * @BotFather. The backend validates it live (getMe) before persisting. */
+export interface RegisterTelegramRequest {
+ bot_token: string;
+}
+
+/** Post-redemption echo: the Telegram user id the token carried is now bound
+ * to the logged-in Multica user in this workspace/installation. */
+export interface RedeemTelegramBindingTokenResponse {
+ workspace_id: string;
+ installation_id: string;
+ telegram_user_id: string;
+}
diff --git a/packages/views/agents/components/agent-overview-pane.test.tsx b/packages/views/agents/components/agent-overview-pane.test.tsx
index 4d96ce756d..94650837a9 100644
--- a/packages/views/agents/components/agent-overview-pane.test.tsx
+++ b/packages/views/agents/components/agent-overview-pane.test.tsx
@@ -59,6 +59,9 @@ const larkListingRef = vi.hoisted(() => ({
const slackListingRef = vi.hoisted(() => ({
current: { installations: [] as unknown[], configured: false },
}));
+const telegramListingRef = vi.hoisted(() => ({
+ current: { installations: [] as unknown[], configured: false },
+}));
vi.mock("@multica/core/hooks", () => ({
useWorkspaceId: () => "ws-1",
}));
@@ -74,6 +77,12 @@ vi.mock("@multica/core/slack", () => ({
queryFn: () => Promise.resolve(slackListingRef.current),
}),
}));
+vi.mock("@multica/core/telegram", () => ({
+ telegramInstallationsOptions: () => ({
+ queryKey: ["telegram", "installations"],
+ queryFn: () => Promise.resolve(telegramListingRef.current),
+ }),
+}));
import { AgentOverviewPane } from "./agent-overview-pane";
@@ -167,6 +176,7 @@ function openSettings() {
beforeEach(() => {
larkListingRef.current = { installations: [], configured: false };
slackListingRef.current = { installations: [], configured: false };
+ telegramListingRef.current = { installations: [], configured: false };
});
describe("AgentOverviewPane MCP tab visibility", () => {
@@ -226,9 +236,18 @@ describe("AgentOverviewPane Integrations tab visibility", () => {
).toBeInTheDocument();
});
- it("hides the Integrations tab when neither Lark nor Slack is configured", () => {
- // Default refs are configured:false; the tab must not appear on
- // deployments without either integration, the common case.
+ it("shows the Integrations tab when only Telegram is configured", async () => {
+ telegramListingRef.current = { installations: [], configured: true };
+ renderPane([makeRuntime("claude")]);
+ openCapabilities();
+ expect(
+ await screen.findByRole("tab", { name: /^Integrations$/i }),
+ ).toBeInTheDocument();
+ });
+
+ it("hides the Integrations tab when no channel integration is configured", () => {
+ // Default refs are configured:false; the tab must not appear on a
+ // deployment without any channel integration, the common case.
renderPane([makeRuntime("claude")]);
openCapabilities();
expect(
diff --git a/packages/views/agents/components/agent-overview-pane.tsx b/packages/views/agents/components/agent-overview-pane.tsx
index e99f5cbf1f..26199709bc 100644
--- a/packages/views/agents/components/agent-overview-pane.tsx
+++ b/packages/views/agents/components/agent-overview-pane.tsx
@@ -15,6 +15,7 @@ import { larkInstallationsOptions } from "@multica/core/lark";
import { slackInstallationsOptions } from "@multica/core/slack";
import { dingtalkInstallationsOptions } from "@multica/core/dingtalk";
import { wecomInstallationsOptions } from "@multica/core/wecom";
+import { telegramInstallationsOptions } from "@multica/core/telegram";
import {
AlertDialog,
AlertDialogAction,
@@ -180,12 +181,17 @@ export function AgentOverviewPane({
...wecomInstallationsOptions(wsId),
enabled: !!wsId,
});
+ const { data: telegramListing } = useQuery({
+ ...telegramInstallationsOptions(wsId),
+ enabled: !!wsId,
+ });
const integrationsConfigured =
larkListing?.configured === true ||
slackListing?.configured === true ||
dingtalkListing?.configured === true ||
- wecomListing?.configured === true;
+ wecomListing?.configured === true ||
+ telegramListing?.configured === true;
const visibleCapabilityTabs = useMemo(() => {
const showMcp = runtime
diff --git a/packages/views/agents/components/tabs/integrations-tab.test.tsx b/packages/views/agents/components/tabs/integrations-tab.test.tsx
index 342cce1316..d2db766bfc 100644
--- a/packages/views/agents/components/tabs/integrations-tab.test.tsx
+++ b/packages/views/agents/components/tabs/integrations-tab.test.tsx
@@ -68,6 +68,13 @@ vi.mock("@multica/core/wecom", () => ({
}),
}));
+vi.mock("@multica/core/telegram", () => ({
+ telegramInstallationsOptions: () => ({
+ queryKey: ["telegram", "installations"],
+ queryFn: vi.fn(),
+ }),
+}));
+
vi.mock("@multica/core/auth", () => {
const useAuthStore = Object.assign(
(sel?: (s: { user: { id: string } }) => unknown) =>
@@ -109,6 +116,12 @@ vi.mock("../../../settings/components/wecom-tab", () => ({
),
}));
+vi.mock("../../../settings/components/telegram-tab", () => ({
+ TelegramAgentBindButton: ({ agentId }: { agentId: string }) => (
+ <div data-testid="telegram-bind-button" data-agent-id={agentId} />
+ ),
+}));
+
import { IntegrationsTab } from "./integrations-tab";
const TEST_RESOURCES = {
@@ -163,12 +176,17 @@ function resetFixtures() {
describe("IntegrationsTab", () => {
beforeEach(resetFixtures);
- it("renders the shared bind entry for both platforms for an owner when configured and supported", () => {
+ it("renders the shared bind entries for an owner when configured and supported", () => {
renderTab(<IntegrationsTab agent={agent} />);
expect(screen.getByText("Lark")).toBeTruthy();
expect(screen.getByText("Slack")).toBeTruthy();
+ expect(screen.getByText("Telegram")).toBeTruthy();
+ expect(screen.getByText(/Telegram bot.*\/issue.*reply stream live/i)).toBeTruthy();
expect(screen.getByTestId("lark-bind-button").getAttribute("data-agent-id")).toBe("agent-1");
expect(screen.getByTestId("slack-bind-button").getAttribute("data-agent-id")).toBe("agent-1");
+ expect(screen.getByTestId("telegram-bind-button").getAttribute("data-agent-id")).toBe(
+ "agent-1",
+ );
});
it("renders the DingTalk brand mark in the DingTalk integration card", () => {
@@ -210,12 +228,13 @@ describe("IntegrationsTab", () => {
expect(screen.queryByTestId("lark-bind-button")).toBeNull();
expect(screen.queryByTestId("slack-bind-button")).toBeNull();
expect(screen.queryByTestId("wecom-bind-button")).toBeNull();
+ expect(screen.queryByTestId("telegram-bind-button")).toBeNull();
});
it("lets a non-admin agent owner bind Lark but keeps Slack admin-only", () => {
// The agent's owner (user-1) is only a plain workspace member. Lark
// authorizes the agent owner (canManageAgent), so the Lark bind entry
- // renders and receives owner_id; Slack, DingTalk and WeCom routes stay
+ // renders and receives owner_id; Slack, DingTalk, WeCom and Telegram routes stay
// admin-only, so each shows the read-only note instead of a CTA (MUL-4213).
membersRef.current = [{ user_id: "user-1", role: "member" }];
renderTab(<IntegrationsTab agent={agent} />);
@@ -224,11 +243,12 @@ describe("IntegrationsTab", () => {
expect(larkButton.getAttribute("data-agent-owner-id")).toBe("user-1");
expect(screen.queryByTestId("slack-bind-button")).toBeNull();
expect(screen.queryByTestId("wecom-bind-button")).toBeNull();
- // The Slack, DingTalk and WeCom sections each fall back to the shared
+ expect(screen.queryByTestId("telegram-bind-button")).toBeNull();
+ // The Slack, DingTalk, WeCom and Telegram sections each fall back to the shared
// members note.
expect(
screen.getAllByText(/Only workspace owners and admins can connect an agent/i),
- ).toHaveLength(3);
+ ).toHaveLength(4);
});
it("renders the bind entry (not coming-soon) when installs are unavailable but the agent is already bound", () => {
diff --git a/packages/views/agents/components/tabs/integrations-tab.tsx b/packages/views/agents/components/tabs/integrations-tab.tsx
index ef955a0041..91f792c6bc 100644
--- a/packages/views/agents/components/tabs/integrations-tab.tsx
+++ b/packages/views/agents/components/tabs/integrations-tab.tsx
@@ -8,6 +8,7 @@ import { larkInstallationsOptions } from "@multica/core/lark";
import { slackInstallationsOptions } from "@multica/core/slack";
import { dingtalkInstallationsOptions } from "@multica/core/dingtalk";
import { wecomInstallationsOptions } from "@multica/core/wecom";
+import { telegramInstallationsOptions } from "@multica/core/telegram";
import { memberListOptions } from "@multica/core/workspace/queries";
import { LarkAgentBindButton } from "../../../settings/components/lark-tab";
import { LarkMark } from "../../../settings/components/lark-mark";
@@ -17,6 +18,8 @@ import { DingTalkAgentBindButton } from "../../../settings/components/dingtalk-t
import { DingTalkMark } from "../../../settings/components/dingtalk-mark";
import { WecomAgentBindButton } from "../../../settings/components/wecom-tab";
import { WecomMark } from "../../../settings/components/wecom-mark";
+import { TelegramAgentBindButton } from "../../../settings/components/telegram-tab";
+import { TelegramMark } from "../../../settings/components/telegram-mark";
import { useT } from "../../../i18n";
/**
@@ -57,6 +60,10 @@ export function IntegrationsTab({ agent }: { agent: Agent }) {
...wecomInstallationsOptions(wsId),
enabled: !!wsId,
});
+ const { data: telegramListing } = useQuery({
+ ...telegramInstallationsOptions(wsId),
+ enabled: !!wsId,
+ });
const { data: members = [] } = useQuery({
...memberListOptions(wsId),
enabled: !!wsId,
@@ -77,6 +84,7 @@ export function IntegrationsTab({ agent }: { agent: Agent }) {
const canManageLark = isWorkspaceAdmin || isAgentOwner;
const canManageSlack = isWorkspaceAdmin;
const canManageWecom = isWorkspaceAdmin;
+ const canManageTelegram = isWorkspaceAdmin;
const hasActiveInstall =
listing?.installations.some(
(inst) => inst.agent_id === agent.id && inst.status === "active",
@@ -101,11 +109,24 @@ export function IntegrationsTab({ agent }: { agent: Agent }) {
(inst) => inst.agent_id === agent.id && inst.status === "active",
) ?? false;
+ const telegramConfigured = telegramListing?.configured === true;
+ const telegramInstallSupported = telegramListing?.install_supported === true;
+ const telegramHasActiveInstall =
+ telegramListing?.installations.some(
+ (inst) => inst.agent_id === agent.id && inst.status === "active",
+ ) ?? false;
+
// A member who can manage no platform (not a workspace admin and not this
// agent's owner) gets the read-only note instead of the sections.
// Members can still view connected bots in the (member-visible)
// Settings → Integrations listing.
- if (!canManageLark && !canManageSlack && !canManageDingtalk && !canManageWecom) {
+ if (
+ !canManageLark &&
+ !canManageSlack &&
+ !canManageDingtalk &&
+ !canManageWecom &&
+ !canManageTelegram
+ ) {
return (
<div className="space-y-6">
<p className="text-caption text-muted-foreground">
@@ -274,6 +295,40 @@ export function IntegrationsTab({ agent }: { agent: Agent }) {
)}
</div>
</section>
+
+ <section className="rounded-lg border">
+ <div className="flex items-start gap-3 p-4">
+ <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md border bg-muted/40 text-muted-foreground">
+ <TelegramMark className="h-4 w-4" />
+ </span>
+ <div className="min-w-0 flex-1 space-y-1">
+ <h3 className="text-body font-medium">{ts(($) => $.telegram.section_title)}</h3>
+ <p className="text-caption leading-relaxed text-muted-foreground">
+ {ts(($) => $.telegram.page_description)}
+ </p>
+ </div>
+ </div>
+ <div className="border-t px-4 py-3">
+ {!canManageTelegram ? (
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.tab_body.integrations.members_note)}
+ </p>
+ ) : !telegramConfigured ? (
+ <p className="text-caption text-muted-foreground">
+ {ts(($) => $.telegram.not_enabled_title)}
+ </p>
+ ) : !telegramInstallSupported && !telegramHasActiveInstall ? (
+ <div className="space-y-1">
+ <p className="text-caption font-medium">{ts(($) => $.telegram.preview_title)}</p>
+ <p className="text-caption text-muted-foreground">
+ {ts(($) => $.telegram.preview_description)}
+ </p>
+ </div>
+ ) : (
+ <TelegramAgentBindButton agentId={agent.id} agentName={agent.name} />
+ )}
+ </div>
+ </section>
</div>
);
}
diff --git a/packages/views/locales/en/common.json b/packages/views/locales/en/common.json
index 4af6d68ab0..1d09fe235d 100644
--- a/packages/views/locales/en/common.json
+++ b/packages/views/locales/en/common.json
@@ -87,6 +87,21 @@
"error_not_member": "You're signed in to a Multica account that isn't a member of this workspace.",
"error_unknown": "Something went wrong. Try again, and if the problem persists, contact the workspace admin."
},
+ "telegram_bind": {
+ "page_title": "Link your Telegram account",
+ "redeeming": "Linking your account…",
+ "needs_auth_description": "Sign in to Multica to complete the link. The token in the link binds your Telegram account to this Multica user, so you must be logged in first.",
+ "sign_in": "Sign in",
+ "done_title": "You're linked.",
+ "done_description": "Your next message to the bot in Telegram will go straight to the agent. You can close this tab.",
+ "error_title": "Couldn't complete the link",
+ "error_admin_hint": "If this keeps happening, message the bot again in Telegram to get a fresh link.",
+ "error_missing_token": "The link is missing its token. Message the bot again in Telegram to get a new one.",
+ "error_expired": "This link is invalid or expired (links are valid for 15 minutes). Message the bot again to get a new one.",
+ "error_already_bound": "This Telegram account is already linked to a different Multica user. Account transfers must go through an explicit unbind first.",
+ "error_not_member": "You're signed in to a Multica account that isn't a member of this workspace.",
+ "error_unknown": "Something went wrong. Try again, and if the problem persists, contact the workspace admin."
+ },
"expandable_description": {
"expand": "Show more",
"collapse": "Show less"
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 3230795425..67b192d11b 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -1002,6 +1002,47 @@
"byo_install_failed": "Couldn't save this bot — something went wrong on our side. Your credentials were not changed; try again, and contact support if it keeps failing.",
"byo_failed_toast": "Could not connect the WeCom bot"
},
+ "telegram": {
+ "section_title": "Telegram",
+ "page_description": "Connect each Multica Agent to its own Telegram bot. Members can DM the bot, @mention it in a group, type /issue to spin up a new Multica issue, and watch the agent's reply stream live.",
+ "not_enabled_title": "Telegram integration not enabled",
+ "not_enabled_description_prefix": "Set",
+ "not_enabled_description_suffix": "on the server to enable Telegram bot installations.",
+ "not_enabled_self_host_hint": "Self-hosters: see the project README for details.",
+ "preview_title": "Telegram install coming soon",
+ "preview_description": "The at-rest key is set, but installs are not available in this deployment yet. The Connect button will appear here once they are.",
+ "connected_bots": "Connected bots",
+ "loading": "Loading…",
+ "load_failed": "Failed to load Telegram installations",
+ "empty_title": "No bots connected yet",
+ "empty_description_prefix": "Open an Agent in this workspace and click",
+ "empty_description_cta": "Connect Telegram",
+ "empty_description_suffix": "to install a bot for it.",
+ "revoked_badge": "revoked",
+ "installed_at_label": "Installed {{when}}",
+ "disconnect": "Disconnect",
+ "disconnecting": "Disconnecting…",
+ "disconnect_confirm_title": "Disconnect this Telegram bot?",
+ "disconnect_confirm_description": "The bot will stop receiving Telegram messages for this workspace. Chat history in Multica is kept; you can re-connect later from the same Agent.",
+ "disconnect_confirm_cancel": "Cancel",
+ "toast_disconnected": "Disconnected Telegram bot",
+ "toast_disconnect_failed": "Disconnect failed",
+ "bind_button": "Connect Telegram",
+ "bind_button_title": "Connect {{agent}} to a Telegram bot",
+ "agent_bot_connected_label": "Connected to Telegram",
+ "agent_bot_disconnect_tooltip": "Unbind this Telegram bot from the Agent. The bot will stop receiving Telegram messages.",
+ "agent_bot_manage_link": "Open in Telegram",
+ "agent_bot_manage_tooltip": "Open a chat with this bot in Telegram.",
+ "connect_dialog_title": "Connect a Telegram bot",
+ "connect_dialog_description": "Create a bot with @BotFather in Telegram, then paste its token below. The token is verified live and stored encrypted.",
+ "connect_docs_link": "Step-by-step: connect your Multica agent to Telegram",
+ "bot_token_label": "Bot token",
+ "connect_submit": "Connect",
+ "connect_submitting": "Connecting…",
+ "connect_cancel": "Cancel",
+ "connect_success_toast": "Telegram bot connected",
+ "connect_failed_toast": "Could not connect the Telegram bot"
+ },
"repositories": {
"section_title": "Repositories",
"description": "Git repositories associated with this workspace. Agents use these to clone and work on code.",
diff --git a/packages/views/locales/ja/common.json b/packages/views/locales/ja/common.json
index a942005dd6..93affc6eb8 100644
--- a/packages/views/locales/ja/common.json
+++ b/packages/views/locales/ja/common.json
@@ -87,6 +87,21 @@
"error_not_member": "サインインしている Multica アカウントはこのワークスペースのメンバーではありません。",
"error_unknown": "問題が発生しました。もう一度試し、それでも解決しない場合はワークスペース管理者にお問い合わせください。"
},
+ "telegram_bind": {
+ "page_title": "Telegram アカウントをリンク",
+ "redeeming": "アカウントをリンクしています…",
+ "needs_auth_description": "リンクを完了するには Multica にサインインしてください。リンク内のトークンはあなたの Telegram アカウントをこの Multica ユーザーに紐付けるため、先にログインが必要です。",
+ "sign_in": "サインイン",
+ "done_title": "リンクが完了しました。",
+ "done_description": "Telegram でボットに送る次のメッセージは、そのままエージェントに届きます。このタブは閉じて構いません。",
+ "error_title": "リンクを完了できませんでした",
+ "error_admin_hint": "問題が続く場合は、Telegram でボットに再度メッセージを送り、新しいリンクを取得してください。",
+ "error_missing_token": "リンクにトークンがありません。Telegram でボットに再度メッセージを送り、新しいリンクを取得してください。",
+ "error_expired": "このリンクは無効か期限切れです(有効期間は 15 分)。ボットに再度メッセージを送って新しいリンクを取得してください。",
+ "error_already_bound": "この Telegram アカウントは別の Multica ユーザーにリンク済みです。アカウントの移行には先に明示的なリンク解除が必要です。",
+ "error_not_member": "サインイン中の Multica アカウントはこのワークスペースのメンバーではありません。",
+ "error_unknown": "問題が発生しました。再試行しても解決しない場合は、ワークスペース管理者にお問い合わせください。"
+ },
"expandable_description": {
"expand": "詳細を表示",
"collapse": "折りたたむ"
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index e038ac16b8..5797505dad 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -1001,6 +1001,47 @@
"byo_install_failed": "ボットを保存できませんでした。こちら側の問題です。認証情報は変更されていません。もう一度お試しいただき、続くようならサポートにご連絡ください。",
"byo_failed_toast": "WeCom ボットを接続できませんでした"
},
+ "telegram": {
+ "section_title": "Telegram",
+ "page_description": "各 Multica エージェントを専用の Telegram ボットに接続します。メンバーはボットに DM を送ったり、グループで @メンションしたり、/issue と入力して Multica タスクを作成したり、エージェントの返信をリアルタイムで確認できます。",
+ "not_enabled_title": "Telegram 連携が有効になっていません",
+ "not_enabled_description_prefix": "サーバーで",
+ "not_enabled_description_suffix": "を設定すると Telegram ボットのインストールが有効になります。",
+ "not_enabled_self_host_hint": "セルフホストの場合はプロジェクトの README をご覧ください。",
+ "preview_title": "Telegram インストールは近日公開",
+ "preview_description": "暗号化キーは設定済みですが、このデプロイではまだインストールできません。利用可能になると接続ボタンがここに表示されます。",
+ "connected_bots": "接続済みのボット",
+ "loading": "読み込み中…",
+ "load_failed": "Telegram のインストールを読み込めませんでした",
+ "empty_title": "接続済みのボットはまだありません",
+ "empty_description_prefix": "このワークスペースのエージェントを開き、",
+ "empty_description_cta": "Telegram に接続",
+ "empty_description_suffix": "をクリックしてボットをインストールします。",
+ "revoked_badge": "無効化済み",
+ "installed_at_label": "インストール日時 {{when}}",
+ "disconnect": "切断",
+ "disconnecting": "切断中…",
+ "disconnect_confirm_title": "この Telegram ボットを切断しますか?",
+ "disconnect_confirm_description": "ボットはこのワークスペースの Telegram メッセージを受信しなくなります。Multica 内のチャット履歴は保持され、同じエージェントから再接続できます。",
+ "disconnect_confirm_cancel": "キャンセル",
+ "toast_disconnected": "Telegram ボットを切断しました",
+ "toast_disconnect_failed": "切断に失敗しました",
+ "bind_button": "Telegram に接続",
+ "bind_button_title": "{{agent}} を Telegram ボットに接続",
+ "agent_bot_connected_label": "Telegram に接続済み",
+ "agent_bot_disconnect_tooltip": "このエージェントと Telegram ボットのバインドを解除します。ボットはメッセージを受信しなくなります。",
+ "agent_bot_manage_link": "Telegram で開く",
+ "agent_bot_manage_tooltip": "Telegram でこのボットとのチャットを開きます。",
+ "connect_dialog_title": "Telegram ボットを接続",
+ "connect_dialog_description": "Telegram の @BotFather でボットを作成し、そのトークンを以下に貼り付けてください。トークンは即時検証され、暗号化して保存されます。",
+ "connect_docs_link": "手順ガイド:Multica エージェントを Telegram に接続する",
+ "bot_token_label": "ボットトークン",
+ "connect_submit": "接続",
+ "connect_submitting": "接続中…",
+ "connect_cancel": "キャンセル",
+ "connect_success_toast": "Telegram ボットを接続しました",
+ "connect_failed_toast": "Telegram ボットを接続できませんでした"
+ },
"repositories": {
"section_title": "リポジトリ",
"description": "このワークスペースに関連付けられた Git リポジトリです。エージェントはこれらをクローンしてコードを作業します。",
diff --git a/packages/views/locales/ko/common.json b/packages/views/locales/ko/common.json
index b872c908c6..9ed448be07 100644
--- a/packages/views/locales/ko/common.json
+++ b/packages/views/locales/ko/common.json
@@ -87,6 +87,21 @@
"error_not_member": "로그인한 Multica 계정이 이 워크스페이스의 멤버가 아니에요.",
"error_unknown": "문제가 발생했어요. 다시 시도해 보고, 계속되면 워크스페이스 관리자에게 문의하세요."
},
+ "telegram_bind": {
+ "page_title": "Telegram 계정 연결",
+ "redeeming": "계정을 연결하는 중…",
+ "needs_auth_description": "연결을 완료하려면 Multica에 로그인하세요. 링크의 토큰은 Telegram 계정을 현재 로그인한 Multica 사용자에게 바인딩하므로 먼저 로그인해야 합니다.",
+ "sign_in": "로그인",
+ "done_title": "연결되었습니다.",
+ "done_description": "Telegram에서 봇에게 보내는 다음 메시지가 곧바로 에이전트에 전달됩니다. 이 탭을 닫아도 됩니다.",
+ "error_title": "연결을 완료할 수 없습니다",
+ "error_admin_hint": "문제가 계속되면 Telegram에서 봇에게 다시 메시지를 보내 새 링크를 받으세요.",
+ "error_missing_token": "링크에 토큰이 없습니다. Telegram에서 봇에게 다시 메시지를 보내 새 링크를 받으세요.",
+ "error_expired": "이 링크는 유효하지 않거나 만료되었습니다(유효 기간 15분). 봇에게 다시 메시지를 보내 새 링크를 받으세요.",
+ "error_already_bound": "이 Telegram 계정은 이미 다른 Multica 사용자에게 연결되어 있습니다. 계정을 이전하려면 먼저 명시적으로 연결을 해제해야 합니다.",
+ "error_not_member": "로그인한 Multica 계정이 이 워크스페이스의 멤버가 아닙니다.",
+ "error_unknown": "문제가 발생했습니다. 다시 시도하고, 계속되면 워크스페이스 관리자에게 문의하세요."
+ },
"expandable_description": {
"expand": "자세히 보기",
"collapse": "접기"
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index 4b979bbc00..c68e60fe5e 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -749,6 +749,47 @@
"toast_rotated": "Webhook secret regenerated",
"toast_rotate_failed": "Could not regenerate webhook secret"
},
+ "telegram": {
+ "section_title": "Telegram",
+ "page_description": "각 Multica 에이전트를 전용 Telegram 봇에 연결하세요. 멤버는 봇에게 DM을 보내거나 그룹에서 @멘션하고, /issue를 입력해 Multica 태스크를 만들고, 에이전트의 답변을 실시간 스트리밍으로 볼 수 있습니다.",
+ "not_enabled_title": "Telegram 연동이 활성화되지 않았습니다",
+ "not_enabled_description_prefix": "서버에서",
+ "not_enabled_description_suffix": "를 설정하면 Telegram 봇 설치가 활성화됩니다.",
+ "not_enabled_self_host_hint": "셀프 호스팅 사용자는 프로젝트 README를 참고하세요.",
+ "preview_title": "Telegram 설치 곧 제공 예정",
+ "preview_description": "암호화 키는 설정되어 있지만 이 배포에서는 아직 설치할 수 없습니다. 가능해지면 연결 버튼이 여기에 표시됩니다.",
+ "connected_bots": "연결된 봇",
+ "loading": "불러오는 중…",
+ "load_failed": "Telegram 설치를 불러오지 못했습니다",
+ "empty_title": "아직 연결된 봇이 없습니다",
+ "empty_description_prefix": "이 워크스페이스의 에이전트를 열고",
+ "empty_description_cta": "Telegram 연결",
+ "empty_description_suffix": "을 클릭해 봇을 설치하세요.",
+ "revoked_badge": "해지됨",
+ "installed_at_label": "설치일 {{when}}",
+ "disconnect": "연결 해제",
+ "disconnecting": "해제 중…",
+ "disconnect_confirm_title": "이 Telegram 봇의 연결을 해제할까요?",
+ "disconnect_confirm_description": "봇이 이 워크스페이스의 Telegram 메시지를 더 이상 수신하지 않습니다. Multica의 대화 기록은 유지되며 같은 에이전트에서 다시 연결할 수 있습니다.",
+ "disconnect_confirm_cancel": "취소",
+ "toast_disconnected": "Telegram 봇 연결을 해제했습니다",
+ "toast_disconnect_failed": "연결 해제에 실패했습니다",
+ "bind_button": "Telegram 연결",
+ "bind_button_title": "{{agent}}을(를) Telegram 봇에 연결",
+ "agent_bot_connected_label": "Telegram에 연결됨",
+ "agent_bot_disconnect_tooltip": "이 에이전트와 Telegram 봇의 바인딩을 해제합니다. 봇은 더 이상 메시지를 수신하지 않습니다.",
+ "agent_bot_manage_link": "Telegram에서 열기",
+ "agent_bot_manage_tooltip": "Telegram에서 이 봇과의 채팅을 엽니다.",
+ "connect_dialog_title": "Telegram 봇 연결",
+ "connect_dialog_description": "Telegram의 @BotFather로 봇을 만든 뒤 아래에 토큰을 붙여넣으세요. 토큰은 즉시 검증되고 암호화되어 저장됩니다.",
+ "connect_docs_link": "단계별 가이드: Multica 에이전트를 Telegram에 연결하기",
+ "bot_token_label": "봇 토큰",
+ "connect_submit": "연결",
+ "connect_submitting": "연결 중…",
+ "connect_cancel": "취소",
+ "connect_success_toast": "Telegram 봇이 연결되었습니다",
+ "connect_failed_toast": "Telegram 봇을 연결할 수 없습니다"
+ },
"repositories": {
"section_title": "저장소",
"description": "이 워크스페이스와 연결된 Git 저장소입니다. 에이전트는 이 저장소를 클론해 코드 작업을 합니다.",
diff --git a/packages/views/locales/zh-Hans/common.json b/packages/views/locales/zh-Hans/common.json
index 569c3cba94..68f33ca01b 100644
--- a/packages/views/locales/zh-Hans/common.json
+++ b/packages/views/locales/zh-Hans/common.json
@@ -87,6 +87,21 @@
"error_not_member": "你登录的 Multica 账号不是当前工作区成员。",
"error_unknown": "出现未知错误。请稍后再试,如反复失败请联系工作区管理员。"
},
+ "telegram_bind": {
+ "page_title": "绑定你的 Telegram 账号",
+ "redeeming": "正在绑定…",
+ "needs_auth_description": "请先登录 Multica 完成绑定。链接中的 token 会把你的 Telegram 账号绑定到当前登录的 Multica 用户,因此需要先登录。",
+ "sign_in": "登录",
+ "done_title": "绑定成功。",
+ "done_description": "你在 Telegram 中发给机器人的下一条消息将直达智能体。可以关闭此页面了。",
+ "error_title": "绑定未完成",
+ "error_admin_hint": "如果问题持续出现,请在 Telegram 中再给机器人发一条消息以获取新链接。",
+ "error_missing_token": "链接缺少 token。请在 Telegram 中再给机器人发一条消息以获取新链接。",
+ "error_expired": "链接无效或已过期(有效期 15 分钟)。请再给机器人发一条消息以获取新链接。",
+ "error_already_bound": "该 Telegram 账号已绑定到另一个 Multica 用户。如需转移账号,请先显式解绑。",
+ "error_not_member": "当前登录的 Multica 账号不是该工作区的成员。",
+ "error_unknown": "出了点问题。请重试;若问题持续,请联系工作区管理员。"
+ },
"expandable_description": {
"expand": "查看详情",
"collapse": "收起"
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index 1b4187d13c..caccb45196 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -1001,6 +1001,47 @@
"byo_install_failed": "没能保存这个机器人,是我们这边出了问题。你的凭据没有被改动,请重试;如果一直失败,请联系支持。",
"byo_failed_toast": "无法连接企业微信机器人"
},
+ "telegram": {
+ "section_title": "Telegram",
+ "page_description": "将每个 Multica 智能体连接到专属的 Telegram 机器人。成员可私聊机器人、在群里 @ 它、输入 /issue 创建 Multica 任务,并实时看到智能体的流式回复。",
+ "not_enabled_title": "Telegram 集成未启用",
+ "not_enabled_description_prefix": "在服务器上设置",
+ "not_enabled_description_suffix": "以启用 Telegram 机器人安装。",
+ "not_enabled_self_host_hint": "自部署用户:详见项目 README。",
+ "preview_title": "Telegram 安装即将上线",
+ "preview_description": "静态加密密钥已设置,但本部署暂未开放安装。开放后,连接按钮会出现在这里。",
+ "connected_bots": "已连接的机器人",
+ "loading": "加载中…",
+ "load_failed": "加载 Telegram 安装失败",
+ "empty_title": "尚未连接机器人",
+ "empty_description_prefix": "在本工作区打开一个智能体,点击",
+ "empty_description_cta": "连接 Telegram",
+ "empty_description_suffix": "为其安装机器人。",
+ "revoked_badge": "已撤销",
+ "installed_at_label": "安装于 {{when}}",
+ "disconnect": "断开连接",
+ "disconnecting": "正在断开…",
+ "disconnect_confirm_title": "断开此 Telegram 机器人?",
+ "disconnect_confirm_description": "机器人将停止接收本工作区的 Telegram 消息。Multica 中的会话记录会保留;之后可在同一智能体上重新连接。",
+ "disconnect_confirm_cancel": "取消",
+ "toast_disconnected": "已断开 Telegram 机器人",
+ "toast_disconnect_failed": "断开失败",
+ "bind_button": "连接 Telegram",
+ "bind_button_title": "将 {{agent}} 连接到 Telegram 机器人",
+ "agent_bot_connected_label": "已连接 Telegram",
+ "agent_bot_disconnect_tooltip": "解除该智能体与 Telegram 机器人的绑定,机器人将停止接收 Telegram 消息。",
+ "agent_bot_manage_link": "在 Telegram 中打开",
+ "agent_bot_manage_tooltip": "在 Telegram 中打开与该机器人的对话。",
+ "connect_dialog_title": "连接 Telegram 机器人",
+ "connect_dialog_description": "在 Telegram 中通过 @BotFather 创建机器人,然后在下方粘贴它的 token。token 会实时校验并加密存储。",
+ "connect_docs_link": "分步指南:将 Multica 智能体连接到 Telegram",
+ "bot_token_label": "机器人 token",
+ "connect_submit": "连接",
+ "connect_submitting": "正在连接…",
+ "connect_cancel": "取消",
+ "connect_success_toast": "已连接 Telegram 机器人",
+ "connect_failed_toast": "连接 Telegram 机器人失败"
+ },
"repositories": {
"section_title": "代码仓库",
"description": "与该工作区关联的 Git 仓库。智能体会从这里 clone 代码并完成工作。",
diff --git a/packages/views/package.json b/packages/views/package.json
index dd6e1749bb..c881a4ded3 100644
--- a/packages/views/package.json
+++ b/packages/views/package.json
@@ -46,6 +46,7 @@
"./slack": "./slack/index.ts",
"./dingtalk": "./dingtalk/index.ts",
"./wecom": "./wecom/index.ts",
+ "./telegram": "./telegram/index.ts",
"./invite": "./invite/index.ts",
"./invitations": "./invitations/index.ts",
"./onboarding": "./onboarding/index.ts",
diff --git a/packages/views/settings/components/integration-channel-icon.tsx b/packages/views/settings/components/integration-channel-icon.tsx
index 686aecd026..9949d3171a 100644
--- a/packages/views/settings/components/integration-channel-icon.tsx
+++ b/packages/views/settings/components/integration-channel-icon.tsx
@@ -1,9 +1,10 @@
import { DingTalkMark } from "./dingtalk-mark";
import { LarkMark } from "./lark-mark";
import { SlackMark } from "./slack-mark";
+import { TelegramMark } from "./telegram-mark";
import { WecomMark } from "./wecom-mark";
-type IntegrationChannel = "lark" | "slack" | "dingtalk" | "wecom";
+type IntegrationChannel = "lark" | "slack" | "dingtalk" | "wecom" | "telegram";
// Every channel gets its own brand mark, never a generic lucide glyph: the icon
// is what tells a reader which platform the section belongs to, and a stand-in
@@ -16,6 +17,7 @@ export function IntegrationChannelIcon({ channel }: { channel: IntegrationChanne
slack: <SlackMark className="h-4 w-4" />,
dingtalk: <DingTalkMark className="h-5 w-5" />,
wecom: <WecomMark className="h-4 w-4" />,
+ telegram: <TelegramMark className="h-4 w-4" />,
}[channel];
return (
diff --git a/packages/views/settings/components/integrations-tab.test.tsx b/packages/views/settings/components/integrations-tab.test.tsx
index d5e731dc8c..76d08daf80 100644
--- a/packages/views/settings/components/integrations-tab.test.tsx
+++ b/packages/views/settings/components/integrations-tab.test.tsx
@@ -57,6 +57,10 @@ vi.mock("./wecom-tab", () => ({
WecomTab: () => <div data-testid="wecom-tab" />,
}));
+vi.mock("./telegram-tab", () => ({
+ TelegramTab: () => <div data-testid="telegram-tab" />,
+}));
+
import { IntegrationsTab } from "./integrations-tab";
afterEach(cleanup);
@@ -99,7 +103,7 @@ describe("Settings IntegrationsTab", () => {
it("shows each channel description below its icon and title", () => {
renderTab();
- for (const channel of ["lark", "slack", "dingtalk", "wecom"]) {
+ for (const channel of ["lark", "slack", "dingtalk", "wecom", "telegram"]) {
const icon = screen.getByTestId(`integration-channel-icon-${channel}`);
const title = icon.closest("h3");
const description = title?.nextElementSibling;
@@ -113,12 +117,12 @@ describe("Settings IntegrationsTab", () => {
// Reaching for a generic lucide glyph is how Slack and WeCom ended up sharing
// one speech bubble, with nothing on the row saying which platform it was
- // (#6585). Requiring four distinct shapes is the cheap guard against a
+ // (#6585). Requiring five distinct shapes is the cheap guard against a
// regression to that.
it("gives every channel its own brand mark", () => {
renderTab();
- const shapes = ["lark", "slack", "dingtalk", "wecom"].map(
+ const shapes = ["lark", "slack", "dingtalk", "wecom", "telegram"].map(
(channel) => screen.getByTestId(`integration-channel-icon-${channel}`).innerHTML,
);
diff --git a/packages/views/settings/components/integrations-tab.tsx b/packages/views/settings/components/integrations-tab.tsx
index 809c7ac801..5b1725f2fa 100644
--- a/packages/views/settings/components/integrations-tab.tsx
+++ b/packages/views/settings/components/integrations-tab.tsx
@@ -7,6 +7,7 @@ import { SlackTab } from "./slack-tab";
import { DingTalkTab } from "./dingtalk-tab";
import { VCSTab } from "./vcs-tab";
import { WecomTab } from "./wecom-tab";
+import { TelegramTab } from "./telegram-tab";
import { ApiError } from "@multica/core/api";
import { composioToolkitsOptions } from "@multica/core/composio";
import { useConfigStore, useFeatureEnabled } from "@multica/core/config";
@@ -17,8 +18,8 @@ import { IntegrationChannelIcon } from "./integration-channel-icon";
// Integrations is the umbrella tab for third-party platform connections.
// GitHub has its own top-level tab (see github-tab.tsx); everything else
-// — currently Lark, Composio, Slack, the self-hosted Git providers (Forgejo /
-// Gitea / GitLab), and WeCom smart-bot, with Linear etc. to follow —
+// — currently Lark, Composio, Slack, Telegram, the self-hosted Git providers
+// (Forgejo / Gitea / GitLab), and WeCom smart-bot, with Linear etc. to follow —
// lives in here under its own section heading so additional integrations slot
// in without changing the IA. IntegrationsTab is just the host; each
// integration owns its own description and install flow.
@@ -94,6 +95,17 @@ export function IntegrationsTab() {
>
<WecomTab />
</SettingsSection>
+ <SettingsSection
+ title={
+ <span className="flex items-center gap-2">
+ <IntegrationChannelIcon channel="telegram" />
+ {t(($) => $.telegram.section_title)}
+ </span>
+ }
+ description={t(($) => $.telegram.page_description)}
+ >
+ <TelegramTab />
+ </SettingsSection>
</SettingsTab>
);
}
diff --git a/packages/views/settings/components/telegram-mark.tsx b/packages/views/settings/components/telegram-mark.tsx
new file mode 100644
index 0000000000..03a3e0b78a
--- /dev/null
+++ b/packages/views/settings/components/telegram-mark.tsx
@@ -0,0 +1,16 @@
+// The Telegram brand mark below comes from Simple Icons and is available
+// under CC0 1.0. Source:
+// https://github.com/simple-icons/simple-icons/blob/develop/icons/telegram.svg
+// https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md
+export function TelegramMark({ className }: { className?: string }) {
+ return (
+ <svg
+ viewBox="0 0 24 24"
+ aria-hidden="true"
+ className={className}
+ fill="currentColor"
+ >
+ <path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z" />
+ </svg>
+ );
+}
diff --git a/packages/views/settings/components/telegram-tab.test.tsx b/packages/views/settings/components/telegram-tab.test.tsx
new file mode 100644
index 0000000000..9d1c394369
--- /dev/null
+++ b/packages/views/settings/components/telegram-tab.test.tsx
@@ -0,0 +1,331 @@
+// @vitest-environment jsdom
+
+import { type ReactNode } from "react";
+import { describe, it, expect, beforeEach, vi } from "vitest";
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enCommon from "../../locales/en/common.json";
+import enSettings from "../../locales/en/settings.json";
+
+type MemberRole = "owner" | "admin" | "member" | "guest";
+
+const membersRef = vi.hoisted(() => ({
+ current: [{ user_id: "user-1", role: "owner" as MemberRole }],
+}));
+const installationsRef = vi.hoisted(() => ({
+ current: {
+ installations: [] as unknown[],
+ configured: true,
+ install_supported: true,
+ },
+}));
+const mockRegister = vi.hoisted(() => vi.fn());
+const mockDeleteInstallation = vi.hoisted(() => vi.fn());
+const mockOpenExternal = vi.hoisted(() => vi.fn());
+const mockInvalidate = vi.hoisted(() => vi.fn());
+const mockToastError = vi.hoisted(() => vi.fn());
+const telegramQueryErrorRef = vi.hoisted(() => ({ current: false }));
+const telegramQueryLoadingRef = vi.hoisted(() => ({ current: false }));
+
+vi.mock("@tanstack/react-query", () => ({
+ useQuery: (opts: { queryKey: unknown[]; enabled?: boolean }) => {
+ if (opts.enabled === false) return { data: undefined, isLoading: false };
+ const key = JSON.stringify(opts.queryKey);
+ if (key.includes("members")) return { data: membersRef.current, isLoading: false };
+ if (key.includes("installations")) {
+ return {
+ data: telegramQueryLoadingRef.current ? undefined : installationsRef.current,
+ isLoading: telegramQueryLoadingRef.current,
+ isError: telegramQueryErrorRef.current,
+ };
+ }
+ return { data: undefined, isLoading: false };
+ },
+ useQueryClient: () => ({ invalidateQueries: mockInvalidate }),
+ queryOptions: <T,>(opts: T) => opts,
+}));
+
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));
+
+vi.mock("@multica/core/workspace/queries", () => ({
+ memberListOptions: () => ({ queryKey: ["members"], queryFn: vi.fn() }),
+}));
+
+vi.mock("@multica/core/workspace/hooks", () => ({
+ useActorName: () => ({
+ getAgentName: (agentId: string) => `Agent ${agentId}`,
+ getMemberName: () => "Unknown",
+ getSquadName: () => "Unknown Squad",
+ getActorName: () => "Unknown",
+ getActorInitials: () => "??",
+ getActorAvatarUrl: () => null,
+ }),
+}));
+
+vi.mock("../../common/actor-avatar", () => ({
+ ActorAvatar: ({ actorId }: { actorId: string }) => (
+ <span data-testid="actor-avatar" data-actor-id={actorId} />
+ ),
+}));
+
+vi.mock("@multica/core/telegram", () => ({
+ telegramInstallationsOptions: () => ({
+ queryKey: ["telegram", "installations"],
+ queryFn: vi.fn(),
+ }),
+ telegramKeys: { installations: (wsId: string) => ["telegram", "installations", wsId] },
+}));
+
+vi.mock("@multica/core/api", () => ({
+ api: {
+ registerTelegramBot: mockRegister,
+ deleteTelegramInstallation: mockDeleteInstallation,
+ },
+}));
+
+vi.mock("@multica/core/auth", () => {
+ const useAuthStore = Object.assign(
+ (sel?: (s: { user: { id: string } }) => unknown) =>
+ sel ? sel({ user: { id: "user-1" } }) : { user: { id: "user-1" } },
+ { getState: () => ({ user: { id: "user-1" } }) },
+ );
+ return { useAuthStore };
+});
+
+vi.mock("sonner", () => ({
+ toast: { success: vi.fn(), error: mockToastError, message: vi.fn() },
+}));
+
+vi.mock("../../platform", () => ({ openExternal: mockOpenExternal }));
+
+import { TelegramAgentBindButton, TelegramTab } from "./telegram-tab";
+
+const TEST_RESOURCES = { en: { common: enCommon, settings: enSettings } };
+
+function renderUI(children: ReactNode) {
+ return render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ {children}
+ </I18nProvider>,
+ );
+}
+
+function resetFixtures() {
+ vi.clearAllMocks();
+ membersRef.current = [{ user_id: "user-1", role: "owner" }];
+ installationsRef.current = { installations: [], configured: true, install_supported: true };
+ telegramQueryErrorRef.current = false;
+ telegramQueryLoadingRef.current = false;
+}
+
+describe("TelegramAgentBindButton", () => {
+ beforeEach(resetFixtures);
+
+ it("opens the connect dialog and submits the pasted bot token", async () => {
+ mockRegister.mockResolvedValue({ id: "i1", agent_id: "agent-1", status: "active" });
+ renderUI(<TelegramAgentBindButton agentId="agent-1" agentName="Bot" />);
+ await userEvent.click(screen.getByTestId("telegram-agent-connect"));
+ const tokenInput = await screen.findByTestId("telegram-bot-token");
+ expect(tokenInput).toHaveAttribute("type", "password");
+ await userEvent.type(tokenInput, "123456789:AAtesttoken");
+ await userEvent.click(screen.getByTestId("telegram-connect-submit"));
+ await waitFor(() =>
+ expect(mockRegister).toHaveBeenCalledWith("workspace-1", "agent-1", {
+ bot_token: "123456789:AAtesttoken",
+ }),
+ );
+ expect(mockOpenExternal).not.toHaveBeenCalled();
+ });
+
+ it("opens the localized Telegram setup guide", async () => {
+ renderUI(<TelegramAgentBindButton agentId="agent-1" agentName="Bot" />);
+ await userEvent.click(screen.getByTestId("telegram-agent-connect"));
+ await userEvent.click(await screen.findByTestId("telegram-docs-link"));
+ expect(mockOpenExternal).toHaveBeenCalledWith(
+ "https://multica.ai/docs/telegram-bot-integration",
+ );
+ });
+
+ it("does not report success for a malformed install response", async () => {
+ mockRegister.mockResolvedValue({});
+ renderUI(<TelegramAgentBindButton agentId="agent-1" agentName="Bot" />);
+ await userEvent.click(screen.getByTestId("telegram-agent-connect"));
+ await userEvent.type(await screen.findByTestId("telegram-bot-token"), "123456789:AAtesttoken");
+ await userEvent.click(screen.getByTestId("telegram-connect-submit"));
+ await waitFor(() => expect(mockToastError).toHaveBeenCalled());
+ expect(mockInvalidate).not.toHaveBeenCalled();
+ });
+
+ it("shows the connected badge (not the CTA) when the agent already has an active install", () => {
+ installationsRef.current = {
+ installations: [
+ { id: "i1", agent_id: "agent-1", status: "active", bot_username: "my_bot" },
+ ],
+ configured: true,
+ install_supported: true,
+ };
+ renderUI(<TelegramAgentBindButton agentId="agent-1" />);
+ expect(screen.getByTestId("telegram-agent-bot-connected")).toBeTruthy();
+ expect(screen.getByTestId("telegram-agent-bot-disconnect")).toBeTruthy();
+ expect(screen.queryByTestId("telegram-agent-connect")).toBeNull();
+ });
+
+ it("opens the connected bot in Telegram", async () => {
+ installationsRef.current = {
+ installations: [
+ { id: "i1", agent_id: "agent-1", status: "active", bot_username: "my_bot" },
+ ],
+ configured: true,
+ install_supported: true,
+ };
+ renderUI(<TelegramAgentBindButton agentId="agent-1" />);
+
+ await userEvent.click(screen.getByRole("button", { name: /Open in Telegram/i }));
+
+ expect(mockOpenExternal).toHaveBeenCalledWith("https://t.me/my_bot");
+ });
+
+ it("disconnects an agent bot only after confirmation", async () => {
+ mockDeleteInstallation.mockResolvedValue(undefined);
+ installationsRef.current = {
+ installations: [
+ { id: "i1", agent_id: "agent-1", status: "active", bot_username: "my_bot" },
+ ],
+ configured: true,
+ install_supported: true,
+ };
+ renderUI(<TelegramAgentBindButton agentId="agent-1" />);
+
+ await userEvent.click(screen.getByTestId("telegram-agent-bot-disconnect"));
+ expect(mockDeleteInstallation).not.toHaveBeenCalled();
+ const actions = await screen.findAllByRole("button", { name: /^Disconnect$/i });
+ await userEvent.click(actions.at(-1)!);
+
+ await waitFor(() =>
+ expect(mockDeleteInstallation).toHaveBeenCalledWith("workspace-1", "i1"),
+ );
+ expect(mockInvalidate).toHaveBeenCalled();
+ });
+
+ it("keeps an agent bot connected when disconnect fails", async () => {
+ mockDeleteInstallation.mockRejectedValue(new Error("network failed"));
+ installationsRef.current = {
+ installations: [
+ { id: "i1", agent_id: "agent-1", status: "active", bot_username: "my_bot" },
+ ],
+ configured: true,
+ install_supported: true,
+ };
+ renderUI(<TelegramAgentBindButton agentId="agent-1" />);
+
+ await userEvent.click(screen.getByTestId("telegram-agent-bot-disconnect"));
+ const actions = await screen.findAllByRole("button", { name: /^Disconnect$/i });
+ await userEvent.click(actions.at(-1)!);
+
+ await waitFor(() => expect(mockToastError).toHaveBeenCalledWith("network failed"));
+ expect(screen.getByTestId("telegram-agent-bot-connected")).toBeTruthy();
+ expect(mockInvalidate).not.toHaveBeenCalled();
+ });
+
+ it("renders nothing for a non-manager", () => {
+ membersRef.current = [{ user_id: "user-1", role: "member" }];
+ const { container } = renderUI(<TelegramAgentBindButton agentId="agent-1" />);
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("renders nothing when install is unavailable and the agent is unbound", () => {
+ installationsRef.current = { installations: [], configured: true, install_supported: false };
+ const { container } = renderUI(<TelegramAgentBindButton agentId="agent-1" />);
+ expect(container).toBeEmptyDOMElement();
+ });
+});
+
+describe("TelegramTab", () => {
+ beforeEach(resetFixtures);
+
+ it("shows a loading state without claiming Telegram is disabled", () => {
+ telegramQueryLoadingRef.current = true;
+ renderUI(<TelegramTab />);
+ expect(screen.getByText("Loading…")).toBeTruthy();
+ expect(screen.queryByText(/Telegram integration not enabled/i)).toBeNull();
+ });
+
+ it("surfaces the not-enabled notice when the deployment has no Telegram key", () => {
+ installationsRef.current = { installations: [], configured: false, install_supported: false };
+ renderUI(<TelegramTab />);
+ expect(screen.getByText(/Telegram integration not enabled/i)).toBeTruthy();
+ });
+
+ it("shows the empty state when configured but nothing is connected", () => {
+ renderUI(<TelegramTab />);
+ expect(screen.getByText(/No bots connected yet/i)).toBeTruthy();
+ });
+
+ it("lists a connected installation with its agent name and a disconnect control", () => {
+ installationsRef.current = {
+ installations: [
+ { id: "i1", agent_id: "agent-7", status: "active", bot_username: "my_bot" },
+ ],
+ configured: true,
+ install_supported: true,
+ };
+ renderUI(<TelegramTab />);
+ expect(screen.getByText("Agent agent-7")).toBeTruthy();
+ expect(screen.getByText("@my_bot")).toBeTruthy();
+ expect(screen.getByText(/Disconnect/i)).toBeTruthy();
+ });
+
+ it("disconnects only after confirmation and refreshes the installation list", async () => {
+ mockDeleteInstallation.mockResolvedValue(undefined);
+ installationsRef.current = {
+ installations: [
+ { id: "i1", agent_id: "agent-7", status: "active", bot_username: "my_bot" },
+ ],
+ configured: true,
+ install_supported: true,
+ };
+ renderUI(<TelegramTab />);
+ await userEvent.click(screen.getByRole("button", { name: /Disconnect/i }));
+ expect(mockDeleteInstallation).not.toHaveBeenCalled();
+ const actions = await screen.findAllByRole("button", { name: /^Disconnect$/i });
+ await userEvent.click(actions.at(-1)!);
+ await waitFor(() =>
+ expect(mockDeleteInstallation).toHaveBeenCalledWith("workspace-1", "i1"),
+ );
+ expect(mockInvalidate).toHaveBeenCalled();
+ });
+
+ it("keeps the installation visible when disconnect fails", async () => {
+ mockDeleteInstallation.mockRejectedValue(new Error("network failed"));
+ installationsRef.current = {
+ installations: [
+ { id: "i1", agent_id: "agent-7", status: "active", bot_username: "my_bot" },
+ ],
+ configured: true,
+ install_supported: true,
+ };
+ renderUI(<TelegramTab />);
+ await userEvent.click(screen.getByRole("button", { name: /Disconnect/i }));
+ const actions = await screen.findAllByRole("button", { name: /^Disconnect$/i });
+ await userEvent.click(actions.at(-1)!);
+ await waitFor(() => expect(mockToastError).toHaveBeenCalledWith("network failed"));
+ expect(screen.getByText("@my_bot")).toBeTruthy();
+ expect(mockInvalidate).not.toHaveBeenCalled();
+ });
+
+ // Malformed-response defense (CLAUDE.md → API Compatibility): a response
+ // missing `installations` must not crash the panel.
+ it("tolerates a malformed installations response", () => {
+ installationsRef.current = { configured: true } as never;
+ renderUI(<TelegramTab />);
+ expect(screen.getByText(/No bots connected yet/i)).toBeTruthy();
+ });
+
+ it("shows a load error instead of pretending Telegram is disabled", () => {
+ telegramQueryErrorRef.current = true;
+ renderUI(<TelegramTab />);
+ expect(screen.getByText(/Failed to load Telegram installations/i)).toBeTruthy();
+ expect(screen.queryByText(/Telegram integration not enabled/i)).toBeNull();
+ });
+});
diff --git a/packages/views/settings/components/telegram-tab.tsx b/packages/views/settings/components/telegram-tab.tsx
new file mode 100644
index 0000000000..74acdb7018
--- /dev/null
+++ b/packages/views/settings/components/telegram-tab.tsx
@@ -0,0 +1,554 @@
+"use client";
+
+import { useState } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { ChevronRight, ExternalLink, Trash2 } from "lucide-react";
+import { TelegramMark } from "./telegram-mark";
+import { cn } from "@multica/ui/lib/utils";
+import { Button } from "@multica/ui/components/ui/button";
+import { Card, CardContent } from "@multica/ui/components/ui/card";
+import {
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { Input } from "@multica/ui/components/ui/input";
+import { Label } from "@multica/ui/components/ui/label";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
+import { useAuthStore } from "@multica/core/auth";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { memberListOptions } from "@multica/core/workspace/queries";
+import { useActorName } from "@multica/core/workspace/hooks";
+import { telegramInstallationsOptions, telegramKeys } from "@multica/core/telegram";
+import { api } from "@multica/core/api";
+import type { TelegramInstallation } from "@multica/core/types";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { openExternal } from "../../platform";
+import { useT } from "../../i18n";
+
+// TelegramTab is the workspace settings panel for Telegram bot installations,
+// mirroring SlackTab: listing is member-visible; the disconnect action is
+// admin-only (backend-enforced; the UI hides the button to match). Adding a
+// new installation flows through the Agent detail page — the install path is
+// per-agent (one bot per agent, the (workspace_id, agent_id, channel_type)
+// UNIQUE in channel_installation).
+export function TelegramTab() {
+ const { t } = useT("settings");
+ const wsId = useWorkspaceId();
+ const qc = useQueryClient();
+ const user = useAuthStore((s) => s.user);
+
+ const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const currentMember = members.find((m) => m.user_id === user?.id) ?? null;
+ const canManage =
+ currentMember?.role === "owner" || currentMember?.role === "admin";
+
+ const { data, isLoading, isError } = useQuery({
+ ...telegramInstallationsOptions(wsId),
+ enabled: !!wsId,
+ });
+ const installations = data?.installations ?? [];
+ const configured = data?.configured === true;
+
+ const [disconnectTarget, setDisconnectTarget] = useState<string | null>(null);
+ const [disconnecting, setDisconnecting] = useState(false);
+
+ async function handleDisconnect() {
+ if (!disconnectTarget || disconnecting) return;
+ setDisconnecting(true);
+ try {
+ // Await the server before touching cache/UI (repo rule: no optimistic
+ // removal on flows that confirm/destroy).
+ await api.deleteTelegramInstallation(wsId, disconnectTarget);
+ await qc.invalidateQueries({ queryKey: telegramKeys.installations(wsId) });
+ toast.success(t(($) => $.telegram.toast_disconnected));
+ setDisconnectTarget(null);
+ } catch (e) {
+ toast.error(
+ e instanceof Error ? e.message : t(($) => $.telegram.toast_disconnect_failed),
+ );
+ } finally {
+ setDisconnecting(false);
+ }
+ }
+
+ return (
+ <div className="space-y-8">
+ {isError ? (
+ <Card>
+ <CardContent>
+ <p className="text-body text-muted-foreground">
+ {t(($) => $.telegram.load_failed)}
+ </p>
+ </CardContent>
+ </Card>
+ ) : isLoading ? (
+ <Card>
+ <CardContent>
+ <p className="text-body text-muted-foreground">{t(($) => $.telegram.loading)}</p>
+ </CardContent>
+ </Card>
+ ) : !configured ? (
+ <Card>
+ <CardContent className="space-y-2">
+ <p className="text-body font-medium">{t(($) => $.telegram.not_enabled_title)}</p>
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.telegram.not_enabled_description_prefix)}{" "}
+ <code className="rounded bg-muted px-1 py-0.5 text-micro">
+ MULTICA_TELEGRAM_SECRET_KEY
+ </code>{" "}
+ {t(($) => $.telegram.not_enabled_description_suffix)}{" "}
+ {t(($) => $.telegram.not_enabled_self_host_hint)}
+ </p>
+ </CardContent>
+ </Card>
+ ) : (
+ <section className="space-y-3">
+ <h2 className="text-body font-semibold">{t(($) => $.telegram.connected_bots)}</h2>
+ {installations.length === 0 ? (
+ <Card>
+ <CardContent className="space-y-2">
+ <p className="text-body font-medium">{t(($) => $.telegram.empty_title)}</p>
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.telegram.empty_description_prefix)}{" "}
+ <strong>{t(($) => $.telegram.empty_description_cta)}</strong>{" "}
+ {t(($) => $.telegram.empty_description_suffix)}
+ </p>
+ </CardContent>
+ </Card>
+ ) : (
+ <Card>
+ <CardContent className="divide-y">
+ {installations.map((inst) => (
+ <InstallationRow
+ key={inst.id}
+ installation={inst}
+ canManage={canManage}
+ onDisconnect={() => setDisconnectTarget(inst.id)}
+ />
+ ))}
+ </CardContent>
+ </Card>
+ )}
+ </section>
+ )}
+
+ <AlertDialog
+ open={!!disconnectTarget}
+ onOpenChange={(v) => {
+ if (!v && !disconnecting) setDisconnectTarget(null);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(($) => $.telegram.disconnect_confirm_title)}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => $.telegram.disconnect_confirm_description)}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={disconnecting}>
+ {t(($) => $.telegram.disconnect_confirm_cancel)}
+ </AlertDialogCancel>
+ <AlertDialogAction onClick={handleDisconnect} disabled={disconnecting}>
+ {disconnecting
+ ? t(($) => $.telegram.disconnecting)
+ : t(($) => $.telegram.disconnect)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+}
+
+function InstallationRow({
+ installation,
+ canManage,
+ onDisconnect,
+}: {
+ installation: TelegramInstallation;
+ canManage: boolean;
+ onDisconnect: () => void;
+}) {
+ const { t } = useT("settings");
+ const { getAgentName } = useActorName();
+ const isActive = installation.status === "active";
+ const agentName = getAgentName(installation.agent_id);
+ return (
+ <div className="flex items-start justify-between gap-4 py-3 first:pt-0 last:pb-0">
+ <div className="flex items-start gap-3">
+ <ActorAvatar
+ actorType="agent"
+ actorId={installation.agent_id}
+ size="lg"
+ enableHoverCard
+ profileLink
+ />
+ <div className="space-y-1">
+ <p className="text-body font-medium">
+ {agentName}
+ {installation.bot_username ? (
+ <span className="ml-2 text-caption text-muted-foreground">
+ @{installation.bot_username}
+ </span>
+ ) : null}
+ {!isActive && (
+ <span className="ml-2 rounded bg-muted px-1.5 py-0.5 text-micro text-muted-foreground">
+ {t(($) => $.telegram.revoked_badge)}
+ </span>
+ )}
+ </p>
+ <p className="text-micro text-muted-foreground">
+ {t(($) => $.telegram.installed_at_label, {
+ when: new Date(installation.installed_at).toLocaleString(),
+ })}
+ </p>
+ </div>
+ </div>
+ {canManage && isActive && (
+ <Button variant="outline" size="sm" onClick={onDisconnect}>
+ <Trash2 className="h-3 w-3" />
+ {t(($) => $.telegram.disconnect)}
+ </Button>
+ )}
+ </div>
+ );
+}
+
+// telegramDocsUrl points at the Telegram integration guide on the docs site,
+// localized like the Slack docs link.
+function telegramDocsUrl(lang: string | undefined): string {
+ const prefix = lang?.startsWith("zh")
+ ? "/zh"
+ : lang?.startsWith("ja")
+ ? "/ja"
+ : lang?.startsWith("ko")
+ ? "/ko"
+ : "";
+ return `https://multica.ai/docs${prefix}/telegram-bot-integration`;
+}
+
+// TelegramAgentBindButton is the per-agent CTA on the agent detail page.
+// Telegram uses the paste-a-token model: the admin creates a bot with
+// @BotFather and pastes its token; the backend validates via getMe before
+// persisting. Visibility mirrors SlackAgentBindButton (owner/admin only).
+export function TelegramAgentBindButton({
+ agentId,
+ agentName,
+ className,
+ onShowConnectedDetails,
+}: {
+ agentId: string;
+ agentName?: string;
+ className?: string;
+ /** Compact read-only connected row that invokes this instead of the full
+ * badge — the agent inspector passes a "jump to the Integrations tab"
+ * handler so management actions live in one place. */
+ onShowConnectedDetails?: () => void;
+}) {
+ const { t, i18n } = useT("settings");
+ const wsId = useWorkspaceId();
+ const qc = useQueryClient();
+ const user = useAuthStore((s) => s.user);
+
+ const [dialogOpen, setDialogOpen] = useState(false);
+ const [botToken, setBotToken] = useState("");
+ const [submitting, setSubmitting] = useState(false);
+
+ const { data: listing } = useQuery({
+ ...telegramInstallationsOptions(wsId),
+ enabled: !!wsId,
+ });
+ const installSupported = listing?.install_supported === true;
+
+ const { data: members = [] } = useQuery({
+ ...memberListOptions(wsId),
+ enabled: !!wsId,
+ });
+ const currentMember = members.find((m) => m.user_id === user?.id) ?? null;
+ const canManage =
+ currentMember?.role === "owner" || currentMember?.role === "admin";
+
+ if (!canManage) return null;
+
+ const existing = listing?.installations.find(
+ (inst) => inst.agent_id === agentId && inst.status === "active",
+ );
+ if (existing) {
+ return onShowConnectedDetails ? (
+ <TelegramAgentBotStatusRow
+ onClick={onShowConnectedDetails}
+ className={className}
+ />
+ ) : (
+ <TelegramAgentBotConnectedBadge installation={existing} className={className} />
+ );
+ }
+
+ if (!installSupported) return null;
+
+ function closeDialog() {
+ if (submitting) return;
+ setDialogOpen(false);
+ setBotToken("");
+ }
+
+ async function handleSubmit() {
+ const bot_token = botToken.trim();
+ if (submitting || !agentId || !bot_token) return;
+ setSubmitting(true);
+ try {
+ const installation = await api.registerTelegramBot(wsId, agentId, { bot_token });
+ if (!installation.id || installation.status !== "active") {
+ throw new Error("Telegram connection returned an invalid installation");
+ }
+ // The telegram_installation realtime event also refreshes this list, but
+ // invalidate explicitly so the connected badge appears immediately.
+ await qc.invalidateQueries({ queryKey: telegramKeys.installations(wsId) });
+ toast.success(t(($) => $.telegram.connect_success_toast));
+ setDialogOpen(false);
+ setBotToken("");
+ } catch (e) {
+ toast.error(
+ e instanceof Error ? e.message : t(($) => $.telegram.connect_failed_toast),
+ );
+ } finally {
+ setSubmitting(false);
+ }
+ }
+
+ const canSubmit = botToken.trim() !== "" && !submitting;
+
+ return (
+ <div
+ className={cn("flex flex-wrap items-center gap-2", className)}
+ data-testid="telegram-agent-bind-buttons"
+ >
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setDialogOpen(true)}
+ disabled={!agentId}
+ title={
+ agentName
+ ? t(($) => $.telegram.bind_button_title, { agent: agentName })
+ : undefined
+ }
+ data-testid="telegram-agent-connect"
+ >
+ <TelegramMark className="h-3 w-3" />
+ {t(($) => $.telegram.bind_button)}
+ </Button>
+
+ <Dialog
+ open={dialogOpen}
+ onOpenChange={(v) => (v ? setDialogOpen(true) : closeDialog())}
+ >
+ <DialogContent className="sm:max-w-lg" data-testid="telegram-connect-dialog">
+ <DialogHeader>
+ <DialogTitle>{t(($) => $.telegram.connect_dialog_title)}</DialogTitle>
+ </DialogHeader>
+
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.telegram.connect_dialog_description)}
+ </p>
+
+ <button
+ type="button"
+ onClick={() => openExternal(telegramDocsUrl(i18n.language))}
+ className="inline-flex w-fit items-center gap-2 text-body font-medium text-primary underline-offset-2 hover:underline"
+ data-testid="telegram-docs-link"
+ >
+ <ExternalLink className="h-4 w-4" />
+ {t(($) => $.telegram.connect_docs_link)}
+ </button>
+
+ <div className="space-y-1.5">
+ <Label htmlFor="telegram-bot-token">
+ {t(($) => $.telegram.bot_token_label)}
+ </Label>
+ <Input
+ id="telegram-bot-token"
+ data-testid="telegram-bot-token"
+ type="password"
+ value={botToken}
+ onChange={(e) => setBotToken(e.target.value)}
+ placeholder="123456789:AA…"
+ autoComplete="off"
+ spellCheck={false}
+ disabled={submitting}
+ />
+ </div>
+
+ <DialogFooter>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={closeDialog}
+ disabled={submitting}
+ >
+ {t(($) => $.telegram.connect_cancel)}
+ </Button>
+ <Button
+ size="sm"
+ onClick={handleSubmit}
+ disabled={!canSubmit}
+ data-testid="telegram-connect-submit"
+ >
+ {submitting
+ ? t(($) => $.telegram.connect_submitting)
+ : t(($) => $.telegram.connect_submit)}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
+
+// TelegramAgentBotStatusRow is the compact, read-only connected affordance the
+// agent inspector renders; it deep-links into the Integrations tab.
+function TelegramAgentBotStatusRow({
+ onClick,
+ className,
+}: {
+ onClick: () => void;
+ className?: string;
+}) {
+ const { t } = useT("settings");
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className={cn(
+ "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-caption text-muted-foreground transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
+ className,
+ )}
+ data-testid="telegram-agent-bot-status"
+ >
+ <span className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500" />
+ <span className="truncate">{t(($) => $.telegram.agent_bot_connected_label)}</span>
+ <ChevronRight className="ml-auto h-3.5 w-3.5 shrink-0" />
+ </button>
+ );
+}
+
+// TelegramAgentBotConnectedBadge is the full "already connected" affordance:
+// status + Disconnect, then an "Open in Telegram" deep link to the bot.
+function TelegramAgentBotConnectedBadge({
+ installation,
+ className,
+}: {
+ installation: TelegramInstallation;
+ className?: string;
+}) {
+ const { t } = useT("settings");
+ const wsId = useWorkspaceId();
+ const qc = useQueryClient();
+
+ const [confirmOpen, setConfirmOpen] = useState(false);
+ const [disconnecting, setDisconnecting] = useState(false);
+
+ async function handleDisconnect() {
+ if (disconnecting) return;
+ setDisconnecting(true);
+ try {
+ await api.deleteTelegramInstallation(wsId, installation.id);
+ await qc.invalidateQueries({ queryKey: telegramKeys.installations(wsId) });
+ toast.success(t(($) => $.telegram.toast_disconnected));
+ setConfirmOpen(false);
+ } catch (e) {
+ toast.error(
+ e instanceof Error ? e.message : t(($) => $.telegram.toast_disconnect_failed),
+ );
+ } finally {
+ setDisconnecting(false);
+ }
+ }
+
+ return (
+ <div
+ className={cn("space-y-2", className)}
+ data-testid="telegram-agent-bot-connected"
+ >
+ <div className="flex items-center justify-between gap-3">
+ <span className="inline-flex min-w-0 items-center gap-2 text-caption text-muted-foreground">
+ <span className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500" />
+ <span className="truncate">
+ {t(($) => $.telegram.agent_bot_connected_label)}
+ {installation.bot_username ? ` · @${installation.bot_username}` : ""}
+ </span>
+ </span>
+ <Button
+ variant="destructive"
+ size="sm"
+ onClick={() => setConfirmOpen(true)}
+ disabled={disconnecting}
+ title={t(($) => $.telegram.agent_bot_disconnect_tooltip)}
+ aria-label={t(($) => $.telegram.disconnect)}
+ data-testid="telegram-agent-bot-disconnect"
+ >
+ <Trash2 className="h-3 w-3" />
+ {disconnecting
+ ? t(($) => $.telegram.disconnecting)
+ : t(($) => $.telegram.disconnect)}
+ </Button>
+ </div>
+
+ {installation.bot_username && (
+ <button
+ type="button"
+ onClick={() => openExternal(`https://t.me/${installation.bot_username}`)}
+ className="inline-flex items-center gap-1 text-caption text-muted-foreground underline-offset-2 transition-colors hover:text-foreground hover:underline"
+ title={t(($) => $.telegram.agent_bot_manage_tooltip)}
+ >
+ <ExternalLink className="h-3 w-3" />
+ {t(($) => $.telegram.agent_bot_manage_link)}
+ </button>
+ )}
+
+ <AlertDialog
+ open={confirmOpen}
+ onOpenChange={(v) => {
+ if (!v && !disconnecting) setConfirmOpen(false);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(($) => $.telegram.disconnect_confirm_title)}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => $.telegram.disconnect_confirm_description)}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={disconnecting}>
+ {t(($) => $.telegram.disconnect_confirm_cancel)}
+ </AlertDialogCancel>
+ <AlertDialogAction onClick={handleDisconnect} disabled={disconnecting}>
+ {disconnecting
+ ? t(($) => $.telegram.disconnecting)
+ : t(($) => $.telegram.disconnect)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+}
diff --git a/packages/views/telegram/bind-page.test.tsx b/packages/views/telegram/bind-page.test.tsx
new file mode 100644
index 0000000000..bd31b5faf1
--- /dev/null
+++ b/packages/views/telegram/bind-page.test.tsx
@@ -0,0 +1,153 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { render, screen, waitFor, fireEvent } from "@testing-library/react";
+import { StrictMode, type ReactNode } from "react";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enCommon from "../locales/en/common.json";
+
+const TEST_RESOURCES = { en: { common: enCommon } };
+
+const mockAuthState = vi.hoisted(() => ({
+ user: null as { id: string; email: string } | null,
+ isLoading: false,
+}));
+const mockNavigatePush = vi.hoisted(() => vi.fn());
+const mockRedeemToken = vi.hoisted(() => vi.fn());
+
+vi.mock("@multica/core/auth", () => {
+ const useAuthStore = Object.assign(
+ (selector?: (state: typeof mockAuthState) => unknown) =>
+ selector ? selector(mockAuthState) : mockAuthState,
+ { getState: () => mockAuthState },
+ );
+ return { useAuthStore };
+});
+
+vi.mock("../navigation/context", () => ({
+ useNavigation: () => ({ push: mockNavigatePush }),
+ useOptionalNavigation: () => ({ push: mockNavigatePush }),
+}));
+
+vi.mock("@multica/core/api", () => ({
+ api: { redeemTelegramBindingToken: mockRedeemToken },
+}));
+
+import { TelegramBindPage } from "./bind-page";
+
+function I18nWrapper({ children }: { children: ReactNode }) {
+ return (
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ {children}
+ </I18nProvider>
+ );
+}
+
+function renderPage(token: string | null) {
+ return render(<TelegramBindPage token={token} />, { wrapper: I18nWrapper });
+}
+
+describe("TelegramBindPage", () => {
+ beforeEach(() => {
+ mockAuthState.user = null;
+ mockAuthState.isLoading = false;
+ mockNavigatePush.mockReset();
+ mockRedeemToken.mockReset();
+ });
+
+ it("shows linking state while authentication is loading", () => {
+ mockAuthState.isLoading = true;
+ renderPage("tok123");
+ expect(screen.getByText(/linking your account/i)).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: /sign in/i })).toBeNull();
+ expect(mockRedeemToken).not.toHaveBeenCalled();
+ });
+
+ it("requires sign-in before redeeming", () => {
+ renderPage("tok123");
+ expect(screen.getByRole("button", { name: /sign in/i })).toBeInTheDocument();
+ expect(mockRedeemToken).not.toHaveBeenCalled();
+ });
+
+ it("preserves the token in the login next parameter", () => {
+ renderPage("token with+/reserved");
+ fireEvent.click(screen.getByRole("button", { name: /sign in/i }));
+
+ expect(mockNavigatePush).toHaveBeenCalledTimes(1);
+ const destination = mockNavigatePush.mock.calls[0]?.[0] as string;
+ expect(destination).toContain("/login?next=");
+ expect(destination).not.toContain("?redirect=");
+ expect(decodeURIComponent(destination.split("next=")[1] ?? "")).toBe(
+ "/telegram/bind?token=token%20with%2B%2Freserved",
+ );
+ });
+
+ it("redeems immediately when signed in and shows success", async () => {
+ mockAuthState.user = { id: "u1", email: "[email protected]" };
+ mockRedeemToken.mockResolvedValue({
+ workspace_id: "ws1",
+ installation_id: "inst1",
+ telegram_user_id: "tg1",
+ });
+
+ renderPage("tok123");
+
+ await waitFor(() => expect(mockRedeemToken).toHaveBeenCalledWith("tok123"));
+ await waitFor(() => expect(screen.getByText(/you're linked/i)).toBeInTheDocument());
+ });
+
+ it("redeems a one-time token exactly once under StrictMode", async () => {
+ mockAuthState.user = { id: "u1", email: "[email protected]" };
+ mockRedeemToken
+ .mockResolvedValueOnce({
+ workspace_id: "ws1",
+ installation_id: "inst1",
+ telegram_user_id: "tg1",
+ })
+ .mockRejectedValueOnce(new Error("410 binding token invalid or expired"));
+
+ render(
+ <StrictMode>
+ <TelegramBindPage token="single-use-token" />
+ </StrictMode>,
+ { wrapper: I18nWrapper },
+ );
+
+ await waitFor(() => expect(screen.getByText(/you're linked/i)).toBeInTheDocument());
+ expect(mockRedeemToken).toHaveBeenCalledTimes(1);
+ });
+
+ it("rejects a malformed success response", async () => {
+ mockAuthState.user = { id: "u1", email: "[email protected]" };
+ mockRedeemToken.mockResolvedValue({
+ workspace_id: "",
+ installation_id: "",
+ telegram_user_id: "",
+ });
+
+ renderPage("tok123");
+
+ await waitFor(() => expect(screen.getByText(/something went wrong/i)).toBeInTheDocument());
+ });
+
+ it("shows the missing-token error without calling the API", () => {
+ renderPage(null);
+ expect(screen.getByText(/missing its token/i)).toBeInTheDocument();
+ expect(mockRedeemToken).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["410", /invalid or expired/i],
+ ["expired", /invalid or expired/i],
+ ["409", /already linked to a different Multica user/i],
+ ["already bound", /already linked to a different Multica user/i],
+ ["403", /isn't a member of this workspace/i],
+ ["workspace member", /isn't a member of this workspace/i],
+ ["unexpected failure", /something went wrong/i],
+ ])("maps a %s redemption failure to the correct message", async (message, expected) => {
+ mockAuthState.user = { id: "u1", email: "[email protected]" };
+ mockRedeemToken.mockRejectedValue(new Error(message));
+
+ renderPage("tok123");
+
+ await waitFor(() => expect(screen.getByText(expected)).toBeInTheDocument());
+ });
+});
diff --git a/packages/views/telegram/bind-page.tsx b/packages/views/telegram/bind-page.tsx
new file mode 100644
index 0000000000..594da230ee
--- /dev/null
+++ b/packages/views/telegram/bind-page.tsx
@@ -0,0 +1,132 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { Card, CardContent } from "@multica/ui/components/ui/card";
+import { Button } from "@multica/ui/components/ui/button";
+import { api } from "@multica/core/api";
+import { useAuthStore } from "@multica/core/auth";
+import { useNavigation } from "../navigation";
+import { useT } from "../i18n";
+
+type RedeemState =
+ | { kind: "idle" }
+ | { kind: "redeeming" }
+ | { kind: "done"; workspaceId: string; installationId: string }
+ | { kind: "needs-auth" }
+ | { kind: "error"; reason: string };
+
+// TelegramBindPage is the destination the bot's "link your account" prompt
+// points at, mirroring SlackBindPage. Auth is required before redeeming: the
+// redeemer's Multica identity comes from the session, never the token.
+export function TelegramBindPage({ token }: { token: string | null }) {
+ const { t } = useT("common");
+ const user = useAuthStore((s) => s.user);
+ const isAuthLoading = useAuthStore((s) => s.isLoading);
+ const navigation = useNavigation();
+ const [state, setState] = useState<RedeemState>({ kind: "idle" });
+
+ useEffect(() => {
+ if (!token) {
+ setState({ kind: "error", reason: "missing_token" });
+ return;
+ }
+ if (isAuthLoading) return;
+ if (!user) {
+ setState({ kind: "needs-auth" });
+ return;
+ }
+ if (state.kind !== "idle" && state.kind !== "needs-auth") return;
+ setState({ kind: "redeeming" });
+ (async () => {
+ try {
+ const resp = await api.redeemTelegramBindingToken(token);
+ if (!resp.workspace_id || !resp.installation_id || !resp.telegram_user_id) {
+ throw new Error("Telegram binding returned a malformed response");
+ }
+ setState({
+ kind: "done",
+ workspaceId: resp.workspace_id,
+ installationId: resp.installation_id,
+ });
+ } catch (e) {
+ setState({ kind: "error", reason: redemptionFailureReason(e) });
+ }
+ })();
+ }, [token, user, isAuthLoading, state.kind]);
+
+ return (
+ <div className="mx-auto flex min-h-screen max-w-md flex-col items-center justify-center p-6">
+ <Card className="w-full">
+ <CardContent className="space-y-4">
+ <h1 className="text-title font-semibold">{t(($) => $.telegram_bind.page_title)}</h1>
+ {state.kind === "idle" || state.kind === "redeeming" ? (
+ <p className="text-body text-muted-foreground">{t(($) => $.telegram_bind.redeeming)}</p>
+ ) : state.kind === "needs-auth" ? (
+ <>
+ <p className="text-body text-muted-foreground">
+ {t(($) => $.telegram_bind.needs_auth_description)}
+ </p>
+ <Button
+ size="sm"
+ onClick={() =>
+ navigation.push(
+ `/login?next=${encodeURIComponent(
+ `/telegram/bind?token=${encodeURIComponent(token ?? "")}`,
+ )}`,
+ )
+ }
+ >
+ {t(($) => $.telegram_bind.sign_in)}
+ </Button>
+ </>
+ ) : state.kind === "done" ? (
+ <>
+ <p className="text-body font-medium">{t(($) => $.telegram_bind.done_title)}</p>
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.telegram_bind.done_description)}
+ </p>
+ </>
+ ) : (
+ <>
+ <p className="text-body font-medium">{t(($) => $.telegram_bind.error_title)}</p>
+ <p className="text-caption text-muted-foreground">
+ {(() => {
+ switch (state.reason) {
+ case "missing_token":
+ return t(($) => $.telegram_bind.error_missing_token);
+ case "expired":
+ return t(($) => $.telegram_bind.error_expired);
+ case "already_bound":
+ return t(($) => $.telegram_bind.error_already_bound);
+ case "not_member":
+ return t(($) => $.telegram_bind.error_not_member);
+ default:
+ return t(($) => $.telegram_bind.error_unknown);
+ }
+ })()}
+ </p>
+ <p className="text-micro text-muted-foreground">
+ {t(($) => $.telegram_bind.error_admin_hint)}
+ </p>
+ </>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ );
+}
+
+function redemptionFailureReason(err: unknown): string {
+ const msg = err instanceof Error ? err.message : "";
+ const lower = msg.toLowerCase();
+ if (lower.includes("invalid") || lower.includes("expired") || lower.includes("410")) {
+ return "expired";
+ }
+ if (lower.includes("already bound") || lower.includes("409")) {
+ return "already_bound";
+ }
+ if (lower.includes("workspace member") || lower.includes("403")) {
+ return "not_member";
+ }
+ return "unknown";
+}
diff --git a/packages/views/telegram/index.ts b/packages/views/telegram/index.ts
new file mode 100644
index 0000000000..3ea799371e
--- /dev/null
+++ b/packages/views/telegram/index.ts
@@ -0,0 +1 @@
+export { TelegramBindPage } from "./bind-page";
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index bca7f393ab..ef2b4e7854 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -541,6 +541,9 @@ func main() {
if h.WebhookDeliveryWorker != nil {
go h.WebhookDeliveryWorker.Run(sweepCtx)
}
+ if h.TelegramOutbound != nil {
+ h.TelegramOutbound.Start(sweepCtx)
+ }
// GitHub PR-card API snapshot pipeline (MUL-5265): worker pool + TTL sweeper.
// No-op when unconfigured (no App private key).
h.PRRefresh.Start(sweepCtx)
@@ -649,6 +652,9 @@ func main() {
if h.WebhookDeliveryWorker != nil && !h.WebhookDeliveryWorker.WaitWithTimeout(5*time.Second) {
slog.Warn("webhook delivery worker did not exit within shutdown timeout")
}
+ if h.TelegramOutbound != nil && !h.TelegramOutbound.WaitWithTimeout(5*time.Second) {
+ slog.Warn("telegram outbound workers did not exit within shutdown timeout")
+ }
// Join the channel supervisor's per-installation goroutines so the
// lease renewer can issue a final release before process exit;
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index f246712b06..043a4a087f 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -32,6 +32,7 @@ import (
"github.com/multica-ai/multica/server/internal/integrations/dingtalk"
"github.com/multica-ai/multica/server/internal/integrations/lark"
"github.com/multica-ai/multica/server/internal/integrations/slack"
+ "github.com/multica-ai/multica/server/internal/integrations/telegram"
"github.com/multica-ai/multica/server/internal/integrations/wecom"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/middleware"
@@ -946,6 +947,50 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
slog.Info("wecom integration disabled (MULTICA_WECOM_SECRET_KEY not set)")
}
+ // Telegram integration. Same shape as Slack: BYO bot token pasted at
+ // install, one getUpdates long-polling loop per active installation
+ // supervised by the shared engine.Supervisor, resolvers on the generic
+ // channel_* tables, outbound streaming via throttled editMessageText on
+ // the event bus. Gated by MULTICA_TELEGRAM_SECRET_KEY (the at-rest token
+ // encryption key); when unset the handlers return 503 and no Factory is
+ // registered.
+ if telegramKey, err := secretbox.LoadKey("MULTICA_TELEGRAM_SECRET_KEY"); err == nil {
+ box, err := secretbox.New(telegramKey)
+ if err != nil {
+ slog.Error("telegram: secretbox.New failed; telegram integration disabled", "error", err)
+ } else {
+ telegramBindingSvc := telegram.NewBindingTokenService(queries, pool)
+ h.TelegramBindingTokens = telegramBindingSvc
+ telegramReplier := telegram.NewOutboundReplier(telegram.OutboundReplierConfig{
+ Binding: telegramBindingSvc,
+ Decrypt: box.Open,
+ // The bind link (/telegram/bind) is a web-app page: app URL, not
+ // the API URL. Mirrors the Slack replier.
+ AppURL: appURLFromEnv(),
+ Logger: slog.Default(),
+ })
+ telegramTyping := telegram.NewTypingNotifier(box.Open, "", nil, slog.Default())
+ channelRouter.Register(telegram.TypeTelegram, telegram.NewTelegramResolverSet(queries, pool, telegramReplier, telegramTyping))
+ telegramOutbound := telegram.NewOutbound(queries, box.Open, "", nil, slog.Default())
+ telegramOutbound.Register(bus)
+ h.TelegramOutbound = telegramOutbound
+
+ // 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()})
+
+ installSvc, ierr := telegram.NewInstallService(queries, pool, box, slog.Default())
+ if ierr != nil {
+ slog.Error("telegram: InstallService init failed; install disabled", "error", ierr)
+ } else {
+ h.TelegramInstall = installSvc
+ }
+ slog.Info("telegram integration enabled (per-installation long polling)")
+ }
+ } else {
+ slog.Info("telegram integration disabled (MULTICA_TELEGRAM_SECRET_KEY not set)")
+ }
+
// Composio integration (MUL-3720). Gated by COMPOSIO_API_KEY plus the
// composio_mcp_apps feature flag. The env var is the project-scoped key the
// standalone SDK authenticates Composio with (sent as x-api-key; the project
@@ -1525,6 +1570,18 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/dingtalk/install/byo", h.RegisterDingTalkBYO)
r.Patch("/dingtalk/group-routes/{routeId}", h.UpdateDingTalkGroupRoute)
})
+
+ // Telegram integration. Same admin/member split as Slack:
+ // listing is member-visible; install + revoke are admin-only.
+ r.Group(func(r chi.Router) {
+ r.Use(middleware.RequireWorkspaceMemberFromURL(queries, "id"))
+ r.Get("/telegram/installations", h.ListTelegramInstallations)
+ })
+ r.Group(func(r chi.Router) {
+ r.Use(middleware.RequireWorkspaceRoleFromURL(queries, "id", "owner", "admin"))
+ r.Delete("/telegram/installations/{installationId}", h.RevokeTelegramInstallation)
+ r.Post("/telegram/install", h.RegisterTelegramBot)
+ })
})
})
@@ -1548,6 +1605,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// Lark/Slack: the session is the source of truth for the redeemer's
// Multica identity; the token only carries the WeCom userid to bind.
r.Post("/api/wecom/binding/redeem", h.RedeemWecomBindingToken)
+ // Telegram binding-token redemption. Same rationale: not
+ // workspace-scoped, identity from the session, token proves only
+ // "this Telegram user id requested binding".
+ r.Post("/api/telegram/binding/redeem", h.RedeemTelegramBindingToken)
// Composio integration (MUL-3720). User-scoped (no workspace context):
// a connection belongs to a user. These four require a logged-in
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index d53b63deab..c896af7bc1 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -29,6 +29,7 @@ import (
"github.com/multica-ai/multica/server/internal/integrations/ghsnapshot"
"github.com/multica-ai/multica/server/internal/integrations/lark"
"github.com/multica-ai/multica/server/internal/integrations/slack"
+ "github.com/multica-ai/multica/server/internal/integrations/telegram"
"github.com/multica-ai/multica/server/internal/integrations/wecom"
"github.com/multica-ai/multica/server/internal/issuestatus"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
@@ -304,6 +305,18 @@ type Handler struct {
// the install path runs without a socket.
WecomCredentialProbe wecom.CredentialProbe
+ // TelegramInstall owns the Telegram bot install lifecycle (register a
+ // pasted BotFather token / list / revoke) and the at-rest encryption of
+ // each bot's token. Nil unless MULTICA_TELEGRAM_SECRET_KEY is set.
+ TelegramInstall *telegram.InstallService
+ // TelegramBindingTokens mints/redeems the user-binding tokens behind the
+ // "link your Telegram account" prompt. Nil unless Telegram is configured.
+ TelegramBindingTokens *telegram.BindingTokenService
+ // TelegramOutbound owns the asynchronous terminal-delivery worker pool.
+ // The process owner starts and joins it; the synchronous event bus only
+ // enqueues EventChatDone work.
+ TelegramOutbound *telegram.Outbound
+
// channelFileDelivery names the channel types that can, IN THIS
// DEPLOYMENT, carry a file the agent produced the last hop into the
// conversation. It answers the claim response's
diff --git a/server/internal/handler/telegram.go b/server/internal/handler/telegram.go
new file mode 100644
index 0000000000..062e13fc78
--- /dev/null
+++ b/server/internal/handler/telegram.go
@@ -0,0 +1,265 @@
+package handler
+
+import (
+ "encoding/json"
+ "errors"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+
+ "github.com/multica-ai/multica/server/internal/integrations/telegram"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// TelegramInstallationResponse is the wire shape for a Telegram installation
+// row. The encrypted bot token in config is INTENTIONALLY absent — it is
+// server-internal. WS lease columns are runtime state, not API surface.
+type TelegramInstallationResponse struct {
+ ID string `json:"id"`
+ WorkspaceID string `json:"workspace_id"`
+ AgentID string `json:"agent_id"`
+ BotID string `json:"bot_id"`
+ BotUsername string `json:"bot_username"`
+ InstallerUserID string `json:"installer_user_id"`
+ Status string `json:"status"`
+ InstalledAt string `json:"installed_at"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
+}
+
+func telegramInstallationToResponse(row db.ChannelInstallation) TelegramInstallationResponse {
+ info := telegram.DecodePublicConfig(row.Config)
+ return TelegramInstallationResponse{
+ ID: uuidToString(row.ID),
+ WorkspaceID: uuidToString(row.WorkspaceID),
+ AgentID: uuidToString(row.AgentID),
+ BotID: info.BotID,
+ BotUsername: info.BotUsername,
+ InstallerUserID: uuidToString(row.InstallerUserID),
+ Status: row.Status,
+ InstalledAt: row.InstalledAt.Time.UTC().Format(time.RFC3339),
+ CreatedAt: row.CreatedAt.Time.UTC().Format(time.RFC3339),
+ UpdatedAt: row.UpdatedAt.Time.UTC().Format(time.RFC3339),
+ }
+}
+
+// ListTelegramInstallations (GET /api/workspaces/{id}/telegram/installations)
+// is member-visible so the Integrations tab renders for non-admins. Response
+// flags mirror Slack: configured = at-rest key set; install_supported is true
+// whenever configured (paste-a-token needs no hosted credential).
+func (h *Handler) ListTelegramInstallations(w http.ResponseWriter, r *http.Request) {
+ if h.TelegramInstall == nil {
+ writeJSON(w, http.StatusOK, map[string]any{
+ "installations": []TelegramInstallationResponse{},
+ "configured": false,
+ "install_supported": false,
+ })
+ return
+ }
+ wsUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")
+ if !ok {
+ return
+ }
+ rows, err := h.TelegramInstall.ListByWorkspace(r.Context(), wsUUID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list telegram installations")
+ return
+ }
+ out := make([]TelegramInstallationResponse, 0, len(rows))
+ for _, row := range rows {
+ out = append(out, telegramInstallationToResponse(row))
+ }
+ writeJSON(w, http.StatusOK, map[string]any{
+ "installations": out,
+ "configured": true,
+ "install_supported": true,
+ })
+}
+
+// RegisterTelegramRequest is the body for a bot install: the token the user
+// pasted from @BotFather.
+type RegisterTelegramRequest struct {
+ BotToken string `json:"bot_token"`
+}
+
+// RegisterTelegramBot (POST /api/workspaces/{id}/telegram/install?agent_id=…)
+// installs a user-supplied Telegram bot for an agent. Admin-only at the
+// router. Mirrors RegisterSlackBYO.
+func (h *Handler) RegisterTelegramBot(w http.ResponseWriter, r *http.Request) {
+ if h.TelegramInstall == nil {
+ writeError(w, http.StatusServiceUnavailable, "telegram integration not enabled")
+ return
+ }
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ wsUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")
+ if !ok {
+ return
+ }
+ agentIDStr := strings.TrimSpace(r.URL.Query().Get("agent_id"))
+ if agentIDStr == "" {
+ writeError(w, http.StatusBadRequest, "agent_id is required")
+ return
+ }
+ agentUUID, ok := parseUUIDOrBadRequest(w, agentIDStr, "agent_id")
+ if !ok {
+ return
+ }
+ // Ownership pre-check at the boundary so a wrong agent_id is a clear 404.
+ if _, err := h.Queries.GetAgentInWorkspace(r.Context(), db.GetAgentInWorkspaceParams{
+ ID: agentUUID,
+ WorkspaceID: wsUUID,
+ }); err != nil {
+ writeError(w, http.StatusNotFound, "agent not found in this workspace")
+ return
+ }
+ initiatorUUID, ok := parseUUIDOrBadRequest(w, userID, "user id")
+ if !ok {
+ return
+ }
+ var body RegisterTelegramRequest
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ row, err := h.TelegramInstall.Register(r.Context(), telegram.RegisterParams{
+ WorkspaceID: wsUUID,
+ AgentID: agentUUID,
+ InitiatorID: initiatorUUID,
+ BotToken: body.BotToken,
+ })
+ if err != nil {
+ switch {
+ case errors.Is(err, telegram.ErrInvalidBotToken):
+ writeError(w, http.StatusBadRequest, err.Error())
+ case errors.Is(err, telegram.ErrCredentialsRejected):
+ writeError(w, http.StatusBadRequest, "Telegram rejected this bot token — generate a current token in @BotFather and try again")
+ case errors.Is(err, telegram.ErrCredentialsUnverifiable):
+ writeError(w, http.StatusServiceUnavailable, "could not reach Telegram to verify this bot — check the server network or proxy and try again; the token was not saved")
+ case errors.Is(err, telegram.ErrBotOwnedBySameWorkspace):
+ writeError(w, http.StatusConflict, "this Telegram bot is already connected to another agent in this workspace — disconnect it there first, then connect it here")
+ case errors.Is(err, telegram.ErrBotOwnedByArchivedAgent):
+ writeError(w, http.StatusConflict, "this Telegram bot is connected to an archived agent in this workspace — restore that agent, or disconnect its bot, before connecting it here")
+ case errors.Is(err, telegram.ErrBotOwnedByAnotherWorkspace):
+ writeError(w, http.StatusConflict, "this Telegram bot is already connected to a different Multica workspace — disconnect it there before connecting it here")
+ case errors.Is(err, telegram.ErrWebhookConfigured):
+ writeError(w, http.StatusBadRequest, "this Telegram bot has a webhook configured — remove the webhook before connecting it with long polling")
+ default:
+ writeError(w, http.StatusInternalServerError, "could not save this Telegram bot — something went wrong on the server; the token was not saved")
+ }
+ return
+ }
+ // Broadcast so every open client invalidates its installations query and
+ // shows the new bot — matching the Slack install semantics.
+ h.publish(protocol.EventTelegramInstallationCreated, uuidToString(row.WorkspaceID), "user", userID, map[string]any{
+ "id": uuidToString(row.ID),
+ })
+ writeJSON(w, http.StatusOK, telegramInstallationToResponse(row))
+}
+
+// RevokeTelegramInstallation (DELETE /api/workspaces/{id}/telegram/installations/{installationId})
+// flips status to 'revoked'. Admin-only at the router. The row is preserved
+// for audit and chat history stays in Multica; a re-install (re-pasting the
+// bot's token) flips status back to 'active'.
+func (h *Handler) RevokeTelegramInstallation(w http.ResponseWriter, r *http.Request) {
+ if h.TelegramInstall == nil {
+ writeError(w, http.StatusServiceUnavailable, "telegram integration not configured")
+ return
+ }
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ wsUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")
+ if !ok {
+ return
+ }
+ instUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "installationId"), "installation id")
+ if !ok {
+ return
+ }
+ // Workspace-scoped lookup so one workspace cannot revoke another's
+ // installation by guessing the UUID.
+ if _, err := h.TelegramInstall.GetInWorkspace(r.Context(), instUUID, wsUUID); err != nil {
+ if errors.Is(err, telegram.ErrInstallationNotFound) {
+ writeError(w, http.StatusNotFound, "telegram installation not found")
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "failed to load installation")
+ return
+ }
+ if err := h.TelegramInstall.Revoke(r.Context(), instUUID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to revoke installation")
+ return
+ }
+ h.publish(protocol.EventTelegramInstallationRevoked, uuidToString(wsUUID), "user", userID, map[string]any{
+ "id": uuidToString(instUUID),
+ })
+ w.WriteHeader(http.StatusNoContent)
+}
+
+// RedeemTelegramBindingTokenRequest carries the raw token from the bot's
+// "link your account" prompt.
+type RedeemTelegramBindingTokenRequest struct {
+ Token string `json:"token"`
+}
+
+// RedeemTelegramBindingTokenResponse echoes the bound identifiers so the
+// frontend can confirm without a second fetch.
+type RedeemTelegramBindingTokenResponse struct {
+ WorkspaceID string `json:"workspace_id"`
+ InstallationID string `json:"installation_id"`
+ TelegramUserID string `json:"telegram_user_id"`
+}
+
+// RedeemTelegramBindingToken (POST /api/telegram/binding/redeem) binds the
+// Telegram user id carried by the token to the logged-in Multica user. The
+// redeemer's identity comes from the session, not the token. Status codes
+// mirror the Slack redeem handler.
+func (h *Handler) RedeemTelegramBindingToken(w http.ResponseWriter, r *http.Request) {
+ if h.TelegramBindingTokens == nil {
+ writeError(w, http.StatusServiceUnavailable, "telegram integration not configured")
+ return
+ }
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ var req RedeemTelegramBindingTokenRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ if req.Token == "" {
+ writeError(w, http.StatusBadRequest, "token is required")
+ return
+ }
+ userUUID, ok := parseUUIDOrBadRequest(w, userID, "user id")
+ if !ok {
+ return
+ }
+ redeemed, err := h.TelegramBindingTokens.RedeemAndBind(r.Context(), req.Token, userUUID)
+ if err != nil {
+ switch {
+ case errors.Is(err, telegram.ErrBindingTokenInvalid):
+ writeError(w, http.StatusGone, "binding token invalid or expired")
+ case errors.Is(err, telegram.ErrBindingAlreadyAssigned):
+ writeError(w, http.StatusConflict, "this Telegram account is already bound to a different Multica user")
+ case errors.Is(err, telegram.ErrBindingNotWorkspaceMember):
+ writeError(w, http.StatusForbidden, "binding refused (are you a workspace member?)")
+ default:
+ writeError(w, http.StatusInternalServerError, "failed to redeem token")
+ }
+ return
+ }
+ writeJSON(w, http.StatusOK, RedeemTelegramBindingTokenResponse{
+ WorkspaceID: uuidToString(redeemed.WorkspaceID),
+ InstallationID: uuidToString(redeemed.InstallationID),
+ TelegramUserID: redeemed.TelegramUserID,
+ })
+}
diff --git a/server/internal/handler/telegram_test.go b/server/internal/handler/telegram_test.go
new file mode 100644
index 0000000000..1145c15455
--- /dev/null
+++ b/server/internal/handler/telegram_test.go
@@ -0,0 +1,112 @@
+package handler
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func TestListTelegramInstallationsNotConfiguredReturnsEmpty(t *testing.T) {
+ h := &Handler{}
+ req := httptest.NewRequest(http.MethodGet, "/api/workspaces/x/telegram/installations", nil)
+ w := httptest.NewRecorder()
+
+ h.ListTelegramInstallations(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
+ }
+ var resp struct {
+ Installations []any `json:"installations"`
+ Configured bool `json:"configured"`
+ InstallSupported bool `json:"install_supported"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if resp.Configured || resp.InstallSupported || len(resp.Installations) != 0 {
+ t.Fatalf("unexpected unconfigured response: %+v", resp)
+ }
+}
+
+func TestTelegramMutationHandlersRejectUnconfiguredDeployment(t *testing.T) {
+ tests := []struct {
+ name string
+ method string
+ path string
+ body string
+ run func(*Handler, http.ResponseWriter, *http.Request)
+ }{
+ {
+ name: "register",
+ method: http.MethodPost,
+ path: "/api/workspaces/x/telegram/install?agent_id=y",
+ body: `{"bot_token":"placeholder"}`,
+ run: (*Handler).RegisterTelegramBot,
+ },
+ {
+ name: "revoke",
+ method: http.MethodDelete,
+ path: "/api/workspaces/x/telegram/installations/y",
+ run: (*Handler).RevokeTelegramInstallation,
+ },
+ {
+ name: "redeem binding",
+ method: http.MethodPost,
+ path: "/api/telegram/binding/redeem",
+ body: `{"token":"placeholder"}`,
+ run: (*Handler).RedeemTelegramBindingToken,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ h := &Handler{}
+ req := httptest.NewRequest(tt.method, tt.path, strings.NewReader(tt.body))
+ w := httptest.NewRecorder()
+
+ tt.run(h, w, req)
+
+ if w.Code != http.StatusServiceUnavailable {
+ t.Fatalf("expected 503, got %d body=%s", w.Code, w.Body.String())
+ }
+ })
+ }
+}
+
+func TestTelegramInstallationResponseNeverExposesStoredCredential(t *testing.T) {
+ now := time.Date(2026, 8, 14, 1, 0, 0, 0, time.UTC)
+ row := db.ChannelInstallation{
+ ID: parseUUID("11111111-1111-1111-1111-111111111111"),
+ WorkspaceID: parseUUID("22222222-2222-2222-2222-222222222222"),
+ AgentID: parseUUID("33333333-3333-3333-3333-333333333333"),
+ InstallerUserID: parseUUID("44444444-4444-4444-4444-444444444444"),
+ Status: "active",
+ Config: json.RawMessage(
+ `{"app_id":"123456789","bot_username":"my_test_bot","bot_token_encrypted":"ciphertext-sentinel"}`,
+ ),
+ InstalledAt: pgtype.Timestamptz{Time: now, Valid: true},
+ CreatedAt: pgtype.Timestamptz{Time: now, Valid: true},
+ UpdatedAt: pgtype.Timestamptz{Time: now, Valid: true},
+ }
+
+ got := telegramInstallationToResponse(row)
+ if got.BotID != "123456789" || got.BotUsername != "my_test_bot" {
+ t.Fatalf("public bot identity = %+v", got)
+ }
+ payload, err := json.Marshal(got)
+ if err != nil {
+ t.Fatalf("marshal response: %v", err)
+ }
+ if strings.Contains(string(payload), "ciphertext-sentinel") ||
+ strings.Contains(string(payload), "bot_token") {
+ t.Fatalf("management response exposed stored credential: %s", payload)
+ }
+}
diff --git a/server/internal/integrations/telegram/api.go b/server/internal/integrations/telegram/api.go
new file mode 100644
index 0000000000..a5dfc768ca
--- /dev/null
+++ b/server/internal/integrations/telegram/api.go
@@ -0,0 +1,304 @@
+package telegram
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "time"
+)
+
+// This file is the minimal Telegram Bot API surface the adapter needs:
+// getMe (install-time validation), getUpdates (inbound long polling),
+// sendMessage / editMessageText (outbound + streaming), sendChatAction
+// (typing indicator). It is a thin hand-rolled client over net/http — the
+// Bot API is plain JSON-over-HTTPS, so no SDK dependency is warranted.
+
+// defaultAPIBase is the production Bot API host. Tests point apiBase at an
+// httptest server.
+const defaultAPIBase = "https://api.telegram.org"
+
+// longPollTimeoutSecs is the getUpdates server-side hold. 50s stays under
+// common 60s proxy/LB idle timeouts while keeping the request count low.
+const longPollTimeoutSecs = 50
+
+// ErrConflict surfaces a 409 from getUpdates: the same bot token is being
+// polled by another consumer (a second Multica instance, another worktree, or
+// a foreign process). The polling loop treats it as fatal for the attempt and
+// reports a precise message so the operator sees "bot polled elsewhere"
+// instead of a silent message tug-of-war.
+var ErrConflict = errors.New("telegram: bot is already being polled by another instance (409 conflict)")
+
+// requestError deliberately omits the request URL from Error(). Bot API URLs
+// contain the bot token, while net/http transport errors can include that URL.
+// Unwrap preserves cancellation and transport classification without making
+// the credential loggable through the outer error string.
+type requestError struct {
+ method string
+ cause error
+}
+
+func (e *requestError) Error() string { return fmt.Sprintf("telegram: %s request failed", e.method) }
+
+func (e *requestError) Unwrap() error { return e.cause }
+
+// apiError is a non-OK Bot API response.
+type apiError struct {
+ Code int
+ Description string
+ // RetryAfter is Telegram's mandated backoff (seconds) on a 429.
+ RetryAfter int
+}
+
+func (e *apiError) Error() string {
+ return fmt.Sprintf("telegram api: %d %s", e.Code, e.Description)
+}
+
+// isRetryAfter reports the 429 backoff, if this error carries one.
+func retryAfter(err error) (time.Duration, bool) {
+ var ae *apiError
+ if errors.As(err, &ae) && ae.Code == http.StatusTooManyRequests {
+ secs := ae.RetryAfter
+ if secs <= 0 {
+ secs = 1
+ }
+ return time.Duration(secs) * time.Second, true
+ }
+ return 0, false
+}
+
+// botAPI is one bot's API client.
+type botAPI struct {
+ base string // API host, no trailing slash
+ token string
+ client *http.Client
+}
+
+func newBotAPI(base, token string, client *http.Client) *botAPI {
+ if base == "" {
+ base = defaultAPIBase
+ }
+ if client == nil {
+ client = &http.Client{Timeout: 65 * time.Second}
+ }
+ return &botAPI{base: base, token: token, client: client}
+}
+
+// envelope is the Bot API response wrapper.
+type envelope struct {
+ OK bool `json:"ok"`
+ Result json.RawMessage `json:"result"`
+ ErrorCode int `json:"error_code"`
+ Description string `json:"description"`
+ Parameters *struct {
+ RetryAfter int `json:"retry_after"`
+ } `json:"parameters"`
+}
+
+// call POSTs one Bot API method and decodes the result into out (skipped when
+// out is nil). API-level failures return *apiError; a 409 on getUpdates is
+// mapped by the caller.
+func (a *botAPI) call(ctx context.Context, method string, params any, out any) error {
+ var body io.Reader
+ if params != nil {
+ buf, err := json.Marshal(params)
+ if err != nil {
+ return fmt.Errorf("telegram: encode %s params: %w", method, err)
+ }
+ body = bytes.NewReader(buf)
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, a.base+"/bot"+a.token+"/"+method, body)
+ if err != nil {
+ return fmt.Errorf("telegram: build %s request: %w", method, err)
+ }
+ if params != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ resp, err := a.client.Do(req)
+ if err != nil {
+ return &requestError{method: method, cause: err}
+ }
+ defer resp.Body.Close()
+ var env envelope
+ if err := json.NewDecoder(resp.Body).Decode(&env); err != nil {
+ return fmt.Errorf("telegram: decode %s response (http %d): %w", method, resp.StatusCode, err)
+ }
+ if !env.OK {
+ ae := &apiError{Code: env.ErrorCode, Description: env.Description}
+ if env.Parameters != nil {
+ ae.RetryAfter = env.Parameters.RetryAfter
+ }
+ return ae
+ }
+ if out != nil {
+ if err := json.Unmarshal(env.Result, out); err != nil {
+ return fmt.Errorf("telegram: decode %s result: %w", method, err)
+ }
+ }
+ return nil
+}
+
+// User is the Bot API User object (getMe result / message sender).
+type User struct {
+ ID int64 `json:"id"`
+ IsBot bool `json:"is_bot"`
+ FirstName string `json:"first_name"`
+ LastName string `json:"last_name,omitempty"`
+ Username string `json:"username,omitempty"`
+}
+
+// Chat is the Bot API Chat object.
+type Chat struct {
+ ID int64 `json:"id"`
+ Type string `json:"type"` // "private", "group", "supergroup", "channel"
+}
+
+// Message is the subset of the Bot API Message object the adapter reads.
+type Message struct {
+ MessageID int64 `json:"message_id"`
+ From *User `json:"from"`
+ Chat Chat `json:"chat"`
+ Date int64 `json:"date"`
+ Text string `json:"text"`
+ Entities []MessageEntity `json:"entities,omitempty"`
+ Caption string `json:"caption,omitempty"`
+ CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
+ ReplyToMessage *Message `json:"reply_to_message,omitempty"`
+ MessageThreadID int64 `json:"message_thread_id,omitempty"`
+ IsTopicMessage bool `json:"is_topic_message,omitempty"`
+ Photo []any `json:"photo,omitempty"`
+ Document *struct {
+ FileName string `json:"file_name"`
+ } `json:"document,omitempty"`
+ Voice *struct{} `json:"voice,omitempty"`
+ Video *struct{} `json:"video,omitempty"`
+ Sticker *struct{} `json:"sticker,omitempty"`
+}
+
+// MessageEntity is the Bot API's structured annotation for mentions,
+// commands, links, and formatting. Offset and Length are UTF-16 code units,
+// not UTF-8 byte offsets or Go rune indexes.
+type MessageEntity struct {
+ Type string `json:"type"`
+ Offset int `json:"offset"`
+ Length int `json:"length"`
+}
+
+// Update is the getUpdates envelope entry. Only new messages are consumed;
+// edits, channel posts, and callback queries are ignored in v1.
+type Update struct {
+ UpdateID int64 `json:"update_id"`
+ Message *Message `json:"message"`
+}
+
+// GetMe validates the token and returns the bot's own identity.
+func (a *botAPI) GetMe(ctx context.Context) (User, error) {
+ var u User
+ err := a.call(ctx, "getMe", nil, &u)
+ return u, err
+}
+
+// WebhookInfo is the subset of the Bot API webhook status needed before
+// starting a long-polling installation.
+type WebhookInfo struct {
+ URL string `json:"url"`
+ PendingUpdateCount int `json:"pending_update_count"`
+}
+
+// GetWebhookInfo detects a webhook that would make getUpdates unavailable.
+func (a *botAPI) GetWebhookInfo(ctx context.Context) (WebhookInfo, error) {
+ var info WebhookInfo
+ err := a.call(ctx, "getWebhookInfo", nil, &info)
+ return info, err
+}
+
+type getUpdatesParams struct {
+ Offset int64 `json:"offset,omitempty"`
+ Timeout int `json:"timeout"`
+ AllowedUpdates []string `json:"allowed_updates"`
+}
+
+// GetUpdates long-polls for new updates. A 409 is translated to ErrConflict.
+func (a *botAPI) GetUpdates(ctx context.Context, offset int64) ([]Update, error) {
+ var updates []Update
+ err := a.call(ctx, "getUpdates", getUpdatesParams{
+ Offset: offset,
+ Timeout: longPollTimeoutSecs,
+ // Restrict the stream to plain messages: fewer wakeups, and edits /
+ // reactions / channel posts never enter the pipeline.
+ AllowedUpdates: []string{"message"},
+ }, &updates)
+ if err != nil {
+ var ae *apiError
+ if errors.As(err, &ae) && ae.Code == http.StatusConflict {
+ return nil, ErrConflict
+ }
+ return nil, err
+ }
+ return updates, nil
+}
+
+type sendMessageParams struct {
+ ChatID int64 `json:"chat_id"`
+ Text string `json:"text"`
+ ParseMode string `json:"parse_mode,omitempty"`
+ MessageThreadID int64 `json:"message_thread_id,omitempty"`
+ ReplyParameters *replyParameters `json:"reply_parameters,omitempty"`
+}
+
+// replyParameters is Telegram's current quote-reply shape. The legacy
+// reply_to_message_id field is no longer part of sendMessage.
+type replyParameters struct {
+ MessageID int64 `json:"message_id"`
+ AllowSendingWithoutReply bool `json:"allow_sending_without_reply,omitempty"`
+}
+
+// SendMessage posts a message. HTML parse mode is used by callers that send
+// converted markdown; plain calls leave parseMode empty.
+func (a *botAPI) SendMessage(ctx context.Context, p sendMessageParams) (Message, error) {
+ var m Message
+ err := a.call(ctx, "sendMessage", p, &m)
+ return m, err
+}
+
+// sendMessageWithRetryAfter honors Telegram's explicit 429 backoff once. It
+// deliberately does not retry transport or other API errors because a lost
+// response can mean Telegram already accepted the message.
+func sendMessageWithRetryAfter(ctx context.Context, a *botAPI, p sendMessageParams) (Message, error) {
+ m, err := a.SendMessage(ctx, p)
+ if wait, ok := retryAfter(err); ok {
+ if !sleepCtx(ctx, wait) {
+ return Message{}, ctx.Err()
+ }
+ return a.SendMessage(ctx, p)
+ }
+ return m, err
+}
+
+type editMessageTextParams struct {
+ ChatID int64 `json:"chat_id"`
+ MessageID int64 `json:"message_id"`
+ Text string `json:"text"`
+ ParseMode string `json:"parse_mode,omitempty"`
+}
+
+// EditMessageText replaces a previously sent message's text — the streaming
+// primitive. "message is not modified" errors are swallowed by the caller.
+func (a *botAPI) EditMessageText(ctx context.Context, p editMessageTextParams) error {
+ return a.call(ctx, "editMessageText", p, nil)
+}
+
+// SendChatAction shows the native "typing…" indicator for ~5s in the same
+// forum topic as the triggering message, when applicable.
+func (a *botAPI) SendChatAction(ctx context.Context, chatID, messageThreadID int64) error {
+ return a.call(ctx, "sendChatAction", struct {
+ ChatID int64 `json:"chat_id"`
+ Action string `json:"action"`
+ MessageThreadID int64 `json:"message_thread_id,omitempty"`
+ }{
+ ChatID: chatID, Action: "typing", MessageThreadID: messageThreadID,
+ }, nil)
+}
diff --git a/server/internal/integrations/telegram/binding.go b/server/internal/integrations/telegram/binding.go
new file mode 100644
index 0000000000..ee7cce1917
--- /dev/null
+++ b/server/internal/integrations/telegram/binding.go
@@ -0,0 +1,171 @@
+package telegram
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// This file is the Telegram user-binding token flow, mirroring
+// slack/binding.go on the generic channel_* queries with
+// channel_type='telegram': an unbound Telegram user who messages the bot gets
+// a "link your account" prompt, clicks through to the in-product redeem page,
+// and their Telegram user id is bound to their Multica account.
+
+// BindingTokenTTL bounds a token's life; the channel_binding_token CHECK
+// enforces the same 15-minute cap.
+const BindingTokenTTL = 15 * time.Minute
+
+var (
+ // ErrBindingTokenInvalid: token unknown / already consumed / expired. One
+ // opaque error avoids a replay timing oracle.
+ ErrBindingTokenInvalid = errors.New("telegram: binding token invalid or expired")
+ // ErrBindingAlreadyAssigned: this Telegram user id is already bound to a
+ // different Multica user.
+ ErrBindingAlreadyAssigned = errors.New("telegram: user id is already bound to a different user")
+ // ErrBindingNotWorkspaceMember: the redeemer is not a member of the token's
+ // workspace.
+ ErrBindingNotWorkspaceMember = errors.New("telegram: redeemer is not a workspace member")
+)
+
+// BindingToken is a freshly minted token; the raw value is returned exactly
+// once, only its hash is persisted.
+type BindingToken struct {
+ Raw string
+ ExpiresAt time.Time
+}
+
+// RedeemedBindingToken is returned after a successful redemption.
+type RedeemedBindingToken struct {
+ WorkspaceID pgtype.UUID
+ InstallationID pgtype.UUID
+ TelegramUserID string
+}
+
+// BindingTokenService mints and redeems Telegram binding tokens. Redemption
+// is transactional: consuming the token and inserting the binding row commit
+// together, so a failed bind never burns a token.
+type BindingTokenService struct {
+ q *db.Queries
+ tx engine.TxStarter
+ now func() time.Time
+}
+
+// NewBindingTokenService constructs the service.
+func NewBindingTokenService(q *db.Queries, tx engine.TxStarter) *BindingTokenService {
+ return &BindingTokenService{q: q, tx: tx, now: time.Now}
+}
+
+// Mint creates a single-use binding token for (installation, telegramUserID).
+func (s *BindingTokenService) Mint(ctx context.Context, workspaceID, installationID pgtype.UUID, telegramUserID string) (BindingToken, error) {
+ raw, err := randomBindingToken(32)
+ if err != nil {
+ return BindingToken{}, fmt.Errorf("generate token: %w", err)
+ }
+ expiresAt := s.now().Add(BindingTokenTTL)
+ if _, err := s.q.CreateChannelBindingToken(ctx, db.CreateChannelBindingTokenParams{
+ TokenHash: hashBindingToken(raw),
+ WorkspaceID: workspaceID,
+ InstallationID: installationID,
+ ChannelType: string(TypeTelegram),
+ ChannelUserID: telegramUserID,
+ ExpiresAt: pgtype.Timestamptz{Time: expiresAt, Valid: true},
+ }); err != nil {
+ return BindingToken{}, fmt.Errorf("persist token: %w", err)
+ }
+ return BindingToken{Raw: raw, ExpiresAt: expiresAt}, nil
+}
+
+// RedeemAndBind atomically consumes a raw token and binds the Telegram user
+// id to multicaUserID (taken from the session, never from the token).
+func (s *BindingTokenService) RedeemAndBind(ctx context.Context, raw string, multicaUserID pgtype.UUID) (RedeemedBindingToken, error) {
+ if s.tx == nil {
+ return RedeemedBindingToken{}, errors.New("telegram: BindingTokenService missing TxStarter")
+ }
+ tx, err := s.tx.Begin(ctx)
+ if err != nil {
+ return RedeemedBindingToken{}, fmt.Errorf("begin tx: %w", err)
+ }
+ defer func() { _ = tx.Rollback(ctx) }()
+ qtx := s.q.WithTx(tx)
+
+ row, err := qtx.ConsumeChannelBindingToken(ctx, hashBindingToken(raw))
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return RedeemedBindingToken{}, ErrBindingTokenInvalid
+ }
+ return RedeemedBindingToken{}, fmt.Errorf("consume token: %w", err)
+ }
+ if err := validateBindingTokenChannel(row); err != nil {
+ // The token table is shared across channel adapters. Keep a token from
+ // another adapter from being redeemed through Telegram; returning here
+ // rolls the consume back with the surrounding transaction.
+ return RedeemedBindingToken{}, err
+ }
+
+ // Explicit membership gate (no member FK): returning before Commit rolls
+ // the consume back, so a non-member's attempt does not burn the token.
+ if _, err := qtx.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
+ UserID: multicaUserID,
+ WorkspaceID: row.WorkspaceID,
+ }); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return RedeemedBindingToken{}, ErrBindingNotWorkspaceMember
+ }
+ return RedeemedBindingToken{}, fmt.Errorf("check membership: %w", err)
+ }
+
+ if _, err := qtx.CreateChannelUserBinding(ctx, db.CreateChannelUserBindingParams{
+ WorkspaceID: row.WorkspaceID,
+ MulticaUserID: multicaUserID,
+ InstallationID: row.InstallationID,
+ ChannelType: string(TypeTelegram),
+ ChannelUserID: row.ChannelUserID,
+ Config: []byte(`{}`),
+ }); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return RedeemedBindingToken{}, ErrBindingAlreadyAssigned
+ }
+ return RedeemedBindingToken{}, fmt.Errorf("create binding: %w", err)
+ }
+
+ if err := tx.Commit(ctx); err != nil {
+ return RedeemedBindingToken{}, fmt.Errorf("commit: %w", err)
+ }
+ return RedeemedBindingToken{
+ WorkspaceID: row.WorkspaceID,
+ InstallationID: row.InstallationID,
+ TelegramUserID: row.ChannelUserID,
+ }, nil
+}
+
+func validateBindingTokenChannel(row db.ChannelBindingToken) error {
+ if row.ChannelType != string(TypeTelegram) {
+ return ErrBindingTokenInvalid
+ }
+ return nil
+}
+
+func randomBindingToken(n int) (string, error) {
+ buf := make([]byte, n)
+ if _, err := rand.Read(buf); err != nil {
+ return "", err
+ }
+ return base64.RawURLEncoding.EncodeToString(buf), nil
+}
+
+func hashBindingToken(raw string) string {
+ sum := sha256.Sum256([]byte(raw))
+ return hex.EncodeToString(sum[:])
+}
diff --git a/server/internal/integrations/telegram/binding_test.go b/server/internal/integrations/telegram/binding_test.go
new file mode 100644
index 0000000000..9a8772a97d
--- /dev/null
+++ b/server/internal/integrations/telegram/binding_test.go
@@ -0,0 +1,62 @@
+package telegram
+
+import (
+ "context"
+ "errors"
+ "regexp"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+func TestRandomBindingTokenIsUniqueAndURLSafe(t *testing.T) {
+ first, err := randomBindingToken(32)
+ if err != nil {
+ t.Fatalf("first token: %v", err)
+ }
+ second, err := randomBindingToken(32)
+ if err != nil {
+ t.Fatalf("second token: %v", err)
+ }
+ if first == second {
+ t.Fatal("two random binding tokens were identical")
+ }
+ if ok := regexp.MustCompile(`^[A-Za-z0-9_-]+$`).MatchString(first); !ok {
+ t.Fatalf("token is not raw URL-safe base64: %q", first)
+ }
+}
+
+func TestHashBindingTokenIsDeterministicAndDoesNotRetainRawValue(t *testing.T) {
+ const raw = "binding-token-sentinel"
+ first := hashBindingToken(raw)
+ second := hashBindingToken(raw)
+ if first != second {
+ t.Fatalf("hash changed between calls: %q != %q", first, second)
+ }
+ if first == raw || len(first) != 64 {
+ t.Fatalf("unexpected SHA-256 representation: %q", first)
+ }
+}
+
+func TestRedeemAndBindRequiresTransactionStarter(t *testing.T) {
+ service := &BindingTokenService{}
+ _, err := service.RedeemAndBind(context.Background(), "token", pgtype.UUID{})
+ if err == nil || err.Error() != "telegram: BindingTokenService missing TxStarter" {
+ t.Fatalf("error = %v", err)
+ }
+}
+
+func TestBindingErrorSentinelsRemainDistinct(t *testing.T) {
+ errs := []error{
+ ErrBindingTokenInvalid,
+ ErrBindingAlreadyAssigned,
+ ErrBindingNotWorkspaceMember,
+ }
+ for i := range errs {
+ for j := range errs {
+ if i != j && errors.Is(errs[i], errs[j]) {
+ t.Fatalf("binding errors %v and %v overlap", errs[i], errs[j])
+ }
+ }
+ }
+}
diff --git a/server/internal/integrations/telegram/config.go b/server/internal/integrations/telegram/config.go
new file mode 100644
index 0000000000..a1b62aaf90
--- /dev/null
+++ b/server/internal/integrations/telegram/config.go
@@ -0,0 +1,158 @@
+// Package telegram is the Telegram integration for the channel-agnostic
+// engine. It follows the Slack BYO model: the workspace admin creates a bot
+// via @BotFather, pastes its bot token into Multica, and the installation is
+// keyed by the bot's numeric id (the token prefix). Inbound runs on a
+// per-installation getUpdates long-polling loop (telegram_channel.go) —
+// Telegram offers no WebSocket transport, and long polling is the deployment
+// model that needs no public HTTPS endpoint, matching the Feishu/Slack
+// "persistent per-installation connection supervised by engine.Supervisor"
+// shape. Outbound agent replies stream via throttled editMessageText
+// (outbound.go); verdict replies (binding prompt, offline notice) live in
+// replier.go.
+//
+// Maintenance: this package is COMMUNITY-MAINTAINED. @leonzone contributed it
+// and is its code owner — the first stop for Telegram-specific bugs and behavior
+// questions, on a best-effort volunteer basis. The Multica team keeps this
+// package compiling and its tests green through shared-layer refactors, but
+// does not use Telegram and cannot verify behavior against the real platform;
+// that part depends on the code owner. If the integration breaks in a way that
+// cannot be fixed without real Telegram access and no fix lands for a few
+// releases, it may be deprecated rather than left quietly broken. Changing the
+// shared channel engine? Keep this adapter building — and loop in the code
+// owner for anything that changes Telegram-visible behavior.
+package telegram
+
+import (
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+)
+
+// TypeTelegram is the channel discriminator for the Telegram adapter. Defined
+// here (not in the channel core) so registering the platform never edits the
+// core, mirroring TypeSlack.
+const TypeTelegram channel.Type = "telegram"
+
+// installConfig is the JSON shape stored in channel_installation.config for a
+// Telegram installation.
+//
+// app_id holds the bot's numeric id as a string (parsed from the token's
+// "<id>:<secret>" prefix). It fills the generic (channel_type, config->>'app_id')
+// routing slot; inbound needs no per-event routing lookup (each polling loop
+// serves exactly one installation), but the unique index still guarantees one
+// bot maps to one agent across all workspaces.
+//
+// bot_token_encrypted is base64-encoded secretbox ciphertext, never plaintext,
+// mirroring Slack's bot_token_encrypted and Feishu's app_secret_encrypted.
+type installConfig struct {
+ AppID string `json:"app_id"`
+ BotUsername string `json:"bot_username,omitempty"`
+ BotTokenEncrypted string `json:"bot_token_encrypted"`
+}
+
+// credentials is the decoded, decrypted form the transports run on. The
+// installation identity (workspace / agent / installer) is deliberately
+// absent: it is resolved per message by the Router, as in Feishu and Slack.
+type credentials struct {
+ BotID string
+ BotUsername string
+ BotToken string
+}
+
+// Decrypter turns stored ciphertext into plaintext. The wiring injects a
+// secretbox-backed implementation; tests inject nil (stored bytes are treated
+// as plaintext).
+type Decrypter func(ciphertext []byte) (plaintext []byte, err error)
+
+// decodeCredentials parses the per-installation config blob and decrypts the
+// stored bot token. It is the single place the Telegram config JSON is
+// interpreted.
+func decodeCredentials(raw json.RawMessage, decrypt Decrypter) (credentials, error) {
+ if len(raw) == 0 {
+ return credentials{}, errors.New("telegram: empty installation config")
+ }
+ var cfg installConfig
+ if err := json.Unmarshal(raw, &cfg); err != nil {
+ return credentials{}, fmt.Errorf("decode telegram installation config: %w", err)
+ }
+ token, err := decryptToken(cfg.BotTokenEncrypted, decrypt)
+ if err != nil {
+ return credentials{}, fmt.Errorf("decrypt bot token: %w", err)
+ }
+ return credentials{
+ BotID: cfg.AppID,
+ BotUsername: cfg.BotUsername,
+ BotToken: token,
+ }, nil
+}
+
+// PublicConfig is the non-secret subset of an installation config, safe to
+// surface on the management API (the encrypted bot token is never included).
+type PublicConfig struct {
+ BotID string
+ BotUsername string
+}
+
+// DecodePublicConfig extracts the display-safe fields from a stored config
+// blob. A decode miss yields a zero PublicConfig rather than an error so the
+// management list still renders the row.
+func DecodePublicConfig(raw json.RawMessage) PublicConfig {
+ var cfg installConfig
+ _ = json.Unmarshal(raw, &cfg)
+ return PublicConfig{BotID: cfg.AppID, BotUsername: cfg.BotUsername}
+}
+
+// decryptToken base64-decodes the stored ciphertext (tolerating MIME newline
+// wrapping) and runs it through the injected Decrypter; mirrors the Slack
+// helper of the same name.
+func decryptToken(enc string, decrypt Decrypter) (string, error) {
+ if enc == "" {
+ return "", nil
+ }
+ ciphertext, err := base64.StdEncoding.DecodeString(stripWhitespace(enc))
+ if err != nil {
+ return "", fmt.Errorf("base64 decode: %w", err)
+ }
+ if decrypt == nil {
+ return string(ciphertext), nil
+ }
+ plaintext, err := decrypt(ciphertext)
+ if err != nil {
+ return "", err
+ }
+ return string(plaintext), nil
+}
+
+func stripWhitespace(s string) string {
+ var b strings.Builder
+ b.Grow(len(s))
+ for _, r := range s {
+ switch r {
+ case ' ', '\t', '\n', '\r':
+ continue
+ default:
+ b.WriteRune(r)
+ }
+ }
+ return b.String()
+}
+
+// parseBotID extracts the bot's numeric id from a bot token. BotFather tokens
+// are "<numeric id>:<secret>"; the id part is the stable per-bot identity used
+// as the installation routing key (config->>'app_id').
+func parseBotID(token string) (string, error) {
+ id, secret, ok := strings.Cut(strings.TrimSpace(token), ":")
+ if !ok || id == "" || secret == "" {
+ return "", ErrInvalidBotToken
+ }
+ for _, r := range id {
+ if r < '0' || r > '9' {
+ return "", ErrInvalidBotToken
+ }
+ }
+ return id, nil
+}
diff --git a/server/internal/integrations/telegram/inbound.go b/server/internal/integrations/telegram/inbound.go
new file mode 100644
index 0000000000..430715290f
--- /dev/null
+++ b/server/internal/integrations/telegram/inbound.go
@@ -0,0 +1,304 @@
+package telegram
+
+import (
+ "encoding/json"
+ "fmt"
+ "strconv"
+ "strings"
+ "unicode/utf16"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+)
+
+// This file holds the translation from a Telegram Update to the engine's
+// normalized channel.InboundMessage. Free functions parameterized by the bot
+// identity, mirroring slack/inbound.go, so the per-installation polling loop
+// threads in its own bot's id and username.
+
+// telegramRawEvent carries the Telegram-specific fields the cross-platform
+// envelope does not — read back only inside the Telegram resolvers.
+type telegramRawEvent struct {
+ // BotID routes the message to its installation (config->>'app_id').
+ BotID string `json:"bot_id"`
+ // EventType is a coarse label for drop audits ("message").
+ EventType string `json:"event_type"`
+ // SenderName is the sender's Telegram display name, carried for
+ // group-context attribution.
+ 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).
+//
+// 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) {
+ m := u.Message
+ if m == nil || m.From == nil || m.From.IsBot || m.From.ID == botID {
+ return channel.InboundMessage{}, false
+ }
+ chatType, ok := telegramChatType(m.Chat.Type)
+ if !ok {
+ return channel.InboundMessage{}, false
+ }
+
+ text := m.Text
+ if text == "" {
+ text = m.Caption
+ }
+ msgType := classifyMessage(m)
+
+ mentioned := mentionsBot(m, botUsername)
+ repliedToBot := m.ReplyToMessage != nil && m.ReplyToMessage.From != nil && m.ReplyToMessage.From.ID == botID
+ addressed := chatType == channel.ChatTypeP2P || mentioned || repliedToBot
+
+ cleaned := normalizeText(text, botUsername)
+ commandText := cleaned
+ forceFresh := false
+ if body, fresh := engine.ParseFreshSessionCommand(cleaned); fresh {
+ cleaned = body
+ forceFresh = true
+ }
+ agentText := cleaned
+ quotedHuman := m.ReplyToMessage != nil && m.ReplyToMessage.From != nil && !m.ReplyToMessage.From.IsBot
+ if chatType == channel.ChatTypeGroup && mentioned && quotedHuman {
+ agentText = enrichWithQuotedHumanMessage(cleaned, m.Chat.ID, m.ReplyToMessage)
+ }
+
+ senderID := strconv.FormatInt(m.From.ID, 10)
+ chatID := strconv.FormatInt(m.Chat.ID, 10)
+ threadID := ""
+ if m.IsTopicMessage && m.MessageThreadID != 0 {
+ threadID = strconv.FormatInt(m.MessageThreadID, 10)
+ }
+
+ raw, _ := json.Marshal(telegramRawEvent{
+ BotID: strconv.FormatInt(botID, 10),
+ EventType: "message",
+ SenderName: senderDisplayName(m.From),
+ })
+
+ var reply *channel.ReplyCtx
+ if m.ReplyToMessage != nil {
+ reply = &channel.ReplyCtx{
+ MessageID: messageKey(m.Chat.ID, m.ReplyToMessage.MessageID),
+ RootID: threadID,
+ }
+ }
+
+ return channel.InboundMessage{
+ EventID: strconv.FormatInt(u.UpdateID, 10),
+ // Telegram message ids are only unique per chat, so the dedup key
+ // (installation, message_id) uses the composite chat:message form.
+ MessageID: messageKey(m.Chat.ID, m.MessageID),
+ Type: msgType,
+ Text: agentText,
+ CommandText: commandText,
+ ReplyTo: reply,
+ AddressedToBot: addressed,
+ ForceFresh: forceFresh,
+ Source: channel.Source{
+ ChannelType: TypeTelegram,
+ ChatID: chatID,
+ ChatType: chatType,
+ SenderID: senderID,
+ // Telegram user ids are global, so the per-installation id doubles as
+ // the cross-installation stable id.
+ SenderStableID: senderID,
+ ThreadID: threadID,
+ },
+ Raw: raw,
+ }, true
+}
+
+// messageKey builds the per-installation-unique message id "chat:message".
+func messageKey(chatID, messageID int64) string {
+ return strconv.FormatInt(chatID, 10) + ":" + strconv.FormatInt(messageID, 10)
+}
+
+// telegramChatType maps Telegram's chat.type. Channel posts (broadcast
+// channels, no interactive sender context) are not ingested.
+func telegramChatType(t string) (channel.ChatType, bool) {
+ switch t {
+ case "private":
+ return channel.ChatTypeP2P, true
+ case "group", "supergroup":
+ return channel.ChatTypeGroup, true
+ default:
+ return "", false
+ }
+}
+
+// classifyMessage maps the message payload to the normalized MsgType. Only
+// text is actionable in v1 (aligned with Feishu/Slack); media kinds are
+// reported so the caller can reply "unsupported" rather than stay silent.
+func classifyMessage(m *Message) channel.MsgType {
+ switch {
+ case m.Text != "":
+ return channel.MsgTypeText
+ case len(m.Photo) > 0:
+ return channel.MsgTypeImage
+ case m.Voice != nil:
+ return channel.MsgTypeAudio
+ case m.Video != nil:
+ return channel.MsgTypeVideo
+ case m.Document != nil:
+ return channel.MsgTypeFile
+ default:
+ return channel.MsgTypeUnknown
+ }
+}
+
+// mentionsBot reports whether the message text contains "@botusername".
+// Telegram marks mentions with entities, but matching the literal token is
+// equivalent for bot usernames (they are globally unique and always start
+// with "@" in text) and keeps the check entity-order independent.
+func mentionsBot(m *Message, botUsername string) bool {
+ if botUsername == "" {
+ return false
+ }
+ wantMention := "@" + botUsername
+ for _, source := range []struct {
+ text string
+ entities []MessageEntity
+ }{
+ {text: m.Text, entities: m.Entities},
+ {text: m.Caption, entities: m.CaptionEntities},
+ } {
+ for _, entity := range source.entities {
+ if entity.Type != "mention" && entity.Type != "bot_command" {
+ continue
+ }
+ value, ok := messageEntityText(source.text, entity)
+ if !ok {
+ continue
+ }
+ if strings.EqualFold(value, wantMention) || commandTargetsBot(value, botUsername) {
+ return true
+ }
+ }
+ }
+ // Telegram normally supplies entities. Keep a boundary-aware fallback for
+ // old fixtures and defensive compatibility with incomplete gateways.
+ return containsBotMention(m.Text, botUsername) || containsBotMention(m.Caption, botUsername)
+}
+
+// normalizeText strips the bot mention token while retaining shared commands
+// such as /new and /issue for the engine's command parser.
+func normalizeText(text, botUsername string) string {
+ cleaned := text
+ if botUsername != "" {
+ cleaned = removeBotMentions(cleaned, botUsername)
+ }
+ return strings.TrimSpace(cleaned)
+}
+
+// enrichWithQuotedHumanMessage prepends only the message a group member
+// explicitly selected by replying and mentioning the bot. Ambient group
+// history never enters the agent context. CommandText remains the sender's own
+// cleaned instruction so commands inside the quoted message stay historical.
+func enrichWithQuotedHumanMessage(instruction string, chatID int64, quoted *Message) string {
+ quotedText := quoted.Text
+ if quotedText == "" {
+ quotedText = quoted.Caption
+ }
+ if strings.TrimSpace(quotedText) == "" {
+ quotedText = "[empty or non-text message]"
+ }
+ sender := "Unknown user"
+ if quoted.From != nil {
+ if name := senderDisplayName(quoted.From); name != "" {
+ sender = name
+ }
+ }
+ msgType := classifyMessage(quoted)
+ block := fmt.Sprintf("<quoted_message message_id=%q sender=%q type=%q>\n%s\n</quoted_message>",
+ messageKey(chatID, quoted.MessageID), sender, msgType, quotedText)
+ 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)
+}
+
+func messageEntityText(text string, entity MessageEntity) (string, bool) {
+ if entity.Offset < 0 || entity.Length <= 0 {
+ return "", false
+ }
+ units := utf16.Encode([]rune(text))
+ end := entity.Offset + entity.Length
+ if entity.Offset > len(units) || end < entity.Offset || end > len(units) {
+ return "", false
+ }
+ return string(utf16.Decode(units[entity.Offset:end])), true
+}
+
+func containsBotMention(text, botUsername string) bool {
+ token := "@" + strings.ToLower(botUsername)
+ lower := strings.ToLower(text)
+ for start := 0; ; {
+ i := strings.Index(lower[start:], token)
+ if i < 0 {
+ return false
+ }
+ i += start
+ end := i + len(token)
+ if end == len(lower) || !isTelegramUsernameByte(lower[end]) {
+ return true
+ }
+ start = end
+ }
+}
+
+func removeBotMentions(text, botUsername string) string {
+ token := "@" + strings.ToLower(botUsername)
+ lower := strings.ToLower(text)
+ var out strings.Builder
+ for start := 0; start < len(text); {
+ i := strings.Index(lower[start:], token)
+ if i < 0 {
+ out.WriteString(text[start:])
+ break
+ }
+ i += start
+ end := i + len(token)
+ if end < len(lower) && isTelegramUsernameByte(lower[end]) {
+ out.WriteString(text[start:end])
+ start = end
+ continue
+ }
+ out.WriteString(text[start:i])
+ start = end
+ }
+ return out.String()
+}
+
+func isTelegramUsernameByte(b byte) bool {
+ return b == '_' || b >= 'a' && b <= 'z' || b >= '0' && b <= '9'
+}
+
+func containsFold(s, sub string) bool {
+ return strings.Contains(strings.ToLower(s), strings.ToLower(sub))
+}
+
+// senderDisplayName renders "First Last" or the username as fallback.
+func senderDisplayName(u *User) string {
+ name := strings.TrimSpace(u.FirstName + " " + u.LastName)
+ if name != "" {
+ return name
+ }
+ return u.Username
+}
+
+// containsFold is a case-insensitive strings.Contains (bot usernames are
+// case-insensitive on Telegram).
diff --git a/server/internal/integrations/telegram/install.go b/server/internal/integrations/telegram/install.go
new file mode 100644
index 0000000000..d28fbce639
--- /dev/null
+++ b/server/internal/integrations/telegram/install.go
@@ -0,0 +1,303 @@
+package telegram
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgconn"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/internal/util/secretbox"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// This file is the Telegram install backend, mirroring slack/install.go +
+// byo_install.go: the workspace admin creates a bot via @BotFather and pastes
+// its token into Multica. The InstallService owns the at-rest encryption of
+// the token — no caller can write a channel_installation with a plaintext
+// token — plus the shared persist transaction and the list / get / revoke
+// management surface.
+
+var (
+ // ErrInstallationNotFound surfaces "no row matches in this workspace".
+ ErrInstallationNotFound = errors.New("telegram installation not found")
+ // ErrInvalidBotToken is returned when the pasted token is malformed
+ // ("<numeric id>:<secret>") — mapped to 400 by the handler.
+ ErrInvalidBotToken = errors.New("telegram: bot token must look like 123456:ABC-DEF…")
+ // ErrCredentialsRejected means Telegram itself rejected the token. Keep it
+ // distinct from an unreachable API so users are never told to rotate a
+ // valid credential because the deployment's proxy or network is down.
+ ErrCredentialsRejected = errors.New("telegram: Telegram rejected this bot token")
+ // ErrCredentialsUnverifiable means Multica could not complete the live
+ // Telegram check. The token has not been persisted or changed.
+ ErrCredentialsUnverifiable = errors.New("telegram: could not reach Telegram to verify this bot")
+ // ErrBotOwnedByAnotherWorkspace: the pasted bot is already connected to a
+ // live owner in a DIFFERENT Multica workspace.
+ ErrBotOwnedByAnotherWorkspace = errors.New("telegram: this bot is already connected to a different Multica workspace")
+ // ErrBotOwnedBySameWorkspace: the bot is already connected to a different
+ // live agent in the SAME workspace.
+ ErrBotOwnedBySameWorkspace = errors.New("telegram: this bot is already connected to another agent in this workspace")
+ // ErrBotOwnedByArchivedAgent: the bot's owning agent is archived.
+ ErrBotOwnedByArchivedAgent = errors.New("telegram: this bot is connected to an archived agent in this workspace")
+ // ErrWebhookConfigured means the bot is currently managed by an outgoing
+ // webhook. Long polling and webhooks are mutually exclusive, so do not
+ // silently delete another integration's webhook during installation.
+ ErrWebhookConfigured = errors.New("telegram: bot has an outgoing webhook configured")
+)
+
+// installQueries is the slice of generated queries InstallService needs,
+// interface-shaped so tests inject a fake (same adapter pattern as Slack).
+type installQueries interface {
+ WithTx(tx pgx.Tx) installQueries
+ UpsertChannelInstallation(ctx context.Context, arg db.UpsertChannelInstallationParams) (db.ChannelInstallation, error)
+ ReclaimDeadChannelInstallationByAppID(ctx context.Context, arg db.ReclaimDeadChannelInstallationByAppIDParams) (pgtype.UUID, error)
+ GetChannelInstallationOwnerByAppID(ctx context.Context, arg db.GetChannelInstallationOwnerByAppIDParams) (db.GetChannelInstallationOwnerByAppIDRow, error)
+ ListChannelInstallationsByWorkspace(ctx context.Context, arg db.ListChannelInstallationsByWorkspaceParams) ([]db.ChannelInstallation, error)
+ GetChannelInstallationInWorkspace(ctx context.Context, arg db.GetChannelInstallationInWorkspaceParams) (db.ChannelInstallation, error)
+ SetChannelInstallationStatus(ctx context.Context, arg db.SetChannelInstallationStatusParams) error
+}
+
+type dbInstallQueries struct{ *db.Queries }
+
+func (q dbInstallQueries) WithTx(tx pgx.Tx) installQueries {
+ return dbInstallQueries{q.Queries.WithTx(tx)}
+}
+
+// InstallService owns the at-rest encryption of the bot token and the install
+// transaction. The box MUST be non-nil (we refuse plaintext storage even in
+// dev).
+type InstallService struct {
+ box *secretbox.Box
+ q installQueries
+ tx engine.TxStarter
+ httpClient *http.Client
+ logger *slog.Logger
+
+ // apiBase overrides the Bot API host for the getMe validation call (tests
+ // point it at an httptest server). Empty uses the real API.
+ apiBase string
+}
+
+// NewInstallService binds the service to queries, a tx starter, and an
+// encryption box.
+func NewInstallService(q *db.Queries, tx engine.TxStarter, box *secretbox.Box, logger *slog.Logger) (*InstallService, error) {
+ if q == nil {
+ return nil, errors.New("telegram: InstallService requires queries")
+ }
+ return newInstallService(dbInstallQueries{q}, tx, box, logger)
+}
+
+func newInstallService(q installQueries, tx engine.TxStarter, box *secretbox.Box, logger *slog.Logger) (*InstallService, error) {
+ if box == nil {
+ return nil, errors.New("telegram: InstallService requires a non-nil secretbox.Box")
+ }
+ if q == nil {
+ return nil, errors.New("telegram: InstallService requires queries")
+ }
+ if tx == nil {
+ return nil, errors.New("telegram: InstallService requires a tx starter")
+ }
+ if logger == nil {
+ logger = slog.Default()
+ }
+ return &InstallService{
+ box: box,
+ q: q,
+ tx: tx,
+ httpClient: newCredentialVerificationClient(),
+ logger: logger,
+ }, nil
+}
+
+// RegisterParams are the inputs for a bot install: the agent this bot
+// represents, who is installing, and the pasted BotFather token.
+type RegisterParams struct {
+ WorkspaceID pgtype.UUID
+ AgentID pgtype.UUID
+ InitiatorID pgtype.UUID
+ BotToken string
+}
+
+// Register installs a user-supplied Telegram bot for an agent: validate the
+// token live via getMe (which also yields the bot's username for @-mention
+// detection), encrypt the token at rest, and persist the installation keyed
+// by (workspace, agent) with the bot id in the routing slot.
+func (s *InstallService) Register(ctx context.Context, p RegisterParams) (db.ChannelInstallation, error) {
+ token := strings.TrimSpace(p.BotToken)
+ botID, err := parseBotID(token)
+ if err != nil {
+ return db.ChannelInstallation{}, err
+ }
+ api := newBotAPI(s.apiBase, token, s.httpClient)
+ me, err := api.GetMe(ctx)
+ if err != nil {
+ return db.ChannelInstallation{}, fmt.Errorf("telegram getMe: %w", classifyCredentialVerificationError(err))
+ }
+ if !me.IsBot || me.Username == "" {
+ return db.ChannelInstallation{}, fmt.Errorf("%w: response is not a bot with a username", ErrCredentialsRejected)
+ }
+ webhook, err := api.GetWebhookInfo(ctx)
+ if err != nil {
+ return db.ChannelInstallation{}, fmt.Errorf("telegram getWebhookInfo: %w", classifyCredentialVerificationError(err))
+ }
+ if webhook.URL != "" {
+ return db.ChannelInstallation{}, ErrWebhookConfigured
+ }
+
+ sealed, err := s.box.Seal([]byte(token))
+ if err != nil {
+ return db.ChannelInstallation{}, fmt.Errorf("encrypt telegram bot token: %w", err)
+ }
+ cfgJSON, err := json.Marshal(installConfig{
+ AppID: botID,
+ BotUsername: me.Username,
+ BotTokenEncrypted: base64.StdEncoding.EncodeToString(sealed),
+ })
+ if err != nil {
+ return db.ChannelInstallation{}, fmt.Errorf("encode telegram installation config: %w", err)
+ }
+ return s.persistInstall(ctx, installPersist{
+ wsID: p.WorkspaceID,
+ agentID: p.AgentID,
+ installerID: p.InitiatorID,
+ appIDKey: botID,
+ configJSON: cfgJSON,
+ })
+}
+
+// classifyCredentialVerificationError separates Telegram's authoritative
+// credential rejection from failures where no verdict was obtained. getMe and
+// getWebhookInfo use the same classifier so a proxy outage at either step has
+// the same user-facing next action.
+func classifyCredentialVerificationError(err error) error {
+ var apiErr *apiError
+ if errors.As(err, &apiErr) && apiErr.Code == http.StatusUnauthorized {
+ return fmt.Errorf("%w: %v", ErrCredentialsRejected, err)
+ }
+ return fmt.Errorf("%w: %v", ErrCredentialsUnverifiable, err)
+}
+
+// installPersist carries the resolved fields persistInstall writes.
+type installPersist struct {
+ wsID pgtype.UUID
+ agentID pgtype.UUID
+ installerID pgtype.UUID
+ appIDKey string
+ configJSON []byte
+}
+
+const pgUniqueViolation = "23505"
+
+const credentialVerificationTimeout = 15 * time.Second
+
+func newCredentialVerificationClient() *http.Client {
+ return &http.Client{Timeout: credentialVerificationTimeout}
+}
+
+// persistInstall upserts the installation keyed by (workspace_id, agent_id,
+// channel_type): ONE Telegram bot per agent. A unique violation on the
+// (channel_type, app_id) routing index means the pasted bot is already
+// connected to a different live agent or workspace — refuse rather than
+// steal, with the accurate conflict message (same policy as Slack #4810).
+func (s *InstallService) persistInstall(ctx context.Context, p installPersist) (db.ChannelInstallation, error) {
+ tx, err := s.tx.Begin(ctx)
+ if err != nil {
+ return db.ChannelInstallation{}, fmt.Errorf("begin install tx: %w", err)
+ }
+ defer func() { _ = tx.Rollback(ctx) }()
+ qtx := s.q.WithTx(tx)
+
+ // Free the routing slot from any DEAD prior owner before the upsert.
+ if _, err := qtx.ReclaimDeadChannelInstallationByAppID(ctx, db.ReclaimDeadChannelInstallationByAppIDParams{
+ ChannelType: string(TypeTelegram),
+ AppID: p.appIDKey,
+ WorkspaceID: p.wsID,
+ AgentID: p.agentID,
+ }); err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ return db.ChannelInstallation{}, fmt.Errorf("reclaim dead telegram installation: %w", err)
+ }
+
+ inst, err := qtx.UpsertChannelInstallation(ctx, db.UpsertChannelInstallationParams{
+ WorkspaceID: p.wsID,
+ AgentID: p.agentID,
+ ChannelType: string(TypeTelegram),
+ Config: p.configJSON,
+ InstallerUserID: p.installerID,
+ })
+ if err != nil {
+ var pgErr *pgconn.PgError
+ if errors.As(err, &pgErr) && pgErr.Code == pgUniqueViolation {
+ return db.ChannelInstallation{}, s.liveOwnerConflictErr(ctx, p.wsID, p.appIDKey)
+ }
+ return db.ChannelInstallation{}, fmt.Errorf("upsert telegram installation: %w", err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return db.ChannelInstallation{}, fmt.Errorf("commit telegram install: %w", err)
+ }
+ return inst, nil
+}
+
+// liveOwnerConflictErr classifies who holds the routing slot so the handler
+// renders an accurate message.
+func (s *InstallService) liveOwnerConflictErr(ctx context.Context, requestingWorkspaceID pgtype.UUID, appID string) error {
+ owner, err := s.q.GetChannelInstallationOwnerByAppID(ctx, db.GetChannelInstallationOwnerByAppIDParams{
+ ChannelType: string(TypeTelegram),
+ AppID: appID,
+ })
+ if err != nil {
+ return ErrBotOwnedByAnotherWorkspace
+ }
+ switch {
+ case owner.WorkspaceID != requestingWorkspaceID:
+ return ErrBotOwnedByAnotherWorkspace
+ case owner.AgentArchivedAt.Valid:
+ return ErrBotOwnedByArchivedAgent
+ default:
+ return ErrBotOwnedBySameWorkspace
+ }
+}
+
+// ListByWorkspace returns every Telegram installation in the workspace, for
+// the management surface.
+func (s *InstallService) ListByWorkspace(ctx context.Context, wsID pgtype.UUID) ([]db.ChannelInstallation, error) {
+ return s.q.ListChannelInstallationsByWorkspace(ctx, db.ListChannelInstallationsByWorkspaceParams{
+ WorkspaceID: wsID,
+ ChannelType: string(TypeTelegram),
+ })
+}
+
+// GetInWorkspace is the workspace-scoped lookup so a forged installation id
+// from another workspace returns NotFound instead of leaking existence.
+func (s *InstallService) GetInWorkspace(ctx context.Context, id, wsID pgtype.UUID) (db.ChannelInstallation, error) {
+ inst, err := s.q.GetChannelInstallationInWorkspace(ctx, db.GetChannelInstallationInWorkspaceParams{
+ ID: id,
+ WorkspaceID: wsID,
+ ChannelType: string(TypeTelegram),
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return db.ChannelInstallation{}, ErrInstallationNotFound
+ }
+ return db.ChannelInstallation{}, err
+ }
+ return inst, nil
+}
+
+// Revoke flips status to 'revoked'. The row is preserved for audit; existing
+// chat sessions stay in Multica. The Supervisor stops supervising the
+// installation, so its polling loop winds down and outbound drops too.
+func (s *InstallService) Revoke(ctx context.Context, id pgtype.UUID) error {
+ return s.q.SetChannelInstallationStatus(ctx, db.SetChannelInstallationStatusParams{
+ ID: id,
+ Status: "revoked",
+ })
+}
diff --git a/server/internal/integrations/telegram/install_error_test.go b/server/internal/integrations/telegram/install_error_test.go
new file mode 100644
index 0000000000..451230b0a1
--- /dev/null
+++ b/server/internal/integrations/telegram/install_error_test.go
@@ -0,0 +1,52 @@
+package telegram
+
+import (
+ "errors"
+ "net/http"
+ "testing"
+ "time"
+)
+
+func TestCredentialVerificationClientHasBoundedTimeout(t *testing.T) {
+ client := newCredentialVerificationClient()
+ if client.Timeout != 15*time.Second {
+ t.Fatalf("verification timeout = %s, want 15s", client.Timeout)
+ }
+}
+
+func TestClassifyCredentialVerificationError(t *testing.T) {
+ tests := []struct {
+ name string
+ err error
+ want error
+ }{
+ {
+ name: "Telegram rejects the token",
+ err: &apiError{Code: http.StatusUnauthorized, Description: "Unauthorized"},
+ want: ErrCredentialsRejected,
+ },
+ {
+ name: "Telegram rate limits verification",
+ err: &apiError{Code: http.StatusTooManyRequests, Description: "Too Many Requests"},
+ want: ErrCredentialsUnverifiable,
+ },
+ {
+ name: "transport cannot reach Telegram",
+ err: &requestError{method: "getMe", cause: errors.New("proxy connect failed")},
+ want: ErrCredentialsUnverifiable,
+ },
+ {
+ name: "malformed upstream response",
+ err: errors.New("decode response"),
+ want: ErrCredentialsUnverifiable,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if err := classifyCredentialVerificationError(tt.err); !errors.Is(err, tt.want) {
+ t.Fatalf("classifyCredentialVerificationError() = %v, want %v", err, tt.want)
+ }
+ })
+ }
+}
diff --git a/server/internal/integrations/telegram/install_test.go b/server/internal/integrations/telegram/install_test.go
new file mode 100644
index 0000000000..d2adfc3513
--- /dev/null
+++ b/server/internal/integrations/telegram/install_test.go
@@ -0,0 +1,250 @@
+package telegram
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgconn"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/util/secretbox"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+type fakeTelegramInstallQueries struct {
+ upsertCalled bool
+ upsert db.UpsertChannelInstallationParams
+ rowID pgtype.UUID
+ appIDTaken bool
+ owner db.GetChannelInstallationOwnerByAppIDRow
+ ownerErr error
+ listed []db.ChannelInstallation
+ listParams db.ListChannelInstallationsByWorkspaceParams
+ listErr error
+ got db.ChannelInstallation
+ getParams db.GetChannelInstallationInWorkspaceParams
+ getErr error
+ statusParams db.SetChannelInstallationStatusParams
+ statusErr error
+}
+
+func (f *fakeTelegramInstallQueries) WithTx(pgx.Tx) installQueries { return f }
+func (f *fakeTelegramInstallQueries) ReclaimDeadChannelInstallationByAppID(context.Context, db.ReclaimDeadChannelInstallationByAppIDParams) (pgtype.UUID, error) {
+ return pgtype.UUID{}, pgx.ErrNoRows
+}
+func (f *fakeTelegramInstallQueries) UpsertChannelInstallation(_ context.Context, p db.UpsertChannelInstallationParams) (db.ChannelInstallation, error) {
+ f.upsertCalled, f.upsert = true, p
+ if f.appIDTaken {
+ return db.ChannelInstallation{}, &pgconn.PgError{Code: pgUniqueViolation}
+ }
+ return db.ChannelInstallation{ID: f.rowID, WorkspaceID: p.WorkspaceID, AgentID: p.AgentID, ChannelType: p.ChannelType, Config: p.Config, InstallerUserID: p.InstallerUserID, Status: "active"}, nil
+}
+func (f *fakeTelegramInstallQueries) GetChannelInstallationOwnerByAppID(context.Context, db.GetChannelInstallationOwnerByAppIDParams) (db.GetChannelInstallationOwnerByAppIDRow, error) {
+ return f.owner, f.ownerErr
+}
+func (f *fakeTelegramInstallQueries) ListChannelInstallationsByWorkspace(_ context.Context, p db.ListChannelInstallationsByWorkspaceParams) ([]db.ChannelInstallation, error) {
+ f.listParams = p
+ return f.listed, f.listErr
+}
+func (f *fakeTelegramInstallQueries) GetChannelInstallationInWorkspace(_ context.Context, p db.GetChannelInstallationInWorkspaceParams) (db.ChannelInstallation, error) {
+ f.getParams = p
+ return f.got, f.getErr
+}
+func (f *fakeTelegramInstallQueries) SetChannelInstallationStatus(_ context.Context, p db.SetChannelInstallationStatusParams) error {
+ f.statusParams = p
+ return f.statusErr
+}
+
+type fakeTelegramTx struct {
+ pgx.Tx
+ committed bool
+}
+
+func (t *fakeTelegramTx) Commit(context.Context) error { t.committed = true; return nil }
+func (t *fakeTelegramTx) Rollback(context.Context) error { return nil }
+
+type fakeTelegramTxStarter struct{ tx *fakeTelegramTx }
+
+func (f fakeTelegramTxStarter) Begin(context.Context) (pgx.Tx, error) { return f.tx, nil }
+
+func telegramInstallTestBox(t *testing.T) *secretbox.Box {
+ t.Helper()
+ key := make([]byte, secretbox.KeySize)
+ for i := range key {
+ key[i] = byte(i + 1)
+ }
+ box, err := secretbox.New(key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return box
+}
+
+func newTelegramInstallTestService(t *testing.T, q installQueries) *InstallService {
+ t.Helper()
+ svc, err := newInstallService(q, fakeTelegramTxStarter{tx: &fakeTelegramTx{}}, telegramInstallTestBox(t), testLogger())
+ if err != nil {
+ t.Fatal(err)
+ }
+ return svc
+}
+
+func telegramInstallAPIServer(t *testing.T, webhookURL string) *httptest.Server {
+ t.Helper()
+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ switch {
+ case strings.HasSuffix(r.URL.Path, "/getMe"):
+ _, _ = w.Write([]byte(`{"ok":true,"result":{"id":12345,"is_bot":true,"first_name":"Multica","username":"multica_test_bot"}}`))
+ case strings.HasSuffix(r.URL.Path, "/getWebhookInfo"):
+ _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "result": map[string]any{"url": webhookURL}})
+ default:
+ t.Errorf("unexpected Telegram method %s", r.URL.Path)
+ }
+ }))
+}
+
+func TestRegisterValidatesAndEncryptsBotToken(t *testing.T) {
+ srv := telegramInstallAPIServer(t, "")
+ defer srv.Close()
+ q := &fakeTelegramInstallQueries{rowID: telegramTestUUID(9)}
+ svc := newTelegramInstallTestService(t, q)
+ svc.apiBase, svc.httpClient = srv.URL, srv.Client()
+ p := RegisterParams{WorkspaceID: telegramTestUUID(1), AgentID: telegramTestUUID(2), InitiatorID: telegramTestUUID(3), BotToken: " 12345:secret "}
+ row, err := svc.Register(context.Background(), p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !q.upsertCalled || row.ID != q.rowID || q.upsert.ChannelType != string(TypeTelegram) {
+ t.Fatalf("persisted row = %+v params = %+v", row, q.upsert)
+ }
+ var cfg installConfig
+ if err := json.Unmarshal(q.upsert.Config, &cfg); err != nil {
+ t.Fatal(err)
+ }
+ if cfg.AppID != "12345" || cfg.BotUsername != "multica_test_bot" || strings.Contains(cfg.BotTokenEncrypted, "secret") {
+ t.Fatalf("unsafe or incorrect config = %+v", cfg)
+ }
+ plain, err := decryptToken(cfg.BotTokenEncrypted, svc.box.Open)
+ if err != nil || plain != "12345:secret" {
+ t.Fatalf("decrypted token = %q, %v", plain, err)
+ }
+}
+
+func TestRegisterRejectsMalformedTokenBeforeNetwork(t *testing.T) {
+ q := &fakeTelegramInstallQueries{}
+ svc := newTelegramInstallTestService(t, q)
+ for _, token := range []string{"", "12345:", ":secret", "abc:secret"} {
+ if _, err := svc.Register(context.Background(), RegisterParams{BotToken: token}); !errors.Is(err, ErrInvalidBotToken) {
+ t.Errorf("token %q error = %v", token, err)
+ }
+ }
+ if q.upsertCalled {
+ t.Fatal("malformed token reached persistence")
+ }
+}
+
+func TestRegisterRefusesConfiguredWebhook(t *testing.T) {
+ srv := telegramInstallAPIServer(t, "https://other.example/telegram")
+ defer srv.Close()
+ q := &fakeTelegramInstallQueries{}
+ svc := newTelegramInstallTestService(t, q)
+ svc.apiBase, svc.httpClient = srv.URL, srv.Client()
+ _, err := svc.Register(context.Background(), RegisterParams{BotToken: "12345:secret"})
+ if !errors.Is(err, ErrWebhookConfigured) || q.upsertCalled {
+ t.Fatalf("error = %v, persisted = %v", err, q.upsertCalled)
+ }
+}
+
+func TestInstallationManagementStaysWorkspaceAndChannelScoped(t *testing.T) {
+ q := &fakeTelegramInstallQueries{
+ listed: []db.ChannelInstallation{{ID: telegramTestUUID(9)}},
+ got: db.ChannelInstallation{ID: telegramTestUUID(8)},
+ }
+ svc := newTelegramInstallTestService(t, q)
+ workspaceID := telegramTestUUID(1)
+ installationID := telegramTestUUID(2)
+
+ rows, err := svc.ListByWorkspace(context.Background(), workspaceID)
+ if err != nil || len(rows) != 1 || rows[0].ID != telegramTestUUID(9) {
+ t.Fatalf("ListByWorkspace = %+v, %v", rows, err)
+ }
+ if q.listParams.WorkspaceID != workspaceID || q.listParams.ChannelType != string(TypeTelegram) {
+ t.Fatalf("list params = %+v", q.listParams)
+ }
+
+ row, err := svc.GetInWorkspace(context.Background(), installationID, workspaceID)
+ if err != nil || row.ID != telegramTestUUID(8) {
+ t.Fatalf("GetInWorkspace = %+v, %v", row, err)
+ }
+ if q.getParams.ID != installationID || q.getParams.WorkspaceID != workspaceID ||
+ q.getParams.ChannelType != string(TypeTelegram) {
+ t.Fatalf("get params = %+v", q.getParams)
+ }
+
+ if err := svc.Revoke(context.Background(), installationID); err != nil {
+ t.Fatal(err)
+ }
+ if q.statusParams.ID != installationID || q.statusParams.Status != "revoked" {
+ t.Fatalf("status params = %+v", q.statusParams)
+ }
+}
+
+func TestGetInstallationMapsMissingRowWithoutLeakingScope(t *testing.T) {
+ q := &fakeTelegramInstallQueries{getErr: pgx.ErrNoRows}
+ svc := newTelegramInstallTestService(t, q)
+ _, err := svc.GetInWorkspace(context.Background(), telegramTestUUID(2), telegramTestUUID(1))
+ if !errors.Is(err, ErrInstallationNotFound) {
+ t.Fatalf("GetInWorkspace error = %v, want ErrInstallationNotFound", err)
+ }
+}
+
+func TestLiveBotOwnerConflictIsClassified(t *testing.T) {
+ workspaceID := telegramTestUUID(1)
+ tests := []struct {
+ name string
+ owner db.GetChannelInstallationOwnerByAppIDRow
+ err error
+ want error
+ }{
+ {
+ name: "same workspace active agent",
+ owner: db.GetChannelInstallationOwnerByAppIDRow{WorkspaceID: workspaceID},
+ want: ErrBotOwnedBySameWorkspace,
+ },
+ {
+ name: "same workspace archived agent",
+ owner: db.GetChannelInstallationOwnerByAppIDRow{
+ WorkspaceID: workspaceID,
+ AgentArchivedAt: pgtype.Timestamptz{Time: time.Now(), Valid: true},
+ },
+ want: ErrBotOwnedByArchivedAgent,
+ },
+ {
+ name: "different workspace",
+ owner: db.GetChannelInstallationOwnerByAppIDRow{WorkspaceID: telegramTestUUID(2)},
+ want: ErrBotOwnedByAnotherWorkspace,
+ },
+ {
+ name: "owner lookup failure is privacy preserving",
+ err: errors.New("database unavailable"),
+ want: ErrBotOwnedByAnotherWorkspace,
+ },
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ q := &fakeTelegramInstallQueries{owner: tc.owner, ownerErr: tc.err}
+ svc := newTelegramInstallTestService(t, q)
+ if err := svc.liveOwnerConflictErr(context.Background(), workspaceID, "12345"); !errors.Is(err, tc.want) {
+ t.Fatalf("liveOwnerConflictErr = %v, want %v", err, tc.want)
+ }
+ })
+ }
+}
diff --git a/server/internal/integrations/telegram/markdown.go b/server/internal/integrations/telegram/markdown.go
new file mode 100644
index 0000000000..84f8886907
--- /dev/null
+++ b/server/internal/integrations/telegram/markdown.go
@@ -0,0 +1,119 @@
+package telegram
+
+import (
+ "html"
+ "regexp"
+ "strings"
+)
+
+// This file converts the agent's standard Markdown to Telegram HTML parse
+// mode. HTML is chosen over MarkdownV2 deliberately: MarkdownV2 requires
+// escaping 18 punctuation characters in ALL text (one missed escape fails the
+// whole sendMessage), while HTML only needs &, <, > escaped and unknown tags
+// are the only failure mode. The conversion is line-oriented and intentionally
+// conservative — unrecognized markdown passes through as escaped plain text
+// rather than risking a rejected message.
+
+var (
+ reBold = regexp.MustCompile(`\*\*(.+?)\*\*`)
+ reItalic = regexp.MustCompile(`(^|[^*])\*([^*]+?)\*`)
+ reStrike = regexp.MustCompile(`~~(.+?)~~`)
+ reInlineCode = regexp.MustCompile("`([^`]+)`")
+ reLink = regexp.MustCompile(`\[([^\]]+)\]\(([^)\s]+)\)`)
+ reHeading = regexp.MustCompile(`^#{1,6}\s+(.*)$`)
+ reBullet = regexp.MustCompile(`^(\s*)[-*]\s+`)
+)
+
+// formatHTML renders markdown text as Telegram HTML. Code blocks are handled
+// first (their content must stay verbatim, only entity-escaped); the rest is
+// converted line by line.
+func formatHTML(md string) string {
+ var out strings.Builder
+ lines := strings.Split(md, "\n")
+ inCode := false
+ var codeLang string
+ var codeBuf []string
+ for _, line := range lines {
+ trimmed := strings.TrimSpace(line)
+ if strings.HasPrefix(trimmed, "```") {
+ if inCode {
+ out.WriteString(renderCodeBlock(codeLang, codeBuf))
+ out.WriteString("\n")
+ inCode, codeBuf, codeLang = false, nil, ""
+ } else {
+ inCode = true
+ codeLang = strings.TrimPrefix(trimmed, "```")
+ }
+ continue
+ }
+ if inCode {
+ codeBuf = append(codeBuf, line)
+ continue
+ }
+ out.WriteString(formatLine(line))
+ out.WriteString("\n")
+ }
+ if inCode {
+ // Unterminated fence (mid-stream snapshot): render what we have so the
+ // throttled edit still shows the partial block.
+ out.WriteString(renderCodeBlock(codeLang, codeBuf))
+ out.WriteString("\n")
+ }
+ return strings.TrimRight(out.String(), "\n")
+}
+
+func renderCodeBlock(lang string, lines []string) string {
+ body := html.EscapeString(strings.Join(lines, "\n"))
+ if lang != "" {
+ return `<pre><code class="language-` + html.EscapeString(lang) + `">` + body + `</code></pre>`
+ }
+ return "<pre>" + body + "</pre>"
+}
+
+// formatLine converts one non-code line: escape first, then re-introduce the
+// allowed tags by pattern. Placeholders guard inline code spans from the
+// styling passes.
+func formatLine(line string) string {
+ if m := reHeading.FindStringSubmatch(line); m != nil {
+ return "<b>" + formatInline(m[1]) + "</b>"
+ }
+ if m := reBullet.FindStringSubmatchIndex(line); m != nil {
+ return line[m[2]:m[3]] + "• " + formatInline(line[m[1]:])
+ }
+ return formatInline(line)
+}
+
+func formatInline(s string) string {
+ // Extract inline code spans before escaping/styling so their content is
+ // untouched by the emphasis passes.
+ type span struct{ content string }
+ var spans []span
+ s = reInlineCode.ReplaceAllStringFunc(s, func(m string) string {
+ content := strings.Trim(m, "`")
+ spans = append(spans, span{content})
+ return "\x00CODE\x00"
+ })
+
+ // Links: capture before escaping so the URL survives untouched.
+ type link struct{ label, url string }
+ var links []link
+ s = reLink.ReplaceAllStringFunc(s, func(m string) string {
+ g := reLink.FindStringSubmatch(m)
+ links = append(links, link{g[1], g[2]})
+ return "\x00LINK\x00"
+ })
+
+ s = html.EscapeString(s)
+ s = reBold.ReplaceAllString(s, "<b>$1</b>")
+ s = reItalic.ReplaceAllString(s, "$1<i>$2</i>")
+ s = reStrike.ReplaceAllString(s, "<s>$1</s>")
+
+ for _, l := range links {
+ tag := `<a href="` + html.EscapeString(l.url) + `">` + html.EscapeString(l.label) + `</a>`
+ s = strings.Replace(s, "\x00LINK\x00", tag, 1)
+ }
+ for _, c := range spans {
+ s = strings.Replace(s, "\x00CODE\x00", "<code>"+html.EscapeString(c.content)+"</code>", 1)
+ }
+ return s
+}
diff --git a/server/internal/integrations/telegram/outbound.go b/server/internal/integrations/telegram/outbound.go
new file mode 100644
index 0000000000..a935731081
--- /dev/null
+++ b/server/internal/integrations/telegram/outbound.go
@@ -0,0 +1,1117 @@
+package telegram
+
+import (
+ "container/heap"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "strconv"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// Outbound delivers an agent's chat reply back to Telegram — the outbound
+// half of the round trip, mirroring lark.Patcher / slack.Outbound on the
+// shared event bus.
+//
+// Streaming: Telegram has no stream-update protocol, so the "stream 帧" UX is
+// simulated with the platform's canonical pattern — post one placeholder
+// message on the first partial, then throttled editMessageText calls as the
+// agent's transcript grows (EventTaskMessage text frames), and a final edit /
+// send on EventChatDone. Edits are throttled per chat to stay inside
+// Telegram's editMessageText rate budget; on a 429 the streamer backs off and
+// the final content always lands via the EventChatDone path.
+type Outbound struct {
+ q outboundQueries
+ decrypt Decrypter
+ logger *slog.Logger
+ apiBase string
+ client *http.Client
+
+ mu sync.Mutex
+ streams map[string]*streamState // key = task_id
+ chats map[chatScheduleKey]*chatSchedule
+ botFallbackBackoff map[string]time.Time
+ now func() time.Time
+ wait func(context.Context, time.Duration) error
+
+ terminalMu sync.Mutex
+ terminalSessions map[string]*terminalSession
+ terminalReady []string
+ terminalRetries terminalRetryHeap
+ terminalWake chan struct{}
+ terminalWork chan terminalWork
+ terminalResults chan terminalResult
+ terminalStopped bool
+ terminalInFlight int
+ queuedTerminalReplyCount int
+ queuedTerminalReplyBytes int
+ workerOnce sync.Once
+ workerWG sync.WaitGroup
+ terminalWorkerWG sync.WaitGroup
+}
+
+// outboundQueries is the slice of generated queries the subscriber needs.
+// *db.Queries satisfies it.
+type outboundQueries interface {
+ GetAgentTask(ctx context.Context, id pgtype.UUID) (db.AgentTaskQueue, error)
+ TaskHasChannelIngestedMessages(ctx context.Context, taskID pgtype.UUID) (bool, error)
+ GetChannelChatSessionBindingBySession(ctx context.Context, arg db.GetChannelChatSessionBindingBySessionParams) (db.ChannelChatSessionBinding, error)
+ GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)
+}
+
+// streamState tracks one in-flight streamed reply.
+type streamState struct {
+ chatID int64
+ threadID int64
+ replyTo int64
+ messageID int64 // placeholder message being edited; 0 until first send
+ accumulated string
+ schedule *chatSchedule
+}
+
+// chatSchedule serializes Telegram delivery and owns rate-limit state shared
+// by every task targeting the same chat. refs and idleSince are protected by
+// Outbound.mu; lastEdit and backoffTill are protected by mu.
+type chatSchedule struct {
+ mu sync.Mutex
+ key chatScheduleKey
+ refs int
+ lastEdit time.Time
+ backoffTill time.Time
+ backoffUnix atomic.Int64
+ idleSince time.Time
+}
+
+type chatScheduleKey struct {
+ botKey string
+ chatID int64
+}
+
+type terminalSession struct {
+ queue []*terminalReply
+ running bool
+ ready bool
+ retryWaiting bool
+}
+
+type terminalReply struct {
+ event events.Event
+ byteSize int
+ initialized bool
+ target *replyTarget
+ schedule *chatSchedule
+ chunks []string
+ chunkIndex int
+ streamedMessageID int64
+ placeholderEdited bool
+ fallbackFreshSend bool
+ plainTextFallback bool
+ cleanupOnce sync.Once
+}
+
+type terminalWork struct {
+ sessionID string
+ reply *terminalReply
+}
+
+type terminalResult struct {
+ terminalWork
+ done bool
+ retryAt time.Time
+ err error
+}
+
+type terminalRetry struct {
+ sessionID string
+ retryAt time.Time
+}
+
+type terminalRetryHeap []terminalRetry
+
+func (h terminalRetryHeap) Len() int { return len(h) }
+func (h terminalRetryHeap) Less(i, j int) bool { return h[i].retryAt.Before(h[j].retryAt) }
+func (h terminalRetryHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
+func (h *terminalRetryHeap) Push(x any) { *h = append(*h, x.(terminalRetry)) }
+func (h *terminalRetryHeap) Pop() any {
+ old := *h
+ n := len(old)
+ x := old[n-1]
+ *h = old[:n-1]
+ return x
+}
+
+// editInterval is the minimum spacing between editMessageText calls per chat.
+// Telegram tolerates roughly one edit per second per chat, with a much
+// stricter per-group budget (~20 messages/min); 2.5s keeps a long generation
+// well inside both without feeling static.
+const editInterval = 2500 * time.Millisecond
+
+// Idle schedules remain briefly reusable so sequential tasks and cancellation
+// cannot discard a chat's edit cooldown or Telegram retry_after window. The
+// schedule and compressed-fallback maps both have hard capacity limits.
+const (
+ chatScheduleIdleTTL = 10 * time.Minute
+ maxChatSchedules = 1024
+ terminalWorkerCount = 4
+ maxBotFallbacks = 1024
+ chatCapacityRetry = time.Second
+ maxQueuedTerminalReplies = 64
+ maxQueuedTerminalRepliesPerSession = 8
+ maxQueuedTerminalReplyBytes = 16 << 20
+)
+
+// streamPlaceholder is the first frame's text while the first tokens arrive.
+const streamPlaceholder = "…"
+
+// taskFailedText is sent when the agent run fails outright.
+const taskFailedText = "❌ 智能体处理失败,请稍后重试。"
+
+// NewOutbound builds the Telegram outbound subscriber.
+func NewOutbound(q outboundQueries, decrypt Decrypter, apiBase string, client *http.Client, logger *slog.Logger) *Outbound {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ o := &Outbound{
+ q: q,
+ decrypt: decrypt,
+ logger: logger,
+ apiBase: apiBase,
+ client: client,
+ streams: make(map[string]*streamState),
+ chats: make(map[chatScheduleKey]*chatSchedule),
+ botFallbackBackoff: make(map[string]time.Time),
+ now: time.Now,
+ wait: waitForOutbound,
+ terminalSessions: make(map[string]*terminalSession),
+ terminalWake: make(chan struct{}, 1),
+ terminalWork: make(chan terminalWork, terminalWorkerCount),
+ terminalResults: make(chan terminalResult, terminalWorkerCount),
+ }
+ return o
+}
+
+// Register subscribes to the transcript / completion / failure events.
+func (o *Outbound) Register(bus *events.Bus) {
+ bus.Subscribe(protocol.EventTaskMessage, o.handleTaskMessage)
+ bus.Subscribe(protocol.EventChatDone, o.enqueueTerminalReply)
+ bus.Subscribe(protocol.EventTaskFailed, o.handleTaskFailed)
+ bus.Subscribe(protocol.EventTaskCancelled, o.handleTaskCancelled)
+}
+
+// Start owns the asynchronous terminal-delivery workers. EventChatDone is
+// published on the synchronous process bus, so its handler only enqueues work;
+// Telegram rate limits and network latency must never delay realtime fanout.
+func (o *Outbound) Start(ctx context.Context) {
+ o.workerOnce.Do(func() {
+ o.workerWG.Add(1)
+ o.terminalWorkerWG.Add(terminalWorkerCount)
+ for range terminalWorkerCount {
+ go o.sendTerminalReplies(ctx)
+ }
+ go o.dispatchTerminalReplies(ctx)
+ o.wakeTerminalDispatcher()
+ })
+}
+
+// WaitWithTimeout bounds graceful shutdown without coupling the event bus to
+// Telegram delivery latency.
+func (o *Outbound) WaitWithTimeout(timeout time.Duration) bool {
+ done := make(chan struct{})
+ go func() {
+ o.workerWG.Wait()
+ close(done)
+ }()
+ select {
+ case <-done:
+ return true
+ case <-time.After(timeout):
+ return false
+ }
+}
+
+// handleTaskMessage streams a partial: on each agent text frame, update the
+// placeholder message (throttled). Bus delivery is synchronous, so all work
+// runs under a tight timeout and never propagates errors.
+func (o *Outbound) handleTaskMessage(e events.Event) {
+ payload, ok := e.Payload.(protocol.TaskMessagePayload)
+ if !ok || payload.Type != "text" || payload.Content == "" {
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ target, err := o.resolveTarget(ctx, e, true)
+ if err != nil || target == nil {
+ return
+ }
+
+ o.mu.Lock()
+ st, exists := o.streams[target.streamKey]
+ if !exists {
+ schedule := o.retainChatLocked(target.botKey, target.chatID)
+ if schedule == nil {
+ o.mu.Unlock()
+ return
+ }
+ st = &streamState{
+ chatID: target.chatID, threadID: target.threadID, replyTo: target.replyTo,
+ schedule: schedule,
+ }
+ o.streams[target.streamKey] = st
+ }
+ st.accumulated += payload.Content
+ snapshot := st.accumulated
+ msgID := st.messageID
+ o.mu.Unlock()
+
+ o.pushPartial(ctx, target, st, msgID, snapshot)
+}
+
+// pushPartial sends the placeholder on the first flush and edits it after.
+func (o *Outbound) pushPartial(ctx context.Context, target *replyTarget, st *streamState, msgID int64, snapshot string) {
+ if !st.schedule.mu.TryLock() {
+ return
+ }
+ defer st.schedule.mu.Unlock()
+ now := o.now()
+ if o.terminalAvailableAt(st.schedule, target.botKey, now).After(now) {
+ return
+ }
+
+ api := newBotAPI(o.apiBase, target.botToken, o.client)
+ text := snapshot
+ if utf16Units(text) > maxMessageUnits {
+ // Mid-stream overflow: freeze the streamed message at the cap; the full
+ // reply is delivered in chunks by the final EventChatDone send.
+ text = chunkMessage(text, maxMessageUnits)[0]
+ }
+ if msgID == 0 {
+ var reply *replyParameters
+ if st.replyTo != 0 {
+ reply = &replyParameters{MessageID: st.replyTo, AllowSendingWithoutReply: true}
+ }
+ m, err := api.SendMessage(ctx, sendMessageParams{
+ ChatID: st.chatID,
+ Text: firstNonEmpty(formatHTML(text), streamPlaceholder),
+ ParseMode: "HTML",
+ MessageThreadID: st.threadID,
+ ReplyParameters: reply,
+ })
+ if err != nil {
+ o.noteEditFailure(st.schedule, err)
+ return
+ }
+ st.schedule.lastEdit = o.now()
+ o.mu.Lock()
+ st.messageID = m.MessageID
+ o.mu.Unlock()
+ return
+ }
+ err := api.EditMessageText(ctx, editMessageTextParams{
+ ChatID: st.chatID,
+ MessageID: msgID,
+ Text: formatHTML(text),
+ ParseMode: "HTML",
+ })
+ if err != nil && !isNotModified(err) {
+ o.noteEditFailure(st.schedule, err)
+ return
+ }
+ st.schedule.lastEdit = o.now()
+}
+
+// noteEditFailure applies the 429-mandated backoff to the stream; other
+// failures are logged and the stream simply stops editing (the final content
+// still lands via EventChatDone).
+func (o *Outbound) noteEditFailure(schedule *chatSchedule, err error) {
+ if wait, ok := retryAfter(err); ok {
+ schedule.setBackoffTill(o.now().Add(wait))
+ return
+ }
+ o.logger.Warn("telegram outbound: stream edit failed", "error", err)
+}
+
+// enqueueTerminalReply only appends to a bounded keyed FIFO. events.Bus is synchronous;
+// doing Telegram I/O here would stall SubscribeAll realtime fanout behind
+// retry_after waits and slow network requests.
+func (o *Outbound) enqueueTerminalReply(e events.Event) {
+ _, hasTaskID := eventTaskID(e)
+ sessionID, sessionErr := util.ParseUUID(e.ChatSessionID)
+ if !hasTaskID || sessionErr != nil || !sessionID.Valid {
+ o.logger.Error("telegram outbound: terminal reply has invalid identity",
+ "task_id", e.TaskID, "chat_session_id", e.ChatSessionID)
+ o.clearStream(e)
+ return
+ }
+ content := chatDoneContent(e.Payload)
+ if content == "" {
+ o.clearStream(e)
+ return
+ }
+ sessionKey := e.ChatSessionID
+ replyBytes := len(content)
+ o.terminalMu.Lock()
+ if o.terminalStopped {
+ o.terminalMu.Unlock()
+ o.clearStream(e)
+ return
+ }
+ session := o.terminalSessions[sessionKey]
+ if session == nil {
+ session = &terminalSession{}
+ o.terminalSessions[sessionKey] = session
+ }
+ if o.queuedTerminalReplyCount >= maxQueuedTerminalReplies ||
+ len(session.queue) >= maxQueuedTerminalRepliesPerSession ||
+ replyBytes > maxQueuedTerminalReplyBytes-o.queuedTerminalReplyBytes {
+ count := o.queuedTerminalReplyCount
+ bytes := o.queuedTerminalReplyBytes
+ perSession := len(session.queue)
+ if len(session.queue) == 0 {
+ delete(o.terminalSessions, sessionKey)
+ }
+ o.terminalMu.Unlock()
+ o.clearStream(e)
+ o.logger.Error("telegram outbound: terminal reply queue capacity exceeded",
+ "task_id", e.TaskID, "chat_session_id", e.ChatSessionID,
+ "queued_count", count, "queued_count_limit", maxQueuedTerminalReplies,
+ "session_queued_count", perSession, "session_queued_count_limit", maxQueuedTerminalRepliesPerSession,
+ "queued_bytes", bytes, "reply_bytes", replyBytes, "queued_bytes_limit", maxQueuedTerminalReplyBytes)
+ return
+ }
+ session.queue = append(session.queue, &terminalReply{event: e, byteSize: replyBytes})
+ o.queuedTerminalReplyCount++
+ o.queuedTerminalReplyBytes += replyBytes
+ if !session.running && !session.ready && !session.retryWaiting {
+ o.queueTerminalReadyLocked(sessionKey, session)
+ }
+ o.terminalMu.Unlock()
+ o.wakeTerminalDispatcher()
+}
+
+func (o *Outbound) queueTerminalReadyLocked(sessionID string, session *terminalSession) {
+ if session == nil || len(session.queue) == 0 || session.ready || session.running || session.retryWaiting {
+ return
+ }
+ session.ready = true
+ o.terminalReady = append(o.terminalReady, sessionID)
+}
+
+func (o *Outbound) wakeTerminalDispatcher() {
+ select {
+ case o.terminalWake <- struct{}{}:
+ default:
+ }
+}
+
+func (o *Outbound) dispatchTerminalReplies(ctx context.Context) {
+ defer o.workerWG.Done()
+ timer := time.NewTimer(time.Hour)
+ if !timer.Stop() {
+ <-timer.C
+ }
+ defer timer.Stop()
+
+ for {
+ o.terminalMu.Lock()
+ now := o.now()
+ for o.terminalRetries.Len() > 0 && !o.terminalRetries[0].retryAt.After(now) {
+ retry := heap.Pop(&o.terminalRetries).(terminalRetry)
+ session := o.terminalSessions[retry.sessionID]
+ if session == nil || !session.retryWaiting {
+ continue
+ }
+ session.retryWaiting = false
+ o.queueTerminalReadyLocked(retry.sessionID, session)
+ }
+ for o.terminalInFlight < terminalWorkerCount && len(o.terminalReady) > 0 {
+ sessionID := o.terminalReady[0]
+ o.terminalReady[0] = ""
+ o.terminalReady = o.terminalReady[1:]
+ session := o.terminalSessions[sessionID]
+ if session == nil || len(session.queue) == 0 || !session.ready {
+ continue
+ }
+ session.ready = false
+ session.running = true
+ o.terminalInFlight++
+ o.terminalWork <- terminalWork{sessionID: sessionID, reply: session.queue[0]}
+ }
+ var timerC <-chan time.Time
+ if o.terminalRetries.Len() > 0 {
+ delay := o.terminalRetries[0].retryAt.Sub(o.now())
+ if delay < 0 {
+ delay = 0
+ }
+ timer.Reset(delay)
+ timerC = timer.C
+ }
+ o.terminalMu.Unlock()
+
+ select {
+ case <-ctx.Done():
+ o.stopTerminalScheduler()
+ return
+ case result := <-o.terminalResults:
+ o.updateQueueAfterTerminalRequest(result)
+ case <-o.terminalWake:
+ case <-timerC:
+ }
+ if timerC != nil && !timer.Stop() {
+ select {
+ case <-timer.C:
+ default:
+ }
+ }
+ }
+}
+
+func (o *Outbound) updateQueueAfterTerminalRequest(result terminalResult) {
+ o.terminalMu.Lock()
+ defer o.terminalMu.Unlock()
+ session := o.terminalSessions[result.sessionID]
+ if session == nil || len(session.queue) == 0 || session.queue[0] != result.reply {
+ return
+ }
+ session.running = false
+ o.terminalInFlight--
+ if result.done {
+ if result.err != nil {
+ o.logger.Warn("telegram outbound: reply delivery failed",
+ "error", result.err, "chat_session_id", result.reply.event.ChatSessionID)
+ }
+ o.queuedTerminalReplyCount--
+ o.queuedTerminalReplyBytes -= result.reply.byteSize
+ session.queue[0] = nil
+ session.queue = session.queue[1:]
+ if len(session.queue) == 0 {
+ delete(o.terminalSessions, result.sessionID)
+ return
+ }
+ o.queueTerminalReadyLocked(result.sessionID, session)
+ return
+ }
+ if result.retryAt.After(o.now()) {
+ session.retryWaiting = true
+ heap.Push(&o.terminalRetries, terminalRetry{sessionID: result.sessionID, retryAt: result.retryAt})
+ return
+ }
+ o.queueTerminalReadyLocked(result.sessionID, session)
+}
+
+func (o *Outbound) stopTerminalScheduler() {
+ o.terminalMu.Lock()
+ o.terminalStopped = true
+ close(o.terminalWork)
+ o.terminalMu.Unlock()
+ o.terminalWorkerWG.Wait()
+
+ o.terminalMu.Lock()
+ replies := make([]*terminalReply, 0)
+ for _, session := range o.terminalSessions {
+ replies = append(replies, session.queue...)
+ }
+ o.terminalSessions = make(map[string]*terminalSession)
+ o.terminalReady = nil
+ o.terminalRetries = nil
+ o.terminalInFlight = 0
+ o.queuedTerminalReplyCount = 0
+ o.queuedTerminalReplyBytes = 0
+ o.terminalMu.Unlock()
+ for _, reply := range replies {
+ o.cleanupTerminalReply(reply)
+ }
+}
+
+func (o *Outbound) sendTerminalReplies(ctx context.Context) {
+ defer o.terminalWorkerWG.Done()
+ for work := range o.terminalWork {
+ request := o.sendNextTerminalRequest(ctx, work.reply)
+ if request.done {
+ o.cleanupTerminalReply(work.reply)
+ }
+ result := terminalResult{terminalWork: work, done: request.done, retryAt: request.retryAt, err: request.err}
+ select {
+ case o.terminalResults <- result:
+ case <-ctx.Done():
+ return
+ }
+ }
+}
+
+type terminalRequestResult struct {
+ done bool
+ retryAt time.Time
+ err error
+}
+
+// sendNextTerminalRequest performs at most one Telegram API request. Throttling and
+// retry_after return a future retryAt to the keyed dispatcher, leaving the
+// fixed worker available for another session.
+func (o *Outbound) sendNextTerminalRequest(ctx context.Context, reply *terminalReply) terminalRequestResult {
+ if !reply.initialized {
+ target, err := o.resolveTarget(ctx, reply.event, false)
+ if err != nil {
+ return terminalRequestResult{done: true, err: err}
+ }
+ if target == nil {
+ return terminalRequestResult{done: true}
+ }
+
+ o.mu.Lock()
+ st := o.streams[target.streamKey]
+ var schedule *chatSchedule
+ if st != nil {
+ schedule = st.schedule
+ } else {
+ schedule = o.retainChatLocked(target.botKey, target.chatID)
+ if schedule == nil {
+ o.mu.Unlock()
+ return terminalRequestResult{retryAt: o.now().Add(chatCapacityRetry)}
+ }
+ }
+ delete(o.streams, target.streamKey)
+ o.mu.Unlock()
+
+ reply.initialized = true
+ reply.target = target
+ reply.schedule = schedule
+ reply.chunks = chunkMessage(chatDoneContent(reply.event.Payload), maxMessageUnits)
+ if st != nil {
+ reply.streamedMessageID = st.messageID
+ }
+ if len(reply.chunks) == 0 {
+ return terminalRequestResult{done: true}
+ }
+ return terminalRequestResult{retryAt: o.now()}
+ }
+
+ schedule := reply.schedule
+ schedule.mu.Lock()
+ defer schedule.mu.Unlock()
+ now := o.now()
+ available := o.terminalAvailableAt(schedule, reply.target.botKey, now)
+ if available.After(now) {
+ return terminalRequestResult{retryAt: available}
+ }
+ api := newBotAPI(o.apiBase, reply.target.botToken, o.client)
+
+ if reply.streamedMessageID != 0 && !reply.placeholderEdited && !reply.fallbackFreshSend {
+ err := api.EditMessageText(ctx, editMessageTextParams{
+ ChatID: reply.target.chatID, MessageID: reply.streamedMessageID,
+ Text: formatHTML(reply.chunks[0]), ParseMode: "HTML",
+ })
+ if retry, ok := retryAfter(err); ok {
+ retryAt := o.now().Add(retry)
+ schedule.setBackoffTill(retryAt)
+ return terminalRequestResult{retryAt: retryAt}
+ }
+ if err != nil && !isNotModified(err) {
+ reply.fallbackFreshSend = true
+ reply.chunkIndex = 0
+ return terminalRequestResult{retryAt: o.now()}
+ }
+ reply.placeholderEdited = true
+ reply.chunkIndex = 1
+ schedule.lastEdit = o.now()
+ schedule.setBackoffTill(time.Time{})
+ if reply.chunkIndex == len(reply.chunks) {
+ return terminalRequestResult{done: true}
+ }
+ return terminalRequestResult{retryAt: schedule.lastEdit.Add(editInterval)}
+ }
+
+ chunk := reply.chunks[reply.chunkIndex]
+ params := sendMessageParams{
+ ChatID: reply.target.chatID, Text: formatHTML(chunk), ParseMode: "HTML",
+ MessageThreadID: reply.target.threadID,
+ }
+ if reply.chunkIndex == 0 {
+ params.ReplyParameters = optionalReplyParameters(reply.target.replyTo)
+ }
+ if reply.plainTextFallback {
+ params.Text = chunk
+ params.ParseMode = ""
+ }
+ _, err := api.SendMessage(ctx, params)
+ if retry, ok := retryAfter(err); ok {
+ retryAt := o.now().Add(retry)
+ schedule.setBackoffTill(retryAt)
+ return terminalRequestResult{retryAt: retryAt}
+ }
+ if err != nil && !reply.plainTextFallback && isHTMLParseError(err) {
+ reply.plainTextFallback = true
+ return terminalRequestResult{retryAt: o.now()}
+ }
+ if err != nil {
+ return terminalRequestResult{done: true, err: fmt.Errorf("send final chunk: %w", err)}
+ }
+ reply.chunkIndex++
+ reply.plainTextFallback = false
+ schedule.lastEdit = o.now()
+ schedule.setBackoffTill(time.Time{})
+ if reply.chunkIndex == len(reply.chunks) {
+ return terminalRequestResult{done: true}
+ }
+ return terminalRequestResult{retryAt: schedule.lastEdit.Add(editInterval)}
+}
+
+func (o *Outbound) cleanupTerminalReply(reply *terminalReply) {
+ reply.cleanupOnce.Do(func() {
+ if reply.initialized && reply.schedule != nil {
+ o.releaseChat(reply.schedule, reply.target.chatID)
+ return
+ }
+ o.clearStream(reply.event)
+ })
+}
+
+// handleTaskFailed clears any stream state and posts a failure notice.
+func (o *Outbound) handleTaskFailed(e events.Event) {
+ if taskFailureRetryPending(e.Payload) {
+ o.clearStream(e)
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ target, err := o.resolveTarget(ctx, e, false)
+ if err != nil || target == nil {
+ return
+ }
+ o.mu.Lock()
+ st := o.streams[target.streamKey]
+ delete(o.streams, target.streamKey)
+ var schedule *chatSchedule
+ if st != nil {
+ schedule = st.schedule
+ } else {
+ schedule = o.retainChatLocked(target.botKey, target.chatID)
+ }
+ o.mu.Unlock()
+ if schedule == nil {
+ o.logger.WarnContext(ctx, "telegram outbound: failure notice skipped; chat scheduler is saturated")
+ return
+ }
+ defer o.releaseChat(schedule, target.chatID)
+ schedule.mu.Lock()
+ defer schedule.mu.Unlock()
+
+ api := newBotAPI(o.apiBase, target.botToken, o.client)
+ if st != nil && st.messageID != 0 {
+ if err := o.runScheduled(ctx, schedule, func() error {
+ return api.EditMessageText(ctx, editMessageTextParams{
+ ChatID: st.chatID, MessageID: st.messageID, Text: taskFailedText,
+ })
+ }); err == nil || isNotModified(err) {
+ return
+ }
+ }
+ if err := o.runScheduled(ctx, schedule, func() error {
+ _, err := api.SendMessage(ctx, sendMessageParams{
+ ChatID: target.chatID, Text: taskFailedText, MessageThreadID: target.threadID,
+ ReplyParameters: optionalReplyParameters(target.replyTo),
+ })
+ return err
+ }); err != nil {
+ o.logger.WarnContext(ctx, "telegram outbound: failure notice failed", "error", err)
+ }
+}
+
+// handleTaskCancelled drops local stream state without changing the partial
+// Telegram message already visible to the user. Cancellation has no final
+// agent answer; retaining the partial avoids replacing user-visible content
+// with a synthetic notice while ensuring no task state remains resident.
+func (o *Outbound) handleTaskCancelled(e events.Event) {
+ o.clearStream(e)
+}
+
+func taskFailureRetryPending(payload any) bool {
+ fields, ok := payload.(map[string]any)
+ if !ok {
+ return false
+ }
+ retryPending, _ := fields["retry_pending"].(bool)
+ return retryPending
+}
+
+func (o *Outbound) clearStream(e events.Event) {
+ taskID, ok := eventTaskID(e)
+ if !ok {
+ return
+ }
+ key := util.UUIDToString(taskID)
+ o.mu.Lock()
+ st := o.streams[key]
+ delete(o.streams, key)
+ if st != nil {
+ o.releaseChatLocked(st.schedule, st.chatID)
+ }
+ o.mu.Unlock()
+}
+
+func (o *Outbound) retainChatLocked(botKey string, chatID int64) *chatSchedule {
+ now := o.now()
+ o.pruneIdleChatsLocked(now)
+ key := chatScheduleKey{botKey: botKey, chatID: chatID}
+ schedule := o.chats[key]
+ if schedule != nil && schedule.refs == 0 && !schedule.idleSince.IsZero() &&
+ now.Sub(schedule.idleSince) >= chatScheduleIdleTTL && !schedule.hasActiveBackoff(now) {
+ delete(o.chats, key)
+ schedule = nil
+ }
+ if schedule == nil {
+ if !o.makeChatScheduleRoomLocked(now) {
+ return nil
+ }
+ schedule = &chatSchedule{key: key}
+ o.chats[key] = schedule
+ }
+ schedule.refs++
+ schedule.idleSince = time.Time{}
+ return schedule
+}
+
+func (o *Outbound) releaseChat(schedule *chatSchedule, chatID int64) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ o.releaseChatLocked(schedule, chatID)
+}
+
+func (o *Outbound) releaseChatLocked(schedule *chatSchedule, chatID int64) {
+ if schedule == nil {
+ return
+ }
+ schedule.refs--
+ if schedule.refs == 0 && o.chats[schedule.key] == schedule {
+ schedule.idleSince = o.now()
+ o.pruneIdleChatsLocked(schedule.idleSince)
+ }
+}
+
+func (o *Outbound) pruneIdleChatsLocked(now time.Time) {
+ o.pruneBotFallbacksLocked(now)
+ for key, schedule := range o.chats {
+ if schedule.refs != 0 || schedule.idleSince.IsZero() {
+ continue
+ }
+ if now.Sub(schedule.idleSince) >= chatScheduleIdleTTL && !schedule.hasActiveBackoff(now) {
+ delete(o.chats, key)
+ }
+ }
+}
+
+// makeChatScheduleRoomLocked enforces a hard cap over the entire schedule
+// map. Inactive schedules are evicted first. If every idle candidate has an
+// active retry_after, its exact deadline is conservatively merged into the
+// installation fallback before eviction. A fully in-use cache refuses a new
+// entry; terminal jobs retry later instead of bypassing rate-limit state.
+func (o *Outbound) makeChatScheduleRoomLocked(now time.Time) bool {
+ if len(o.chats) < maxChatSchedules {
+ return true
+ }
+ var inactiveKey chatScheduleKey
+ var inactive *chatSchedule
+ for key, schedule := range o.chats {
+ if schedule.refs != 0 || schedule.idleSince.IsZero() ||
+ now.Sub(schedule.idleSince) < editInterval || schedule.hasActiveBackoff(now) {
+ continue
+ }
+ if inactive == nil || schedule.idleSince.Before(inactive.idleSince) {
+ inactiveKey, inactive = key, schedule
+ }
+ }
+ if inactive != nil {
+ delete(o.chats, inactiveKey)
+ return true
+ }
+
+ var activeKey chatScheduleKey
+ var active *chatSchedule
+ for key, schedule := range o.chats {
+ if schedule.refs != 0 || schedule.idleSince.IsZero() ||
+ now.Sub(schedule.idleSince) < editInterval || !schedule.hasActiveBackoff(now) {
+ continue
+ }
+ if !o.canMergeBotFallbackLocked(schedule.key.botKey, now) {
+ continue
+ }
+ if active == nil || schedule.idleSince.Before(active.idleSince) {
+ activeKey, active = key, schedule
+ }
+ }
+ if active == nil {
+ return false
+ }
+ o.mergeBotFallbackLocked(active.key.botKey, active.backoffSnapshot(), now)
+ delete(o.chats, activeKey)
+ return true
+}
+
+func (o *Outbound) canMergeBotFallbackLocked(botKey string, now time.Time) bool {
+ o.pruneBotFallbacksLocked(now)
+ _, exists := o.botFallbackBackoff[botKey]
+ return exists || len(o.botFallbackBackoff) < maxBotFallbacks
+}
+
+func (o *Outbound) mergeBotFallbackLocked(botKey string, until, now time.Time) {
+ if !until.After(now) {
+ return
+ }
+ if current := o.botFallbackBackoff[botKey]; until.After(current) {
+ o.botFallbackBackoff[botKey] = until
+ }
+}
+
+func (o *Outbound) pruneBotFallbacksLocked(now time.Time) {
+ for botKey, until := range o.botFallbackBackoff {
+ if !until.After(now) {
+ delete(o.botFallbackBackoff, botKey)
+ }
+ }
+}
+
+func (o *Outbound) botFallbackTill(botKey string, now time.Time) time.Time {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ o.pruneBotFallbacksLocked(now)
+ return o.botFallbackBackoff[botKey]
+}
+
+func (o *Outbound) terminalAvailableAt(schedule *chatSchedule, botKey string, now time.Time) time.Time {
+ available := schedule.backoffTill
+ if editAvailable := schedule.lastEdit.Add(editInterval); editAvailable.After(available) {
+ available = editAvailable
+ }
+ if fallback := o.botFallbackTill(botKey, now); fallback.After(available) {
+ available = fallback
+ }
+ return available
+}
+
+// setBackoffTill is called while schedule.mu is held. backoffUnix gives cache
+// pruning a lock-free snapshot, preserving the global Outbound.mu -> no
+// schedule.mu lock order and avoiding the inverse of delivery's
+// schedule.mu -> Outbound.mu path.
+func (s *chatSchedule) setBackoffTill(t time.Time) {
+ s.backoffTill = t
+ if t.IsZero() {
+ s.backoffUnix.Store(0)
+ return
+ }
+ s.backoffUnix.Store(t.UnixNano())
+}
+
+func (s *chatSchedule) hasActiveBackoff(now time.Time) bool {
+ return s.backoffUnix.Load() > now.UnixNano()
+}
+
+func (s *chatSchedule) backoffSnapshot() time.Time {
+ nanos := s.backoffUnix.Load()
+ if nanos == 0 {
+ return time.Time{}
+ }
+ return time.Unix(0, nanos)
+}
+
+// runScheduled waits for the chat's edit interval and any Telegram 429
+// retry_after window. Terminal delivery retries 429 responses until the event
+// context expires; other errors remain non-retriable to avoid duplicates.
+func (o *Outbound) runScheduled(ctx context.Context, schedule *chatSchedule, operation func() error) error {
+ for {
+ now := o.now()
+ available := o.terminalAvailableAt(schedule, schedule.key.botKey, now)
+ if delay := available.Sub(now); delay > 0 {
+ if err := o.wait(ctx, delay); err != nil {
+ return err
+ }
+ }
+ err := operation()
+ if retry, ok := retryAfter(err); ok {
+ schedule.setBackoffTill(o.now().Add(retry))
+ continue
+ }
+ if err == nil {
+ schedule.lastEdit = o.now()
+ schedule.setBackoffTill(time.Time{})
+ }
+ return err
+ }
+}
+
+func waitForOutbound(ctx context.Context, delay time.Duration) error {
+ if sleepCtx(ctx, delay) {
+ return nil
+ }
+ return ctx.Err()
+}
+
+// replyTarget is the resolved destination for one event.
+type replyTarget struct {
+ streamKey string
+ botKey string
+ chatID int64
+ threadID int64
+ replyTo int64
+ botToken string
+}
+
+// resolveTarget maps an event to its Telegram binding + credentials. Returns
+// (nil, nil) when the session is not Telegram-bound. When viaTask is true the
+// chat session id is recovered from the task row (EventTaskMessage carries
+// only TaskID).
+func (o *Outbound) resolveTarget(ctx context.Context, e events.Event, viaTask bool) (*replyTarget, error) {
+ var task *db.AgentTaskQueue
+ taskID, hasTaskID := eventTaskID(e)
+ sessionID, err := util.ParseUUID(e.ChatSessionID)
+ if err != nil || !sessionID.Valid {
+ if !viaTask || !hasTaskID {
+ return nil, nil
+ }
+ taskRow, terr := o.q.GetAgentTask(ctx, taskID)
+ if terr != nil {
+ return nil, fmt.Errorf("load agent task: %w", terr)
+ }
+ if !taskRow.ChatSessionID.Valid {
+ return nil, nil
+ }
+ task = &taskRow
+ sessionID = taskRow.ChatSessionID
+ }
+ binding, err := o.q.GetChannelChatSessionBindingBySession(ctx, db.GetChannelChatSessionBindingBySessionParams{
+ ChatSessionID: sessionID,
+ ChannelType: string(TypeTelegram),
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, nil // not a Telegram session
+ }
+ return nil, fmt.Errorf("lookup telegram chat binding: %w", err)
+ }
+ // A bound session can be reused by web/mobile tasks. Only a task whose
+ // immutable input provenance came from a channel may reply to Telegram;
+ // chat_input_task_id alone cannot distinguish direct tasks from channel
+ // tasks. Fail closed when the task id or provenance lookup is unavailable.
+ if !hasTaskID {
+ return nil, nil
+ }
+ if task == nil {
+ taskRow, terr := o.q.GetAgentTask(ctx, taskID)
+ if terr != nil {
+ return nil, fmt.Errorf("load agent task: %w", terr)
+ }
+ task = &taskRow
+ }
+ deliver, err := engine.TaskInputIsChannelIngested(ctx, o.q, *task)
+ if err != nil {
+ return nil, fmt.Errorf("classify task input origin: %w", err)
+ }
+ if !deliver {
+ return nil, nil
+ }
+ inst, err := o.q.GetChannelInstallation(ctx, db.GetChannelInstallationParams{
+ ID: binding.InstallationID,
+ ChannelType: string(TypeTelegram),
+ })
+ if err != nil {
+ return nil, fmt.Errorf("load telegram installation: %w", err)
+ }
+ if inst.Status != "active" {
+ return nil, nil // revoked between trigger and reply
+ }
+ creds, err := decodeCredentials(inst.Config, o.decrypt)
+ if err != nil {
+ return nil, fmt.Errorf("decode telegram credentials: %w", err)
+ }
+ chatID, threadID, replyTo := outboundTarget(binding)
+ return &replyTarget{
+ streamKey: util.UUIDToString(taskID),
+ botKey: util.UUIDToString(inst.ID),
+ chatID: chatID,
+ threadID: threadID,
+ replyTo: replyTo,
+ botToken: creds.BotToken,
+ }, nil
+}
+
+// outboundTarget recovers the numeric chat id (from the binding config when
+// the binding key is a composite "chat:thread") and the reply thread.
+func outboundTarget(b db.ChannelChatSessionBinding) (chatID, threadID, replyTo int64) {
+ raw := b.ChannelChatID
+ if len(b.Config) > 0 {
+ var cfg telegramBindingConfig
+ if err := json.Unmarshal(b.Config, &cfg); err == nil && cfg.ChatID != "" {
+ raw = cfg.ChatID
+ }
+ }
+ chatID, _ = strconv.ParseInt(raw, 10, 64)
+ if b.LastThreadID.Valid {
+ threadID, _ = strconv.ParseInt(b.LastThreadID.String, 10, 64)
+ }
+ if b.LastMessageID.Valid {
+ replyTo = parseMessageRef(b.LastMessageID.String)
+ }
+ return chatID, threadID, replyTo
+}
+
+func optionalReplyParameters(messageID int64) *replyParameters {
+ if messageID == 0 {
+ return nil
+ }
+ return &replyParameters{MessageID: messageID, AllowSendingWithoutReply: true}
+}
+
+// eventTaskID extracts the task id from the event envelope or payload.
+func eventTaskID(e events.Event) (pgtype.UUID, bool) {
+ raw := e.TaskID
+ if raw == "" {
+ switch p := e.Payload.(type) {
+ case protocol.ChatDonePayload:
+ raw = p.TaskID
+ case map[string]any:
+ raw, _ = p["task_id"].(string)
+ }
+ }
+ id, err := util.ParseUUID(raw)
+ return id, err == nil && id.Valid
+}
+
+// chatDoneContent extracts the reply text from an EventChatDone payload.
+func chatDoneContent(payload any) string {
+ switch p := payload.(type) {
+ case protocol.ChatDonePayload:
+ return p.Content
+ case map[string]any:
+ if s, ok := p["content"].(string); ok {
+ return s
+ }
+ }
+ return ""
+}
+
+// isNotModified reports Telegram's "message is not modified" edit error, which
+// is benign (identical snapshot).
+func isNotModified(err error) bool {
+ var ae *apiError
+ return errors.As(err, &ae) && ae.Code == http.StatusBadRequest &&
+ containsFold(ae.Description, "message is not modified")
+}
+
+func firstNonEmpty(a, b string) string {
+ if a != "" {
+ return a
+ }
+ return b
+}
diff --git a/server/internal/integrations/telegram/outbound_test.go b/server/internal/integrations/telegram/outbound_test.go
new file mode 100644
index 0000000000..553d82bbf7
--- /dev/null
+++ b/server/internal/integrations/telegram/outbound_test.go
@@ -0,0 +1,1369 @@
+package telegram
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+type fakeTelegramOutboundQueries struct {
+ task db.AgentTaskQueue
+ taskErr error
+ channelOrigin bool
+ originErr error
+ binding db.ChannelChatSessionBinding
+ bindings map[[16]byte]db.ChannelChatSessionBinding
+ installation db.ChannelInstallation
+}
+
+func (f *fakeTelegramOutboundQueries) GetAgentTask(context.Context, pgtype.UUID) (db.AgentTaskQueue, error) {
+ return f.task, f.taskErr
+}
+
+func (f *fakeTelegramOutboundQueries) TaskHasChannelIngestedMessages(context.Context, pgtype.UUID) (bool, error) {
+ return f.channelOrigin, f.originErr
+}
+
+func (f *fakeTelegramOutboundQueries) GetChannelChatSessionBindingBySession(_ context.Context, arg db.GetChannelChatSessionBindingBySessionParams) (db.ChannelChatSessionBinding, error) {
+ if binding, ok := f.bindings[arg.ChatSessionID.Bytes]; ok {
+ return binding, nil
+ }
+ return f.binding, nil
+}
+
+func (f *fakeTelegramOutboundQueries) GetChannelInstallation(context.Context, db.GetChannelInstallationParams) (db.ChannelInstallation, error) {
+ return f.installation, nil
+}
+
+func telegramTestUUID(b byte) pgtype.UUID {
+ var id pgtype.UUID
+ id.Bytes[0] = b
+ id.Valid = true
+ return id
+}
+
+func telegramTestTask() db.AgentTaskQueue {
+ return db.AgentTaskQueue{
+ ChatSessionID: telegramTestUUID(3),
+ ChatInputTaskID: telegramTestUUID(4),
+ }
+}
+
+func telegramTestEvent() events.Event {
+ return events.Event{
+ TaskID: "00000000-0000-0000-0000-000000000002",
+ ChatSessionID: "00000000-0000-0000-0000-000000000003",
+ Type: protocol.EventChatDone,
+ Payload: protocol.ChatDonePayload{
+ TaskID: "00000000-0000-0000-0000-000000000002",
+ ChatSessionID: "00000000-0000-0000-0000-000000000003",
+ Content: "reply",
+ },
+ }
+}
+
+func telegramTestEventFor(sessionByte, taskByte byte, content string) events.Event {
+ sessionID := fmt.Sprintf("00000000-0000-0000-0000-%012x", sessionByte)
+ taskID := fmt.Sprintf("00000000-0000-0000-0000-%012x", taskByte)
+ return events.Event{
+ TaskID: taskID, ChatSessionID: sessionID, Type: protocol.EventChatDone,
+ Payload: protocol.ChatDonePayload{TaskID: taskID, ChatSessionID: sessionID, Content: content},
+ }
+}
+
+func sendTerminalReplySynchronouslyForTest(ctx context.Context, o *Outbound, e events.Event) error {
+ reply := &terminalReply{event: e, byteSize: len(chatDoneContent(e.Payload))}
+ for {
+ result := o.sendNextTerminalRequest(ctx, reply)
+ if result.done {
+ o.cleanupTerminalReply(reply)
+ return result.err
+ }
+ if delay := result.retryAt.Sub(o.now()); delay > 0 {
+ if err := o.wait(ctx, delay); err != nil {
+ o.cleanupTerminalReply(reply)
+ return err
+ }
+ }
+ }
+}
+
+func telegramTestBinding(chatID int64) db.ChannelChatSessionBinding {
+ return db.ChannelChatSessionBinding{
+ InstallationID: telegramTestUUID(1),
+ ChannelChatID: strconv.FormatInt(chatID, 10),
+ Config: []byte(fmt.Sprintf(`{"chat_id":"%d"}`, chatID)),
+ LastMessageID: pgtype.Text{String: fmt.Sprintf("%d:17", chatID), Valid: true},
+ }
+}
+
+func newTelegramOutboundQueries() *fakeTelegramOutboundQueries {
+ return &fakeTelegramOutboundQueries{
+ task: telegramTestTask(),
+ binding: db.ChannelChatSessionBinding{
+ InstallationID: telegramTestUUID(1),
+ ChannelChatID: "42",
+ Config: []byte(`{"chat_id":"42"}`),
+ LastMessageID: pgtype.Text{String: "42:17", Valid: true},
+ },
+ installation: db.ChannelInstallation{
+ ID: telegramTestUUID(1),
+ Status: "active",
+ Config: []byte(`{"bot_token_encrypted":"MTIzOnNlY3JldA=="}`),
+ },
+ }
+}
+
+func TestResolveTargetFailsClosedWhenTaskLookupFails(t *testing.T) {
+ q := newTelegramOutboundQueries()
+ q.taskErr = errors.New("database unavailable")
+ o := NewOutbound(q, nil, "", nil, nil)
+
+ if _, err := o.resolveTarget(context.Background(), telegramTestEvent(), false); err == nil {
+ t.Fatal("expected task lookup error")
+ }
+}
+
+func TestResolveTargetSkipsDirectTaskOnBoundTelegramSession(t *testing.T) {
+ q := newTelegramOutboundQueries()
+ o := NewOutbound(q, nil, "", nil, nil)
+
+ target, err := o.resolveTarget(context.Background(), telegramTestEvent(), false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if target != nil {
+ t.Fatalf("target = %+v, want nil for a direct task", target)
+ }
+}
+
+func TestResolveTargetDeliversChannelTaskReply(t *testing.T) {
+ q := newTelegramOutboundQueries()
+ q.channelOrigin = true
+ o := NewOutbound(q, nil, "", nil, nil)
+
+ target, err := o.resolveTarget(context.Background(), telegramTestEvent(), false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if target == nil || target.chatID != 42 || target.replyTo != 17 || target.botToken != "123:secret" || target.streamKey != telegramTestEvent().TaskID {
+ t.Fatalf("target = %+v", target)
+ }
+}
+
+func TestResolveTargetIsolatesConcurrentTasksInOneSession(t *testing.T) {
+ q := newTelegramOutboundQueries()
+ q.channelOrigin = true
+ o := NewOutbound(q, nil, "", nil, nil)
+
+ first := telegramTestEvent()
+ second := telegramTestEvent()
+ second.TaskID = "00000000-0000-0000-0000-000000000005"
+ second.Payload = protocol.ChatDonePayload{
+ TaskID: second.TaskID, ChatSessionID: second.ChatSessionID, Content: "second",
+ }
+
+ target1, err := o.resolveTarget(context.Background(), first, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ target2, err := o.resolveTarget(context.Background(), second, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if target1.streamKey == target2.streamKey {
+ t.Fatalf("concurrent tasks share stream key %q", target1.streamKey)
+ }
+}
+
+func TestValidateBindingTokenChannel(t *testing.T) {
+ if err := validateBindingTokenChannel(db.ChannelBindingToken{ChannelType: string(TypeTelegram)}); err != nil {
+ t.Fatalf("telegram token rejected: %v", err)
+ }
+ if err := validateBindingTokenChannel(db.ChannelBindingToken{ChannelType: "slack"}); !errors.Is(err, ErrBindingTokenInvalid) {
+ t.Fatalf("foreign token error = %v, want ErrBindingTokenInvalid", err)
+ }
+}
+
+func TestOutboundStreamsBySendingThenEditingTheSameQuotedMessage(t *testing.T) {
+ type requestRecord struct {
+ method string
+ body map[string]any
+ }
+ var requests []requestRecord
+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var body map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Errorf("decode %s request: %v", r.URL.Path, err)
+ http.Error(w, "bad test request", http.StatusBadRequest)
+ return
+ }
+ method := r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:]
+ requests = append(requests, requestRecord{method: method, body: body})
+ w.Header().Set("Content-Type", "application/json")
+ if method == "sendMessage" {
+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":99,"chat":{"id":42,"type":"private"},"date":0,"text":"hello"}}`))
+ return
+ }
+ _, _ = w.Write([]byte(`{"ok":true,"result":true}`))
+ }))
+ defer api.Close()
+
+ q := newTelegramOutboundQueries()
+ q.channelOrigin = true
+ o := NewOutbound(q, nil, api.URL, api.Client(), nil)
+ taskID := telegramTestEvent().TaskID
+ partial := events.Event{
+ TaskID: taskID,
+ Type: protocol.EventTaskMessage,
+ Payload: protocol.TaskMessagePayload{
+ TaskID: taskID,
+ Type: "text",
+ Content: "hello",
+ },
+ }
+
+ o.handleTaskMessage(partial)
+ if len(requests) != 1 || requests[0].method != "sendMessage" {
+ t.Fatalf("first partial requests = %+v", requests)
+ }
+ reply, ok := requests[0].body["reply_parameters"].(map[string]any)
+ if !ok || reply["message_id"] != float64(17) {
+ t.Fatalf("first partial reply_parameters = %#v", requests[0].body["reply_parameters"])
+ }
+
+ o.mu.Lock()
+ schedule := o.streams[taskID].schedule
+ o.mu.Unlock()
+ schedule.mu.Lock()
+ schedule.lastEdit = time.Time{}
+ schedule.mu.Unlock()
+ partial.Payload = protocol.TaskMessagePayload{
+ TaskID: taskID,
+ Type: "text",
+ Content: " world",
+ }
+ o.handleTaskMessage(partial)
+ if len(requests) != 2 || requests[1].method != "editMessageText" {
+ t.Fatalf("second partial requests = %+v", requests)
+ }
+ if requests[1].body["message_id"] != float64(99) || requests[1].body["text"] != "hello world" {
+ t.Fatalf("second partial body = %#v", requests[1].body)
+ }
+
+ done := telegramTestEvent()
+ done.Payload = protocol.ChatDonePayload{
+ TaskID: taskID,
+ ChatSessionID: done.ChatSessionID,
+ Content: "hello world!",
+ }
+ schedule.mu.Lock()
+ schedule.lastEdit = time.Time{}
+ schedule.mu.Unlock()
+ if err := sendTerminalReplySynchronouslyForTest(context.Background(), o, done); err != nil {
+ t.Fatalf("finish chat: %v", err)
+ }
+ if len(requests) != 3 || requests[2].method != "editMessageText" {
+ t.Fatalf("final requests = %+v", requests)
+ }
+ if requests[2].body["message_id"] != float64(99) || requests[2].body["text"] != "hello world!" {
+ t.Fatalf("final body = %#v", requests[2].body)
+ }
+ if _, exists := o.streams[taskID]; exists {
+ t.Fatal("completed stream state was not cleared")
+ }
+}
+
+func TestOutboundThrottlesConcurrentTasksPerChat(t *testing.T) {
+ var requests int
+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests++
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":99,"chat":{"id":42,"type":"private"},"date":0,"text":"hello"}}`))
+ }))
+ defer api.Close()
+
+ q := newTelegramOutboundQueries()
+ q.channelOrigin = true
+ o := NewOutbound(q, nil, api.URL, api.Client(), nil)
+ first := telegramTestEvent().TaskID
+ second := "00000000-0000-0000-0000-000000000005"
+ for _, taskID := range []string{first, second} {
+ o.handleTaskMessage(events.Event{
+ TaskID: taskID, Type: protocol.EventTaskMessage,
+ Payload: protocol.TaskMessagePayload{TaskID: taskID, Type: "text", Content: taskID},
+ })
+ }
+ if requests != 1 {
+ t.Fatalf("same-chat concurrent partial requests = %d, want 1", requests)
+ }
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ if o.streams[first] == nil || o.streams[second] == nil ||
+ o.streams[first].schedule != o.streams[second].schedule {
+ t.Fatal("concurrent tasks did not share a chat schedule")
+ }
+}
+
+func TestOutboundCancellationClearsStateAndKeepsPartialMessage(t *testing.T) {
+ o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)
+ taskID := telegramTestEvent().TaskID
+ o.mu.Lock()
+ schedule := o.retainChatLocked("bot-a", 42)
+ o.streams[taskID] = &streamState{chatID: 42, messageID: 99, accumulated: "partial", schedule: schedule}
+ o.mu.Unlock()
+
+ bus := events.New()
+ o.Register(bus)
+ bus.Publish(events.Event{Type: protocol.EventTaskCancelled, TaskID: taskID})
+
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ if _, exists := o.streams[taskID]; exists {
+ t.Fatal("cancelled stream state was not cleared")
+ }
+ if got := o.chats[chatScheduleKey{botKey: "bot-a", chatID: 42}]; got != schedule || got.refs != 0 {
+ t.Fatalf("cancelled chat schedule = %+v, want retained idle schedule", got)
+ }
+}
+
+func TestOutboundRetainsScheduleAcrossSequentialTasks(t *testing.T) {
+ o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)
+ current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)
+ o.now = func() time.Time { return current }
+
+ o.mu.Lock()
+ first := o.retainChatLocked("bot-a", 42)
+ o.releaseChatLocked(first, 42)
+ second := o.retainChatLocked("bot-a", 42)
+ o.mu.Unlock()
+
+ if first != second {
+ t.Fatal("sequential tasks in one chat did not reuse the rate-limit schedule")
+ }
+}
+
+func TestOutboundExpiresIdleScheduleAfterTTL(t *testing.T) {
+ o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)
+ current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)
+ o.now = func() time.Time { return current }
+
+ o.mu.Lock()
+ first := o.retainChatLocked("bot-a", 42)
+ o.releaseChatLocked(first, 42)
+ current = current.Add(chatScheduleIdleTTL)
+ second := o.retainChatLocked("bot-a", 42)
+ o.mu.Unlock()
+
+ if first == second {
+ t.Fatal("expired idle chat schedule was reused")
+ }
+}
+
+func TestOutboundCancellationPreservesActiveRetryAfter(t *testing.T) {
+ o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)
+ current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)
+ o.now = func() time.Time { return current }
+ taskID := telegramTestEvent().TaskID
+ backoffTill := current.Add(30 * time.Second)
+
+ o.mu.Lock()
+ schedule := o.retainChatLocked("bot-a", 42)
+ o.mu.Unlock()
+ schedule.mu.Lock()
+ schedule.setBackoffTill(backoffTill)
+ schedule.mu.Unlock()
+ o.mu.Lock()
+ o.streams[taskID] = &streamState{chatID: 42, schedule: schedule}
+ o.mu.Unlock()
+
+ o.handleTaskCancelled(events.Event{Type: protocol.EventTaskCancelled, TaskID: taskID})
+
+ o.mu.Lock()
+ reused := o.retainChatLocked("bot-a", 42)
+ o.mu.Unlock()
+ if reused != schedule || !reused.backoffTill.Equal(backoffTill) {
+ t.Fatalf("retry_after schedule was discarded on cancellation: got %+v", reused)
+ }
+}
+
+func TestOutboundChatScheduleCacheIsBounded(t *testing.T) {
+ o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)
+ current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)
+ o.now = func() time.Time { return current }
+
+ o.mu.Lock()
+ for chatID := int64(1); chatID <= maxChatSchedules+10; chatID++ {
+ schedule := o.retainChatLocked("bot-a", chatID)
+ o.releaseChatLocked(schedule, chatID)
+ }
+ idleCount := len(o.chats)
+ o.mu.Unlock()
+ if idleCount > maxChatSchedules {
+ t.Fatalf("idle chat schedule cache size = %d, want <= %d", idleCount, maxChatSchedules)
+ }
+}
+
+func TestOutboundIdleSchedulePreservesBackoffBeyondTTL(t *testing.T) {
+ o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)
+ current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)
+ o.now = func() time.Time { return current }
+
+ o.mu.Lock()
+ schedule := o.retainChatLocked("bot-a", 42)
+ o.mu.Unlock()
+ schedule.mu.Lock()
+ schedule.setBackoffTill(current.Add(chatScheduleIdleTTL + time.Minute))
+ schedule.mu.Unlock()
+ o.mu.Lock()
+ o.releaseChatLocked(schedule, 42)
+ current = current.Add(chatScheduleIdleTTL)
+ reused := o.retainChatLocked("bot-a", 42)
+ o.mu.Unlock()
+
+ if reused != schedule {
+ t.Fatal("active retry_after schedule was evicted at the idle TTL")
+ }
+}
+
+func TestOutboundCapacityPruningPreservesActiveBackoff(t *testing.T) {
+ o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)
+ current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)
+ o.now = func() time.Time { return current }
+
+ o.mu.Lock()
+ protected := o.retainChatLocked("bot-a", 1)
+ o.releaseChatLocked(protected, 1)
+ current = current.Add(time.Nanosecond)
+ for chatID := int64(2); chatID <= maxChatSchedules; chatID++ {
+ schedule := o.retainChatLocked("bot-a", chatID)
+ if schedule == nil {
+ o.mu.Unlock()
+ t.Fatalf("fill chat %d returned nil", chatID)
+ }
+ o.releaseChatLocked(schedule, chatID)
+ }
+ o.mu.Unlock()
+ protected.mu.Lock()
+ protected.setBackoffTill(current.Add(time.Hour))
+ protected.mu.Unlock()
+ current = current.Add(editInterval)
+
+ o.mu.Lock()
+ for chatID := int64(maxChatSchedules + 1); chatID <= maxChatSchedules+20; chatID++ {
+ schedule := o.retainChatLocked("bot-a", chatID)
+ if schedule == nil {
+ o.mu.Unlock()
+ t.Fatalf("retain chat %d returned nil", chatID)
+ }
+ o.releaseChatLocked(schedule, chatID)
+ }
+ retained := o.chats[chatScheduleKey{botKey: "bot-a", chatID: 1}]
+ o.mu.Unlock()
+
+ if retained != protected {
+ t.Fatal("capacity pruning evicted a schedule with active retry_after")
+ }
+ if got := len(o.chats); got != maxChatSchedules {
+ t.Fatalf("chat schedule cache size = %d, want %d", got, maxChatSchedules)
+ }
+}
+
+func TestOutboundCapacityEvictionPreservesRecentChatCooldown(t *testing.T) {
+ current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)
+ tests := []struct {
+ name string
+ idleFor time.Duration
+ backoffFor time.Duration
+ wantRoom bool
+ }{
+ {name: "cooldown without retry after", idleFor: editInterval - time.Millisecond},
+ {name: "retry after shorter than cooldown", idleFor: time.Second, backoffFor: time.Second},
+ {name: "cooldown elapsed", idleFor: editInterval, backoffFor: time.Second, wantRoom: true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)
+ candidateKey := chatScheduleKey{botKey: "bot-a", chatID: 1}
+ candidate := &chatSchedule{key: candidateKey, idleSince: current.Add(-tt.idleFor)}
+ if tt.backoffFor > 0 {
+ candidate.mu.Lock()
+ candidate.setBackoffTill(current.Add(tt.backoffFor))
+ candidate.mu.Unlock()
+ }
+ o.chats[candidateKey] = candidate
+ for chatID := int64(2); chatID <= maxChatSchedules; chatID++ {
+ key := chatScheduleKey{botKey: "bot-a", chatID: chatID}
+ o.chats[key] = &chatSchedule{key: key, refs: 1}
+ }
+
+ o.mu.Lock()
+ gotRoom := o.makeChatScheduleRoomLocked(current)
+ _, retained := o.chats[candidateKey]
+ o.mu.Unlock()
+ if gotRoom != tt.wantRoom {
+ t.Fatalf("make room = %v, want %v", gotRoom, tt.wantRoom)
+ }
+ if retained == tt.wantRoom {
+ t.Fatalf("candidate retained = %v, want %v", retained, !tt.wantRoom)
+ }
+ })
+ }
+}
+
+func TestOutboundManyActiveBackoffsKeepTotalScheduleCacheBounded(t *testing.T) {
+ o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)
+ current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)
+ o.now = func() time.Time { return current }
+
+ for chatID := int64(1); chatID <= maxChatSchedules+64; chatID++ {
+ o.mu.Lock()
+ schedule := o.retainChatLocked("bot-a", chatID)
+ o.mu.Unlock()
+ if schedule == nil {
+ t.Fatalf("schedule %d was refused despite compressible idle backoff entries", chatID)
+ }
+ schedule.mu.Lock()
+ schedule.setBackoffTill(current.Add(time.Hour + time.Duration(chatID)*time.Second))
+ schedule.mu.Unlock()
+ o.mu.Lock()
+ o.releaseChatLocked(schedule, chatID)
+ o.mu.Unlock()
+ current = current.Add(editInterval)
+ }
+ o.mu.Lock()
+ got := len(o.chats)
+ fallback := o.botFallbackBackoff["bot-a"]
+ o.mu.Unlock()
+
+ if got > maxChatSchedules {
+ t.Fatalf("active-backoff schedule cache size = %d, want <= %d", got, maxChatSchedules)
+ }
+ if !fallback.After(current) {
+ t.Fatal("compressed active backoff was not merged into the bot fallback")
+ }
+}
+
+func TestOutboundCompressedChatInheritsBotFallback(t *testing.T) {
+ o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)
+ current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)
+ o.now = func() time.Time { return current }
+ backoffTill := current.Add(time.Hour)
+
+ for chatID := int64(1); chatID <= maxChatSchedules; chatID++ {
+ o.mu.Lock()
+ schedule := o.retainChatLocked("bot-a", chatID)
+ o.mu.Unlock()
+ schedule.mu.Lock()
+ schedule.setBackoffTill(backoffTill)
+ schedule.mu.Unlock()
+ o.mu.Lock()
+ o.releaseChatLocked(schedule, chatID)
+ o.mu.Unlock()
+ current = current.Add(editInterval)
+ }
+ o.mu.Lock()
+ newSchedule := o.retainChatLocked("bot-a", maxChatSchedules+1)
+ compressed := o.chats[chatScheduleKey{botKey: "bot-a", chatID: 1}] == nil
+ o.mu.Unlock()
+ if newSchedule == nil || !compressed {
+ t.Fatal("oldest active schedule was not compressed to make room")
+ }
+ o.releaseChat(newSchedule, maxChatSchedules+1)
+ o.mu.Lock()
+ recreated := o.retainChatLocked("bot-a", 1)
+ o.mu.Unlock()
+ if recreated == nil {
+ t.Fatal("compressed chat schedule was not recreated")
+ }
+
+ recreated.mu.Lock()
+ available := o.terminalAvailableAt(recreated, "bot-a", current)
+ recreated.mu.Unlock()
+ if available.Before(backoffTill) {
+ t.Fatalf("compressed chat fallback available at %s, want >= %s", available, backoffTill)
+ }
+ o.releaseChat(recreated, 1)
+}
+
+func TestOutboundExpiredBotFallbackIsRemoved(t *testing.T) {
+ o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)
+ current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)
+ o.mu.Lock()
+ o.botFallbackBackoff["bot-a"] = current.Add(time.Minute)
+ o.mu.Unlock()
+
+ current = current.Add(time.Minute)
+ if got := o.botFallbackTill("bot-a", current); !got.IsZero() {
+ t.Fatalf("expired bot fallback = %s, want zero", got)
+ }
+ o.mu.Lock()
+ _, exists := o.botFallbackBackoff["bot-a"]
+ o.mu.Unlock()
+ if exists {
+ t.Fatal("expired bot fallback remained resident")
+ }
+}
+
+func TestOutboundBotFallbackDoesNotThrottleAnotherInstallation(t *testing.T) {
+ o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)
+ current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)
+ o.mu.Lock()
+ o.botFallbackBackoff["bot-a"] = current.Add(time.Hour)
+ o.mu.Unlock()
+ schedule := &chatSchedule{key: chatScheduleKey{botKey: "bot-b", chatID: 42}}
+
+ schedule.mu.Lock()
+ available := o.terminalAvailableAt(schedule, "bot-b", current)
+ schedule.mu.Unlock()
+ if available.After(current) {
+ t.Fatalf("bot-b was delayed by bot-a fallback until %s", available)
+ }
+}
+
+func TestOutboundCompletionWaitsForRetryAfterBackoff(t *testing.T) {
+ var methods []string
+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ method := r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:]
+ methods = append(methods, method)
+ w.Header().Set("Content-Type", "application/json")
+ switch len(methods) {
+ case 1:
+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":99,"chat":{"id":42,"type":"private"},"date":0,"text":"hello"}}`))
+ case 2:
+ _, _ = w.Write([]byte(`{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":2}}`))
+ default:
+ _, _ = w.Write([]byte(`{"ok":true,"result":true}`))
+ }
+ }))
+ defer api.Close()
+
+ q := newTelegramOutboundQueries()
+ q.channelOrigin = true
+ o := NewOutbound(q, nil, api.URL, api.Client(), nil)
+ current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)
+ o.now = func() time.Time { return current }
+ var waited []time.Duration
+ o.wait = func(_ context.Context, delay time.Duration) error {
+ waited = append(waited, delay)
+ current = current.Add(delay)
+ return nil
+ }
+ taskID := telegramTestEvent().TaskID
+ partial := events.Event{
+ TaskID: taskID, Type: protocol.EventTaskMessage,
+ Payload: protocol.TaskMessagePayload{TaskID: taskID, Type: "text", Content: "hello"},
+ }
+ o.handleTaskMessage(partial)
+ current = current.Add(3 * time.Second)
+ partial.Payload = protocol.TaskMessagePayload{TaskID: taskID, Type: "text", Content: " world"}
+ o.handleTaskMessage(partial)
+
+ done := telegramTestEvent()
+ done.Payload = protocol.ChatDonePayload{
+ TaskID: taskID, ChatSessionID: done.ChatSessionID, Content: "hello world!",
+ }
+ if err := sendTerminalReplySynchronouslyForTest(context.Background(), o, done); err != nil {
+ t.Fatalf("finish chat after 429: %v", err)
+ }
+ if strings.Join(methods, ",") != "sendMessage,editMessageText,editMessageText" {
+ t.Fatalf("methods = %v", methods)
+ }
+ if len(waited) != 1 || waited[0] != 2*time.Second {
+ t.Fatalf("backoff waits = %v, want [2s]", waited)
+ }
+}
+
+func TestOutboundTerminalWorkerDeliversLongMultiChunkReply(t *testing.T) {
+ var requests int
+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests++
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":99,"chat":{"id":42,"type":"private"},"date":0,"text":"ok"}}`))
+ }))
+ defer api.Close()
+
+ q := newTelegramOutboundQueries()
+ q.channelOrigin = true
+ o := NewOutbound(q, nil, api.URL, api.Client(), nil)
+ current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)
+ o.now = func() time.Time { return current }
+ var simulatedElapsed time.Duration
+ o.wait = func(ctx context.Context, delay time.Duration) error {
+ deadline, ok := ctx.Deadline()
+ if ok && simulatedElapsed+delay > time.Until(deadline) {
+ return context.DeadlineExceeded
+ }
+ simulatedElapsed += delay
+ current = current.Add(delay)
+ return nil
+ }
+
+ done := telegramTestEvent()
+ content := strings.Repeat("x", maxMessageUnits*8)
+ done.Payload = protocol.ChatDonePayload{
+ TaskID: done.TaskID, ChatSessionID: done.ChatSessionID, Content: content,
+ }
+ if err := sendTerminalReplySynchronouslyForTest(context.Background(), o, done); err != nil {
+ t.Fatalf("finish long reply: %v", err)
+ }
+
+ if requests != 8 {
+ t.Fatalf("terminal chunk requests = %d, want 8", requests)
+ }
+}
+
+func TestOutboundTerminalDeliveryHasNoFixedRetryAfterBudget(t *testing.T) {
+ var requests int
+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests++
+ w.Header().Set("Content-Type", "application/json")
+ if requests == 1 {
+ _, _ = w.Write([]byte(`{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1200}}`))
+ return
+ }
+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":99,"chat":{"id":42,"type":"private"},"date":0,"text":"ok"}}`))
+ }))
+ defer api.Close()
+
+ q := newTelegramOutboundQueries()
+ q.channelOrigin = true
+ o := NewOutbound(q, nil, api.URL, api.Client(), nil)
+ current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)
+ o.now = func() time.Time { return current }
+ var simulatedElapsed time.Duration
+ o.wait = func(ctx context.Context, delay time.Duration) error {
+ deadline, ok := ctx.Deadline()
+ if ok && simulatedElapsed+delay > time.Until(deadline) {
+ return context.DeadlineExceeded
+ }
+ simulatedElapsed += delay
+ current = current.Add(delay)
+ return nil
+ }
+
+ if err := sendTerminalReplySynchronouslyForTest(context.Background(), o, telegramTestEvent()); err != nil {
+ t.Fatalf("finish reply after long retry_after: %v", err)
+ }
+ if requests != 2 {
+ t.Fatalf("terminal retry requests = %d, want 2", requests)
+ }
+ if simulatedElapsed < 20*time.Minute {
+ t.Fatalf("retry_after wait = %s, want at least 20m", simulatedElapsed)
+ }
+}
+
+func TestOutboundChatDoneDoesNotBlockRealtimeFanout(t *testing.T) {
+ requestStarted := make(chan struct{})
+ releaseRequest := make(chan struct{})
+ var startOnce sync.Once
+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ startOnce.Do(func() { close(requestStarted) })
+ <-releaseRequest
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":99,"chat":{"id":42,"type":"private"},"date":0,"text":"ok"}}`))
+ }))
+ defer api.Close()
+
+ q := newTelegramOutboundQueries()
+ q.channelOrigin = true
+ o := NewOutbound(q, nil, api.URL, api.Client(), nil)
+ ctx, cancel := context.WithCancel(context.Background())
+ o.Start(ctx)
+ defer func() {
+ close(releaseRequest)
+ cancel()
+ if !o.WaitWithTimeout(time.Second) {
+ t.Error("terminal workers did not stop")
+ }
+ }()
+
+ bus := events.New()
+ o.Register(bus)
+ realtimeSeen := make(chan struct{})
+ bus.SubscribeAll(func(events.Event) { close(realtimeSeen) })
+ publishReturned := make(chan struct{})
+ go func() {
+ bus.Publish(telegramTestEvent())
+ close(publishReturned)
+ }()
+
+ select {
+ case <-publishReturned:
+ case <-time.After(250 * time.Millisecond):
+ t.Fatal("EventChatDone publish blocked on Telegram delivery")
+ }
+ select {
+ case <-realtimeSeen:
+ case <-time.After(250 * time.Millisecond):
+ t.Fatal("SubscribeAll realtime fanout was blocked by Telegram delivery")
+ }
+ select {
+ case <-requestStarted:
+ case <-time.After(time.Second):
+ t.Fatal("terminal worker did not start Telegram delivery")
+ }
+}
+
+func TestOutboundLegacyLaneCollisionDoesNotBlockAnotherSession(t *testing.T) {
+ first := telegramTestEventFor(3, 2, "blocked")
+ second := telegramTestEventFor(7, 5, "ready")
+ legacyLane := func(key string) int {
+ hash := uint32(2166136261)
+ for i := 0; i < len(key); i++ {
+ hash ^= uint32(key[i])
+ hash *= 16777619
+ }
+ return int(hash % terminalWorkerCount)
+ }
+ if legacyLane(first.ChatSessionID) != legacyLane(second.ChatSessionID) {
+ t.Fatal("test sessions must collide in the removed four-lane scheduler")
+ }
+
+ blockedSeen := make(chan struct{})
+ readySeen := make(chan struct{})
+ var blockedOnce sync.Once
+ var readyOnce sync.Once
+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var body struct {
+ ChatID int64 `json:"chat_id"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Errorf("decode request: %v", err)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ if body.ChatID == 42 {
+ blockedOnce.Do(func() { close(blockedSeen) })
+ _, _ = w.Write([]byte(`{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1200}}`))
+ return
+ }
+ readyOnce.Do(func() { close(readySeen) })
+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":99,"chat":{"id":43,"type":"private"},"date":0,"text":"ready"}}`))
+ }))
+ defer api.Close()
+
+ q := newTelegramOutboundQueries()
+ q.channelOrigin = true
+ q.bindings = map[[16]byte]db.ChannelChatSessionBinding{
+ {15: 3}: telegramTestBinding(42),
+ {15: 7}: telegramTestBinding(43),
+ }
+ o := NewOutbound(q, nil, api.URL, api.Client(), nil)
+ ctx, cancel := context.WithCancel(context.Background())
+ o.Start(ctx)
+ defer func() {
+ cancel()
+ if !o.WaitWithTimeout(time.Second) {
+ t.Error("terminal scheduler did not stop")
+ }
+ }()
+
+ o.enqueueTerminalReply(first)
+ select {
+ case <-blockedSeen:
+ case <-time.After(time.Second):
+ t.Fatal("blocked session did not reach Telegram")
+ }
+ o.enqueueTerminalReply(second)
+ select {
+ case <-readySeen:
+ case <-time.After(time.Second):
+ t.Fatal("unrelated colliding session was blocked by retry_after")
+ }
+}
+
+func TestOutboundSameSessionSecondReplyCannotOvertakeFirst(t *testing.T) {
+ firstStarted := make(chan struct{})
+ releaseFirst := make(chan struct{})
+ secondStarted := make(chan struct{})
+ var firstOnce sync.Once
+ var secondOnce sync.Once
+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var body struct {
+ Text string `json:"text"`
+ }
+ _ = json.NewDecoder(r.Body).Decode(&body)
+ if body.Text == "first" {
+ firstOnce.Do(func() { close(firstStarted) })
+ <-releaseFirst
+ } else if body.Text == "second" {
+ secondOnce.Do(func() { close(secondStarted) })
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":99,"chat":{"id":42,"type":"private"},"date":0,"text":"ok"}}`))
+ }))
+ defer api.Close()
+
+ q := newTelegramOutboundQueries()
+ q.channelOrigin = true
+ o := NewOutbound(q, nil, api.URL, api.Client(), nil)
+ ctx, cancel := context.WithCancel(context.Background())
+ o.Start(ctx)
+ defer func() {
+ select {
+ case <-releaseFirst:
+ default:
+ close(releaseFirst)
+ }
+ cancel()
+ if !o.WaitWithTimeout(time.Second) {
+ t.Error("terminal scheduler did not stop")
+ }
+ }()
+
+ first := telegramTestEventFor(3, 2, "first")
+ second := telegramTestEventFor(3, 5, "second")
+ o.enqueueTerminalReply(first)
+ select {
+ case <-firstStarted:
+ case <-time.After(time.Second):
+ t.Fatal("first reply did not start")
+ }
+ o.enqueueTerminalReply(second)
+ select {
+ case <-secondStarted:
+ t.Fatal("second reply overtook the in-flight first reply")
+ case <-time.After(150 * time.Millisecond):
+ }
+ close(releaseFirst)
+}
+
+func TestOutboundBackoffSessionsDoNotExhaustWorkers(t *testing.T) {
+ backoffSeen := make(chan int64, terminalWorkerCount+2)
+ readySeen := make(chan struct{})
+ var readyOnce sync.Once
+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var body struct {
+ ChatID int64 `json:"chat_id"`
+ }
+ _ = json.NewDecoder(r.Body).Decode(&body)
+ w.Header().Set("Content-Type", "application/json")
+ if body.ChatID != 200 {
+ backoffSeen <- body.ChatID
+ _, _ = w.Write([]byte(`{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1200}}`))
+ return
+ }
+ readyOnce.Do(func() { close(readySeen) })
+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":99,"chat":{"id":200,"type":"private"},"date":0,"text":"ready"}}`))
+ }))
+ defer api.Close()
+
+ q := newTelegramOutboundQueries()
+ q.channelOrigin = true
+ q.bindings = make(map[[16]byte]db.ChannelChatSessionBinding)
+ for i := byte(1); i <= terminalWorkerCount+2; i++ {
+ q.bindings[[16]byte{15: i}] = telegramTestBinding(100 + int64(i))
+ }
+ q.bindings[[16]byte{15: 20}] = telegramTestBinding(200)
+ o := NewOutbound(q, nil, api.URL, api.Client(), nil)
+ ctx, cancel := context.WithCancel(context.Background())
+ o.Start(ctx)
+ defer func() {
+ cancel()
+ if !o.WaitWithTimeout(time.Second) {
+ t.Error("terminal scheduler did not stop")
+ }
+ }()
+
+ for i := byte(1); i <= terminalWorkerCount+2; i++ {
+ o.enqueueTerminalReply(telegramTestEventFor(i, i+30, "backoff"))
+ }
+ for range terminalWorkerCount + 2 {
+ select {
+ case <-backoffSeen:
+ case <-time.After(time.Second):
+ t.Fatal("retry-waiting sessions occupied the fixed workers")
+ }
+ }
+ o.enqueueTerminalReply(telegramTestEventFor(20, 60, "ready"))
+ select {
+ case <-readySeen:
+ case <-time.After(time.Second):
+ t.Fatal("new ready session could not execute after all workers observed 429")
+ }
+}
+
+func TestOutboundShutdownAbandonsQueuedRetryWaitingAndInflightJobs(t *testing.T) {
+ retrySeen := make(chan struct{})
+ inflightSeen := make(chan struct{})
+ var retryOnce sync.Once
+ var inflightOnce sync.Once
+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var body struct {
+ ChatID int64 `json:"chat_id"`
+ }
+ _ = json.NewDecoder(r.Body).Decode(&body)
+ w.Header().Set("Content-Type", "application/json")
+ switch body.ChatID {
+ case 42:
+ retryOnce.Do(func() { close(retrySeen) })
+ _, _ = w.Write([]byte(`{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1200}}`))
+ case 43:
+ inflightOnce.Do(func() { close(inflightSeen) })
+ <-r.Context().Done()
+ default:
+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":99,"chat":{"id":44,"type":"private"},"date":0,"text":"ok"}}`))
+ }
+ }))
+ defer api.Close()
+
+ q := newTelegramOutboundQueries()
+ q.channelOrigin = true
+ q.bindings = map[[16]byte]db.ChannelChatSessionBinding{
+ {15: 3}: telegramTestBinding(42),
+ {15: 7}: telegramTestBinding(43),
+ }
+ o := NewOutbound(q, nil, api.URL, api.Client(), nil)
+ ctx, cancel := context.WithCancel(context.Background())
+ o.Start(ctx)
+ o.enqueueTerminalReply(telegramTestEventFor(3, 2, "retry"))
+ o.enqueueTerminalReply(telegramTestEventFor(7, 5, "inflight"))
+ o.enqueueTerminalReply(telegramTestEventFor(7, 6, "queued"))
+ select {
+ case <-retrySeen:
+ case <-time.After(time.Second):
+ t.Fatal("retry-waiting job was not established")
+ }
+ select {
+ case <-inflightSeen:
+ case <-time.After(time.Second):
+ t.Fatal("in-flight job was not established")
+ }
+
+ cancel()
+ if !o.WaitWithTimeout(time.Second) {
+ t.Fatal("terminal scheduler did not stop")
+ }
+ o.terminalMu.Lock()
+ sessions := len(o.terminalSessions)
+ retries := o.terminalRetries.Len()
+ inflight := o.terminalInFlight
+ stopped := o.terminalStopped
+ o.terminalMu.Unlock()
+ if !stopped || sessions != 0 || retries != 0 || inflight != 0 {
+ t.Fatalf("shutdown state stopped=%v sessions=%d retries=%d inflight=%d", stopped, sessions, retries, inflight)
+ }
+}
+
+func TestOutboundRetryResumesAtFailedChunkWithoutRepeatingSuccess(t *testing.T) {
+ var sequence []byte
+ var requests atomic.Int32
+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var body struct {
+ Text string `json:"text"`
+ }
+ _ = json.NewDecoder(r.Body).Decode(&body)
+ sequence = append(sequence, body.Text[0])
+ request := requests.Add(1)
+ w.Header().Set("Content-Type", "application/json")
+ if request == 2 {
+ _, _ = w.Write([]byte(`{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1200}}`))
+ return
+ }
+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":99,"chat":{"id":42,"type":"private"},"date":0,"text":"ok"}}`))
+ }))
+ defer api.Close()
+
+ q := newTelegramOutboundQueries()
+ q.channelOrigin = true
+ o := NewOutbound(q, nil, api.URL, api.Client(), nil)
+ current := time.Date(2026, 8, 18, 0, 0, 0, 0, time.UTC)
+ o.now = func() time.Time { return current }
+ o.wait = func(_ context.Context, delay time.Duration) error {
+ current = current.Add(delay)
+ return nil
+ }
+ e := telegramTestEvent()
+ e.Payload = protocol.ChatDonePayload{
+ TaskID: e.TaskID, ChatSessionID: e.ChatSessionID,
+ Content: strings.Repeat("A", maxMessageUnits) + strings.Repeat("B", maxMessageUnits) + "C",
+ }
+ if err := sendTerminalReplySynchronouslyForTest(context.Background(), o, e); err != nil {
+ t.Fatalf("finish chunked reply: %v", err)
+ }
+ if got := string(sequence); got != "ABBC" {
+ t.Fatalf("chunk request sequence = %q, want ABBC", got)
+ }
+}
+
+func TestOutboundTerminalSchedulerPreservesSessionFIFO(t *testing.T) {
+ o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)
+ first := telegramTestEvent()
+ second := telegramTestEvent()
+ second.TaskID = "00000000-0000-0000-0000-000000000005"
+ second.Payload = protocol.ChatDonePayload{
+ TaskID: second.TaskID, ChatSessionID: second.ChatSessionID, Content: "second",
+ }
+
+ o.enqueueTerminalReply(first)
+ o.enqueueTerminalReply(second)
+ o.terminalMu.Lock()
+ session := o.terminalSessions[first.ChatSessionID]
+ o.terminalMu.Unlock()
+ if session == nil || len(session.queue) != 2 {
+ t.Fatalf("terminal session queue = %+v, want 2 jobs", session)
+ }
+ if session.queue[0].event.TaskID != first.TaskID || session.queue[1].event.TaskID != second.TaskID {
+ t.Fatalf("terminal FIFO = [%s, %s], want [%s, %s]",
+ session.queue[0].event.TaskID, session.queue[1].event.TaskID, first.TaskID, second.TaskID)
+ }
+}
+
+func TestOutboundRejectsSixtyFifthQueuedTerminalReply(t *testing.T) {
+ o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)
+ for i := byte(0); i < maxQueuedTerminalReplies; i++ {
+ sessionByte := i/byte(maxQueuedTerminalRepliesPerSession) + 1
+ o.enqueueTerminalReply(telegramTestEventFor(sessionByte, i+20, "queued"))
+ }
+ rejected := telegramTestEventFor(20, 100, "rejected")
+ o.enqueueTerminalReply(rejected)
+
+ o.terminalMu.Lock()
+ count := o.queuedTerminalReplyCount
+ _, rejectedSessionExists := o.terminalSessions[rejected.ChatSessionID]
+ o.terminalMu.Unlock()
+ if count != maxQueuedTerminalReplies || rejectedSessionExists {
+ t.Fatalf("queued replies = %d, rejected session exists = %v", count, rejectedSessionExists)
+ }
+}
+
+func TestOutboundRejectsNinthQueuedTerminalReplyInSession(t *testing.T) {
+ o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)
+ for i := byte(0); i < maxQueuedTerminalRepliesPerSession; i++ {
+ o.enqueueTerminalReply(telegramTestEventFor(3, i+20, "queued"))
+ }
+ o.enqueueTerminalReply(telegramTestEventFor(3, 100, "rejected"))
+
+ o.terminalMu.Lock()
+ session := o.terminalSessions[telegramTestEventFor(3, 20, "").ChatSessionID]
+ count := o.queuedTerminalReplyCount
+ o.terminalMu.Unlock()
+ if session == nil || len(session.queue) != maxQueuedTerminalRepliesPerSession || count != maxQueuedTerminalRepliesPerSession {
+ t.Fatalf("session queue = %v, total = %d", session, count)
+ }
+}
+
+func TestOutboundRejectsTerminalReplyBeyondByteLimit(t *testing.T) {
+ o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)
+ e := telegramTestEventFor(3, 2, strings.Repeat("x", maxQueuedTerminalReplyBytes+1))
+ o.enqueueTerminalReply(e)
+
+ o.terminalMu.Lock()
+ count := o.queuedTerminalReplyCount
+ bytes := o.queuedTerminalReplyBytes
+ o.terminalMu.Unlock()
+ if count != 0 || bytes != 0 {
+ t.Fatalf("rejected payload consumed capacity: count=%d bytes=%d", count, bytes)
+ }
+}
+
+func TestOutboundCompletedTerminalReplyReleasesCapacityImmediately(t *testing.T) {
+ o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)
+ e := telegramTestEventFor(3, 2, "reply")
+ o.enqueueTerminalReply(e)
+
+ o.terminalMu.Lock()
+ session := o.terminalSessions[e.ChatSessionID]
+ reply := session.queue[0]
+ session.ready = false
+ session.running = true
+ o.terminalInFlight = 1
+ o.terminalMu.Unlock()
+ o.updateQueueAfterTerminalRequest(terminalResult{
+ terminalWork: terminalWork{sessionID: e.ChatSessionID, reply: reply},
+ done: true,
+ })
+
+ o.terminalMu.Lock()
+ count := o.queuedTerminalReplyCount
+ bytes := o.queuedTerminalReplyBytes
+ o.terminalMu.Unlock()
+ if count != 0 || bytes != 0 {
+ t.Fatalf("completed reply retained capacity: count=%d bytes=%d", count, bytes)
+ }
+}
+
+func TestOutboundShutdownClearsTerminalReplyCapacity(t *testing.T) {
+ o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)
+ o.enqueueTerminalReply(telegramTestEventFor(3, 2, "first"))
+ o.enqueueTerminalReply(telegramTestEventFor(7, 5, "second"))
+ o.stopTerminalScheduler()
+
+ o.terminalMu.Lock()
+ count := o.queuedTerminalReplyCount
+ bytes := o.queuedTerminalReplyBytes
+ sessions := len(o.terminalSessions)
+ o.terminalMu.Unlock()
+ if count != 0 || bytes != 0 || sessions != 0 {
+ t.Fatalf("shutdown state count=%d bytes=%d sessions=%d", count, bytes, sessions)
+ }
+}
+
+func TestOutboundRejectedTerminalReplyReleasesStreamSchedule(t *testing.T) {
+ var logs bytes.Buffer
+ logger := slog.New(slog.NewTextHandler(&logs, nil))
+ o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, logger)
+ e := telegramTestEventFor(3, 2, "rejected")
+ schedule := &chatSchedule{key: chatScheduleKey{botKey: "bot", chatID: 42}, refs: 1}
+ o.streams[e.TaskID] = &streamState{chatID: 42, schedule: schedule}
+ o.chats[schedule.key] = schedule
+ o.queuedTerminalReplyCount = maxQueuedTerminalReplies
+
+ o.enqueueTerminalReply(e)
+ o.mu.Lock()
+ _, streamExists := o.streams[e.TaskID]
+ refs := schedule.refs
+ o.mu.Unlock()
+ if streamExists || refs != 0 {
+ t.Fatalf("rejected reply retained stream=%v schedule refs=%d", streamExists, refs)
+ }
+ logOutput := logs.String()
+ if !strings.Contains(logOutput, "level=ERROR") || !strings.Contains(logOutput, e.TaskID) || !strings.Contains(logOutput, e.ChatSessionID) {
+ t.Fatalf("rejection log lacks error level or identity: %s", logOutput)
+ }
+}
+
+func TestOutboundEmptyTerminalReplySkipsQueueAndClearsStream(t *testing.T) {
+ o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, nil)
+ e := telegramTestEventFor(3, 2, "")
+ schedule := &chatSchedule{key: chatScheduleKey{botKey: "bot", chatID: 42}, refs: 1}
+ o.streams[e.TaskID] = &streamState{chatID: 42, schedule: schedule}
+ o.chats[schedule.key] = schedule
+
+ o.enqueueTerminalReply(e)
+ o.terminalMu.Lock()
+ count := o.queuedTerminalReplyCount
+ o.terminalMu.Unlock()
+ o.mu.Lock()
+ _, streamExists := o.streams[e.TaskID]
+ refs := schedule.refs
+ o.mu.Unlock()
+ if count != 0 || streamExists || refs != 0 {
+ t.Fatalf("empty reply count=%d stream=%v schedule refs=%d", count, streamExists, refs)
+ }
+}
+
+func TestOutboundInvalidTerminalReplyIdentityFailsFast(t *testing.T) {
+ var logs bytes.Buffer
+ logger := slog.New(slog.NewTextHandler(&logs, nil))
+ o := NewOutbound(newTelegramOutboundQueries(), nil, "", nil, logger)
+ e := telegramTestEvent()
+ e.TaskID = "invalid-task"
+ e.ChatSessionID = "invalid-session"
+ o.enqueueTerminalReply(e)
+
+ o.terminalMu.Lock()
+ count := o.queuedTerminalReplyCount
+ o.terminalMu.Unlock()
+ logOutput := logs.String()
+ if count != 0 || !strings.Contains(logOutput, "level=ERROR") ||
+ !strings.Contains(logOutput, e.TaskID) || !strings.Contains(logOutput, e.ChatSessionID) {
+ t.Fatalf("invalid identity count=%d log=%s", count, logOutput)
+ }
+}
+
+func TestOutboundTerminalReplyUsesPayloadTaskIDFromProductionEvent(t *testing.T) {
+ delivered := make(chan struct{})
+ var deliveredOnce sync.Once
+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ deliveredOnce.Do(func() { close(delivered) })
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":99,"chat":{"id":42,"type":"private"},"date":0,"text":"reply"}}`))
+ }))
+ defer api.Close()
+
+ q := newTelegramOutboundQueries()
+ q.channelOrigin = true
+ o := NewOutbound(q, nil, api.URL, api.Client(), nil)
+ ctx, cancel := context.WithCancel(context.Background())
+ o.Start(ctx)
+ defer func() {
+ cancel()
+ if !o.WaitWithTimeout(time.Second) {
+ t.Error("terminal scheduler did not stop")
+ }
+ }()
+
+ e := telegramTestEvent()
+ e.TaskID = ""
+ o.enqueueTerminalReply(e)
+ select {
+ case <-delivered:
+ case <-time.After(time.Second):
+ t.Fatal("terminal reply with payload-only task id was not delivered")
+ }
+}
+
+func TestOutboundRetryPendingFailureCleansStreamWithoutNotice(t *testing.T) {
+ var requests int
+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests++
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"ok":true,"result":true}`))
+ }))
+ defer api.Close()
+
+ q := newTelegramOutboundQueries()
+ q.channelOrigin = true
+ o := NewOutbound(q, nil, api.URL, api.Client(), nil)
+ taskID := telegramTestEvent().TaskID
+ o.mu.Lock()
+ schedule := o.retainChatLocked("bot-a", 42)
+ o.streams[taskID] = &streamState{chatID: 42, messageID: 99, schedule: schedule}
+ o.mu.Unlock()
+
+ o.handleTaskFailed(events.Event{
+ Type: protocol.EventTaskFailed, TaskID: taskID,
+ Payload: map[string]any{"retry_pending": true},
+ })
+
+ o.mu.Lock()
+ _, streamExists := o.streams[taskID]
+ o.mu.Unlock()
+ if streamExists {
+ t.Fatal("retry-pending failure did not clear the old stream")
+ }
+ if requests != 0 {
+ t.Fatalf("retry-pending failure sent %d terminal notices, want 0", requests)
+ }
+}
+
+func TestOutboundTerminalFailureSendsNotice(t *testing.T) {
+ var requests int
+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests++
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":99,"chat":{"id":42,"type":"private"},"date":0,"text":"failed"}}`))
+ }))
+ defer api.Close()
+
+ q := newTelegramOutboundQueries()
+ q.channelOrigin = true
+ o := NewOutbound(q, nil, api.URL, api.Client(), nil)
+ e := telegramTestEvent()
+ e.Type = protocol.EventTaskFailed
+ e.Payload = map[string]any{"retry_pending": false}
+ o.handleTaskFailed(e)
+ if requests != 1 {
+ t.Fatalf("terminal failure requests = %d, want 1", requests)
+ }
+}
diff --git a/server/internal/integrations/telegram/replier.go b/server/internal/integrations/telegram/replier.go
new file mode 100644
index 0000000000..2fd784567c
--- /dev/null
+++ b/server/internal/integrations/telegram/replier.go
@@ -0,0 +1,261 @@
+package telegram
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// This file is the Telegram OutboundReplier — the engine seam that delivers a
+// verdict-driven reply back to the user, mirroring slack/replier.go:
+// - NeedsBinding: mint a single-use binding token, reply with the link to
+// the in-product redeem page (/telegram/bind).
+// - AgentOffline / AgentArchived: a status notice.
+// - FreshPending / IssueUsage: command confirmation or corrective guidance.
+// - Ingested with an /issue result: creation or duplicate confirmation.
+// - Dropped addressed /issue commands: an authorization/status refusal.
+
+const (
+ msgFreshPending = "✅ 已准备开始新对话。你的下一条聊天消息将不带之前的上下文运行。"
+ msgIssueUsage = "请填写任务标题,格式如下:\n\n/issue <标题>\n[描述](可选)"
+ msgIssueNotMember = "你不是该 Multica 工作区的成员,因此无法创建任务。请让工作区管理员邀请你后重试。"
+ msgIssueDisabled = "该 Telegram 机器人未连接到 Multica(或已断开连接)。请让工作区管理员重新连接。"
+)
+
+// bindingMinter is the binding-token surface the replier needs.
+// *BindingTokenService satisfies it.
+type bindingMinter interface {
+ Mint(ctx context.Context, workspaceID, installationID pgtype.UUID, telegramUserID string) (BindingToken, error)
+}
+
+// OutboundReplier implements engine.OutboundReplier for Telegram.
+type OutboundReplier struct {
+ binding bindingMinter
+ decrypt Decrypter
+ appURL string
+ bindingPath string
+ apiBase string
+ client *http.Client
+ logger *slog.Logger
+}
+
+// OutboundReplierConfig configures the replier. Binding + AppURL are required
+// for the NeedsBinding prompt; without them the prompt is skipped (other
+// notices still fire).
+type OutboundReplierConfig struct {
+ Binding bindingMinter
+ Decrypt Decrypter
+ // AppURL is the Multica web app host for the redeem link, same sourcing as
+ // the Slack replier (MULTICA_APP_URL ?? FRONTEND_ORIGIN).
+ AppURL string
+ BindingPath string // default "/telegram/bind"
+ APIBase string
+ HTTPClient *http.Client
+ Logger *slog.Logger
+}
+
+var _ engine.OutboundReplier = (*OutboundReplier)(nil)
+
+// NewOutboundReplier builds the replier.
+func NewOutboundReplier(cfg OutboundReplierConfig) *OutboundReplier {
+ logger := cfg.Logger
+ if logger == nil {
+ logger = slog.Default()
+ }
+ bindingPath := cfg.BindingPath
+ if bindingPath == "" {
+ bindingPath = "/telegram/bind"
+ }
+ if !strings.HasPrefix(bindingPath, "/") {
+ bindingPath = "/" + bindingPath
+ }
+ return &OutboundReplier{
+ binding: cfg.Binding,
+ decrypt: cfg.Decrypt,
+ appURL: strings.TrimRight(cfg.AppURL, "/"),
+ bindingPath: bindingPath,
+ apiBase: cfg.APIBase,
+ client: cfg.HTTPClient,
+ logger: logger,
+ }
+}
+
+// Reply routes each outcome to its user-visible message. Errors are logged,
+// not propagated: the replier runs detached from the inbound ACK path.
+func (r *OutboundReplier) Reply(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, res engine.Result) {
+ switch res.Outcome {
+ case engine.OutcomeNeedsBinding:
+ if err := r.sendBindingPrompt(ctx, inst, msg, res); err != nil {
+ r.logger.WarnContext(ctx, "telegram replier: binding prompt failed",
+ "installation_id", util.UUIDToString(inst.ID), "error", err)
+ }
+ case engine.OutcomeAgentOffline:
+ if err := r.post(ctx, inst, msg, msgAgentOffline); err != nil {
+ r.logger.WarnContext(ctx, "telegram replier: offline notice failed",
+ "installation_id", util.UUIDToString(inst.ID), "error", err)
+ }
+ case engine.OutcomeAgentArchived:
+ if err := r.post(ctx, inst, msg, msgAgentArchived); err != nil {
+ r.logger.WarnContext(ctx, "telegram replier: archived notice failed",
+ "installation_id", util.UUIDToString(inst.ID), "error", err)
+ }
+ case engine.OutcomeFreshPending:
+ if err := r.post(ctx, inst, msg, msgFreshPending); err != nil {
+ r.logger.WarnContext(ctx, "telegram replier: fresh-start confirmation failed",
+ "installation_id", util.UUIDToString(inst.ID), "error", err)
+ }
+ case engine.OutcomeIssueUsage:
+ if err := r.post(ctx, inst, msg, msgIssueUsage); err != nil {
+ r.logger.WarnContext(ctx, "telegram replier: issue usage reply failed",
+ "installation_id", util.UUIDToString(inst.ID), "error", err)
+ }
+ case engine.OutcomeIngested:
+ if res.IssueID.Valid {
+ text := issueCreatedText(res)
+ if res.IssueDuplicate {
+ text = issueDuplicateText(res)
+ }
+ if err := r.post(ctx, inst, msg, text); err != nil {
+ r.logger.WarnContext(ctx, "telegram replier: issue outcome reply failed",
+ "installation_id", util.UUIDToString(inst.ID), "error", err)
+ }
+ }
+ case engine.OutcomeDropped:
+ if text := droppedReplyText(res, msg); text != "" {
+ if err := r.post(ctx, inst, msg, text); err != nil {
+ r.logger.WarnContext(ctx, "telegram replier: drop refusal failed",
+ "installation_id", util.UUIDToString(inst.ID), "error", err)
+ }
+ }
+ }
+}
+
+func (r *OutboundReplier) sendBindingPrompt(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, res engine.Result) error {
+ // A group-visible bearer link can be redeemed by another group member and
+ // would bind the original sender's Telegram identity to the wrong Multica
+ // user. Ask the sender to start a private chat first; only private-chat
+ // prompts carry a redeem token.
+ if msg.Source.ChatType == channel.ChatTypeGroup {
+ return r.post(ctx, inst, msg, msgBindingGroupHint)
+ }
+ sender := res.Sender
+ if sender == "" {
+ sender = msg.Source.SenderID
+ }
+ if sender == "" {
+ return errors.New("missing sender id")
+ }
+ if r.binding == nil {
+ return errors.New("binding service not configured")
+ }
+ if r.appURL == "" {
+ return errors.New("app url not configured")
+ }
+ token, err := r.binding.Mint(ctx, inst.WorkspaceID, inst.ID, sender)
+ if err != nil {
+ return fmt.Errorf("mint binding token: %w", err)
+ }
+ bindURL := r.appURL + r.bindingPath + "?token=" + url.QueryEscape(token.Raw)
+ text := "👋 要开始和我对话,请先绑定你的 Multica 账号:\n" + bindURL + "\n(链接 15 分钟内有效)"
+ return r.post(ctx, inst, msg, text)
+}
+
+// post resolves the installation's bot token from the carried platform row
+// and sends plain text back into the originating chat / topic.
+func (r *OutboundReplier) post(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, text string) error {
+ row, ok := inst.Platform.(db.ChannelInstallation)
+ if !ok {
+ return errors.New("installation platform row unavailable")
+ }
+ creds, err := decodeCredentials(row.Config, r.decrypt)
+ if err != nil {
+ return fmt.Errorf("decode credentials: %w", err)
+ }
+ chatID, err := strconv.ParseInt(msg.Source.ChatID, 10, 64)
+ if err != nil {
+ return fmt.Errorf("bad chat id %q: %w", msg.Source.ChatID, err)
+ }
+ var threadID int64
+ if msg.Source.ThreadID != "" {
+ threadID, _ = strconv.ParseInt(msg.Source.ThreadID, 10, 64)
+ }
+ var reply *replyParameters
+ if messageID := parseMessageRef(msg.MessageID); messageID != 0 {
+ reply = &replyParameters{MessageID: messageID, AllowSendingWithoutReply: true}
+ }
+ if _, err := newBotAPI(r.apiBase, creds.BotToken, r.client).SendMessage(ctx, sendMessageParams{
+ ChatID: chatID,
+ Text: text,
+ MessageThreadID: threadID,
+ ReplyParameters: reply,
+ }); err != nil {
+ return fmt.Errorf("post telegram reply: %w", err)
+ }
+ return nil
+}
+
+func issueCreatedText(res engine.Result) string {
+ id := issueResultIdentifier(res)
+ title := strings.TrimSpace(res.IssueTitle)
+ if title == "" {
+ return "✅ 已创建 " + id
+ }
+ return "✅ 已创建 " + id + " — " + title
+}
+
+func issueDuplicateText(res engine.Result) string {
+ id := issueResultIdentifier(res)
+ title := strings.TrimSpace(res.IssueTitle)
+ if title == "" {
+ return "⚠️ 未创建:已存在进行中的任务 " + id + "。"
+ }
+ return "⚠️ 未创建:已存在进行中的任务 " + id + " — " + title
+}
+
+func issueResultIdentifier(res engine.Result) string {
+ if res.IssueIdentifier != "" {
+ return res.IssueIdentifier
+ }
+ if res.IssueNumber > 0 {
+ return fmt.Sprintf("#%d", res.IssueNumber)
+ }
+ return util.UUIDToString(res.IssueID)
+}
+
+func isAddressedIssueCommand(msg channel.InboundMessage) bool {
+ if !msg.AddressedToBot {
+ return false
+ }
+ source := msg.CommandText
+ if source == "" {
+ source = msg.Text
+ }
+ _, ok := engine.ParseIssueCommand(source)
+ return ok
+}
+
+func droppedReplyText(res engine.Result, msg channel.InboundMessage) string {
+ if !isAddressedIssueCommand(msg) {
+ return ""
+ }
+ switch res.DropReason {
+ case engine.DropReasonNonWorkspaceMember:
+ return msgIssueNotMember
+ case engine.DropReasonRevokedInstallation:
+ return msgIssueDisabled
+ default:
+ return ""
+ }
+}
diff --git a/server/internal/integrations/telegram/replier_test.go b/server/internal/integrations/telegram/replier_test.go
new file mode 100644
index 0000000000..2d1f3e11cd
--- /dev/null
+++ b/server/internal/integrations/telegram/replier_test.go
@@ -0,0 +1,161 @@
+package telegram
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+type fakeTelegramBindingMinter struct {
+ calls int
+ raw string
+}
+
+func (f *fakeTelegramBindingMinter) Mint(context.Context, pgtype.UUID, pgtype.UUID, string) (BindingToken, error) {
+ f.calls++
+ return BindingToken{Raw: f.raw}, nil
+}
+
+func TestReplyNeedsBindingDoesNotMintBearerLinkInGroup(t *testing.T) {
+ var got sendMessageParams
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
+ t.Errorf("decode request: %v", err)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":1,"chat":{"id":42,"type":"group"}}}`))
+ }))
+ defer srv.Close()
+
+ minter := &fakeTelegramBindingMinter{raw: "secret-token"}
+ r := NewOutboundReplier(OutboundReplierConfig{
+ Binding: minter,
+ Decrypt: nil,
+ AppURL: "https://multica.example",
+ APIBase: srv.URL,
+ HTTPClient: srv.Client(),
+ Logger: testLogger(),
+ })
+ inst := engine.ResolvedInstallation{
+ ID: telegramTestUUID(1),
+ WorkspaceID: telegramTestUUID(2),
+ Platform: db.ChannelInstallation{Config: []byte(`{"bot_token_encrypted":"MTIzOnNlY3JldA=="}`)},
+ }
+ msg := channel.InboundMessage{Source: channel.Source{
+ ChatID: "42", ChatType: channel.ChatTypeGroup, SenderID: "telegram-user",
+ }}
+
+ r.Reply(context.Background(), inst, msg, engine.Result{
+ Outcome: engine.OutcomeNeedsBinding,
+ Sender: "telegram-user",
+ })
+
+ if minter.calls != 0 {
+ t.Fatalf("Mint called %d times for a group prompt", minter.calls)
+ }
+ if !strings.Contains(got.Text, msgBindingGroupHint) {
+ t.Fatalf("group prompt = %q, want %q", got.Text, msgBindingGroupHint)
+ }
+ if strings.Contains(got.Text, "secret-token") || strings.Contains(got.Text, "multica.example") {
+ t.Fatalf("group prompt exposed a redeem link: %q", got.Text)
+ }
+}
+
+func TestReplyNeedsBindingInPrivateChatMintsQuotedLink(t *testing.T) {
+ var got sendMessageParams
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
+ t.Errorf("decode request: %v", err)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":1,"chat":{"id":42,"type":"private"}}`))
+ }))
+ defer srv.Close()
+
+ minter := &fakeTelegramBindingMinter{raw: "one-time-token"}
+ r := NewOutboundReplier(OutboundReplierConfig{
+ Binding: minter, AppURL: "https://multica.example/", APIBase: srv.URL,
+ HTTPClient: srv.Client(), Logger: testLogger(),
+ })
+ inst := engine.ResolvedInstallation{
+ ID: telegramTestUUID(1), WorkspaceID: telegramTestUUID(2),
+ Platform: db.ChannelInstallation{Config: []byte(`{"bot_token_encrypted":"MTIzOnNlY3JldA=="}`)},
+ }
+ msg := channel.InboundMessage{
+ MessageID: "42:7",
+ Source: channel.Source{ChatID: "42", ChatType: channel.ChatTypeP2P, SenderID: "telegram-user"},
+ }
+ r.Reply(context.Background(), inst, msg, engine.Result{Outcome: engine.OutcomeNeedsBinding})
+
+ if minter.calls != 1 || !strings.Contains(got.Text, "https://multica.example/telegram/bind?token=one-time-token") {
+ t.Fatalf("binding prompt = %+v; mint calls = %d", got, minter.calls)
+ }
+ if got.ReplyParameters == nil || got.ReplyParameters.MessageID != 7 || !got.ReplyParameters.AllowSendingWithoutReply {
+ t.Fatalf("binding prompt lost reply context: %+v", got)
+ }
+}
+
+func TestReplyCoversCommandAndIssueOutcomes(t *testing.T) {
+ var got []sendMessageParams
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var body sendMessageParams
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Errorf("decode request: %v", err)
+ }
+ got = append(got, body)
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":1,"chat":{"id":42,"type":"private"}}}`))
+ }))
+ defer srv.Close()
+
+ r := NewOutboundReplier(OutboundReplierConfig{APIBase: srv.URL, HTTPClient: srv.Client(), Logger: testLogger()})
+ inst := engine.ResolvedInstallation{Platform: db.ChannelInstallation{Config: []byte(`{"bot_token_encrypted":"MTIzOnNlY3JldA=="}`)}}
+ msg := channel.InboundMessage{
+ MessageID: "42:19", Text: "/issue title", AddressedToBot: true,
+ Source: channel.Source{ChatID: "42", ChatType: channel.ChatTypeP2P, ThreadID: "8"},
+ }
+ issueID := telegramTestUUID(7)
+
+ for _, res := range []engine.Result{
+ {Outcome: engine.OutcomeFreshPending},
+ {Outcome: engine.OutcomeIssueUsage},
+ {Outcome: engine.OutcomeIngested, IssueID: issueID, IssueIdentifier: "MUL-7", IssueTitle: "Title", IssueDuplicate: true},
+ {Outcome: engine.OutcomeDropped, DropReason: engine.DropReasonNonWorkspaceMember},
+ {Outcome: engine.OutcomeDropped, DropReason: engine.DropReasonRevokedInstallation},
+ } {
+ r.Reply(context.Background(), inst, msg, res)
+ }
+
+ want := []string{msgFreshPending, msgIssueUsage, issueDuplicateText(engine.Result{IssueID: issueID, IssueIdentifier: "MUL-7", IssueTitle: "Title"}), msgIssueNotMember, msgIssueDisabled}
+ if len(got) != len(want) {
+ t.Fatalf("got %d replies, want %d: %+v", len(got), len(want), got)
+ }
+ for i := range want {
+ if got[i].Text != want[i] {
+ t.Errorf("reply[%d] = %q, want %q", i, got[i].Text, want[i])
+ }
+ if got[i].MessageThreadID != 8 || got[i].ReplyParameters == nil ||
+ got[i].ReplyParameters.MessageID != 19 || !got[i].ReplyParameters.AllowSendingWithoutReply {
+ t.Errorf("reply[%d] lost topic/reply context: %+v", i, got[i])
+ }
+ }
+}
+
+func TestDroppedReplyOnlyAnswersAddressedIssueCommands(t *testing.T) {
+ res := engine.Result{Outcome: engine.OutcomeDropped, DropReason: engine.DropReasonNonWorkspaceMember}
+ if got := droppedReplyText(res, channel.InboundMessage{Text: "hello", AddressedToBot: true}); got != "" {
+ t.Fatalf("plain message reply = %q", got)
+ }
+ if got := droppedReplyText(res, channel.InboundMessage{Text: "/issue title", AddressedToBot: false}); got != "" {
+ t.Fatalf("unaddressed issue reply = %q", got)
+ }
+}
diff --git a/server/internal/integrations/telegram/resolvers.go b/server/internal/integrations/telegram/resolvers.go
new file mode 100644
index 0000000000..a935234fde
--- /dev/null
+++ b/server/internal/integrations/telegram/resolvers.go
@@ -0,0 +1,302 @@
+package telegram
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "strconv"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// This file is the Telegram ResolverSet: the platform-specific seams the
+// channel-agnostic engine.Router runs the inbound pipeline through. Built
+// entirely on the generic channel_* queries plus the shared engine.ChatSession
+// — no new query, no schema change — mirroring slack/resolvers.go.
+
+// originTelegramChat is the issue.origin_type label for issues created via the
+// Telegram /issue command.
+const originTelegramChat = "telegram_chat"
+
+// NewTelegramResolverSet assembles the Telegram ResolverSet. Pass a nil
+// replier to disable outbound verdict notices; typing (sendChatAction) is
+// enabled when deps carry a decrypter.
+func NewTelegramResolverSet(q *db.Queries, tx engine.TxStarter, replier engine.OutboundReplier, typing engine.TypingNotifier) engine.ResolverSet {
+ return engine.ResolverSet{
+ Installation: &installationResolver{q: q},
+ Identity: &identityResolver{q: q},
+ Dedup: &deduper{q: q},
+ Session: &sessionBinder{session: engine.NewChatSession(q, tx, TypeTelegram, engine.SessionTitles{
+ Group: "Telegram group",
+ Direct: "Telegram direct message",
+ Fallback: "Telegram chat",
+ })},
+ Audit: &auditor{q: q},
+ Replier: replier,
+ Typing: typing,
+ OriginType: originTelegramChat,
+ }
+}
+
+var (
+ _ engine.InstallationResolver = (*installationResolver)(nil)
+ _ engine.IdentityResolver = (*identityResolver)(nil)
+ _ engine.Deduper = (*deduper)(nil)
+ _ engine.SessionBinder = (*sessionBinder)(nil)
+ _ engine.Auditor = (*auditor)(nil)
+ _ engine.TypingNotifier = (*typingNotifier)(nil)
+)
+
+// telegramBindingConfig is the opaque outbound routing persisted on the chat
+// binding's config: the real chat id survives even when the binding key is a
+// composite (forum-topic thread isolation).
+type telegramBindingConfig struct {
+ ChatID string `json:"chat_id"`
+}
+
+// telegramSessionRouting derives the session-isolation key, the binding
+// config, and the reply thread from one inbound message. A private chat is one
+// continuous session (key = chat id). A group is one session per chat, except
+// forum topics, which isolate per topic (key = "chat:thread") — the closest
+// analog of Feishu thread isolation. Pure function, unit-tested without a DB.
+func telegramSessionRouting(msg channel.InboundMessage) (bindingKey string, config []byte, replyThread string) {
+ chatID := msg.Source.ChatID
+ cfg, _ := json.Marshal(telegramBindingConfig{ChatID: chatID})
+ if msg.Source.ChatType == channel.ChatTypeGroup && msg.Source.ThreadID != "" {
+ return chatID + ":" + msg.Source.ThreadID, cfg, msg.Source.ThreadID
+ }
+ return chatID, cfg, msg.Source.ThreadID
+}
+
+func decodeTelegramRaw(msg channel.InboundMessage) (telegramRawEvent, error) {
+ var raw telegramRawEvent
+ if len(msg.Raw) == 0 {
+ return telegramRawEvent{}, errors.New("telegram: inbound message Raw is empty")
+ }
+ if err := json.Unmarshal(msg.Raw, &raw); err != nil {
+ return telegramRawEvent{}, fmt.Errorf("decode telegram inbound raw: %w", err)
+ }
+ return raw, nil
+}
+
+func nullText(s string) pgtype.Text {
+ if s == "" {
+ return pgtype.Text{}
+ }
+ return pgtype.Text{String: s, Valid: true}
+}
+
+// ---- installation routing ----
+
+type installationResolver struct{ q *db.Queries }
+
+func (r *installationResolver) ResolveInstallation(ctx context.Context, msg channel.InboundMessage) (engine.ResolvedInstallation, error) {
+ raw, err := decodeTelegramRaw(msg)
+ if err != nil {
+ return engine.ResolvedInstallation{}, err
+ }
+ inst, err := r.q.GetChannelInstallationByAppID(ctx, db.GetChannelInstallationByAppIDParams{
+ ChannelType: string(TypeTelegram),
+ // Route by the bot id: each polling loop serves exactly one bot, and the
+ // (channel_type, app_id) unique index maps it to its installation.
+ AppID: raw.BotID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return engine.ResolvedInstallation{}, engine.ErrInstallationNotFound
+ }
+ return engine.ResolvedInstallation{}, err
+ }
+ return engine.ResolvedInstallation{
+ ID: inst.ID,
+ WorkspaceID: inst.WorkspaceID,
+ AgentID: inst.AgentID,
+ InstallerUserID: inst.InstallerUserID,
+ Active: inst.Status == "active",
+ Platform: inst,
+ }, nil
+}
+
+// ---- identity ----
+
+type identityResolver struct{ q *db.Queries }
+
+func (r *identityResolver) ResolveSender(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage) (engine.ResolvedIdentity, error) {
+ binding, err := r.q.GetChannelUserBindingByUserID(ctx, db.GetChannelUserBindingByUserIDParams{
+ InstallationID: inst.ID,
+ ChannelUserID: msg.Source.SenderID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return engine.ResolvedIdentity{}, engine.ErrSenderUnbound
+ }
+ return engine.ResolvedIdentity{}, err
+ }
+ // Binding existence no longer proves membership (no FK); re-check.
+ if _, err := r.q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
+ UserID: binding.MulticaUserID,
+ WorkspaceID: inst.WorkspaceID,
+ }); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return engine.ResolvedIdentity{}, engine.ErrSenderNotMember
+ }
+ return engine.ResolvedIdentity{}, err
+ }
+ return engine.ResolvedIdentity{UserID: binding.MulticaUserID}, nil
+}
+
+// ---- dedup ----
+
+type deduper struct{ q *db.Queries }
+
+func (r *deduper) Claim(ctx context.Context, installationID pgtype.UUID, messageID string) (pgtype.UUID, error) {
+ claim, err := r.q.ClaimChannelInboundDedup(ctx, db.ClaimChannelInboundDedupParams{
+ InstallationID: installationID,
+ MessageID: messageID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return pgtype.UUID{}, engine.ErrDuplicate
+ }
+ return pgtype.UUID{}, err
+ }
+ return claim.ClaimToken, nil
+}
+
+func (r *deduper) Mark(ctx context.Context, installationID pgtype.UUID, messageID string, claimToken pgtype.UUID) error {
+ _, err := r.q.MarkChannelInboundDedupProcessed(ctx, db.MarkChannelInboundDedupProcessedParams{
+ InstallationID: installationID,
+ MessageID: messageID,
+ ClaimToken: claimToken,
+ })
+ return err
+}
+
+func (r *deduper) Release(ctx context.Context, installationID pgtype.UUID, messageID string, claimToken pgtype.UUID) error {
+ _, err := r.q.ReleaseChannelInboundDedup(ctx, db.ReleaseChannelInboundDedupParams{
+ InstallationID: installationID,
+ MessageID: messageID,
+ ClaimToken: claimToken,
+ })
+ return err
+}
+
+// ---- session bind / append ----
+
+type sessionBinder struct{ session *engine.ChatSession }
+
+func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessionParams) (pgtype.UUID, error) {
+ bindingKey, config, _ := telegramSessionRouting(p.Message)
+ return r.session.EnsureSession(ctx, engine.EnsureSessionInput{
+ WorkspaceID: p.Installation.WorkspaceID,
+ AgentID: p.Installation.AgentID,
+ InstallationID: p.Installation.ID,
+ Sender: p.Sender,
+ BindingKey: bindingKey,
+ BindingConfig: config,
+ ChatType: p.Message.Source.ChatType,
+ })
+}
+
+func (r *sessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) error {
+ return r.session.MarkPendingFresh(ctx, sessionID)
+}
+
+func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {
+ _, _, replyThread := telegramSessionRouting(p.Message)
+ commandText := p.Message.CommandText
+ if commandText == "" {
+ commandText = p.Message.Text
+ }
+ return r.session.AppendUserMessage(ctx, engine.AppendInput{
+ SessionID: p.SessionID,
+ Sender: p.Sender,
+ InstallationID: p.InstallationID,
+ Body: p.Message.Text,
+ CommandText: commandText,
+ MessageID: p.Message.MessageID,
+ ThreadID: replyThread,
+ ClaimToken: p.ClaimToken,
+ MediaPendingSeconds: p.MediaPendingSeconds,
+ })
+}
+
+func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) error {
+ return r.session.BindMediaRefs(ctx, engine.BindMediaInput{
+ MessageID: p.MessageID,
+ SessionID: p.SessionID,
+ WorkspaceID: p.WorkspaceID,
+ Sender: p.Sender,
+ MediaRefs: p.MediaRefs,
+ })
+}
+
+// ---- audit ----
+
+type auditor struct{ q *db.Queries }
+
+func (r *auditor) RecordDrop(ctx context.Context, instID pgtype.UUID, msg channel.InboundMessage, reason engine.DropReason) error {
+ raw, _ := decodeTelegramRaw(msg) // best-effort; a decode miss still audits
+ return r.q.RecordChannelInboundDrop(ctx, db.RecordChannelInboundDropParams{
+ ChannelType: string(TypeTelegram),
+ EventType: raw.EventType,
+ DropReason: string(reason),
+ InstallationID: instID,
+ ChannelChatID: nullText(msg.Source.ChatID),
+ ChannelEventID: nullText(msg.EventID),
+ ChannelMessageID: nullText(msg.MessageID),
+ })
+}
+
+// ---- typing indicator ----
+
+// typingNotifier shows Telegram's native "typing…" chat action when a message
+// is ingested. The action self-expires after ~5 seconds, so unlike Slack's
+// reaction there is nothing to clear — OnSettled is a no-op.
+type typingNotifier struct {
+ decrypt Decrypter
+ apiBase string
+ client *http.Client
+ logger *slog.Logger
+}
+
+// NewTypingNotifier builds the sendChatAction-based typing indicator.
+func NewTypingNotifier(decrypt Decrypter, apiBase string, client *http.Client, logger *slog.Logger) engine.TypingNotifier {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ return &typingNotifier{decrypt: decrypt, apiBase: apiBase, client: client, logger: logger}
+}
+
+func (n *typingNotifier) OnIngested(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, sessionID pgtype.UUID) {
+ row, ok := inst.Platform.(db.ChannelInstallation)
+ if !ok {
+ return
+ }
+ creds, err := decodeCredentials(row.Config, n.decrypt)
+ if err != nil {
+ n.logger.WarnContext(ctx, "telegram typing: decode credentials failed", "error", err)
+ return
+ }
+ chatID, err := strconv.ParseInt(msg.Source.ChatID, 10, 64)
+ if err != nil {
+ return
+ }
+ var threadID int64
+ if msg.Source.ThreadID != "" {
+ threadID, _ = strconv.ParseInt(msg.Source.ThreadID, 10, 64)
+ }
+ if err := newBotAPI(n.apiBase, creds.BotToken, n.client).SendChatAction(ctx, chatID, threadID); err != nil {
+ n.logger.WarnContext(ctx, "telegram typing: sendChatAction failed", "error", err)
+ }
+}
+
+func (n *typingNotifier) OnSettled(ctx context.Context, sessionID pgtype.UUID) {}
diff --git a/server/internal/integrations/telegram/sender.go b/server/internal/integrations/telegram/sender.go
new file mode 100644
index 0000000000..4afe779056
--- /dev/null
+++ b/server/internal/integrations/telegram/sender.go
@@ -0,0 +1,179 @@
+package telegram
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "strconv"
+ "strings"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+)
+
+// User-facing copy the bot speaks in Telegram. Chinese-first, aligned with
+// the Lark adapter's product voice (conventions.zh.mdx); the binding prompt
+// carries the redeem link.
+const (
+ msgAgentOffline = "⚠️ 智能体当前离线,消息已记录。下次 daemon 上线后会自动继续处理。"
+ msgAgentArchived = "⚠️ 该智能体已归档,无法回复。请联系工作区管理员。"
+ msgUnsupportedType = "暂不支持此类消息,请发送文字内容。"
+ msgBindingGroupHint = "请先私聊我发送一条消息,再完成 Multica 账号绑定。"
+)
+
+// maxMessageUnits caps one outbound sendMessage body. Telegram hard-caps a
+// message at 4096 UTF-16 code units after entity parsing; 3500 units leaves
+// headroom for the markdown conversion while counting astral characters (such
+// as emoji) correctly.
+const maxMessageUnits = 3500
+
+// sender posts agent replies back to Telegram via sendMessage. Outbound half
+// only; the installation identity is resolved per message by the Router.
+type sender struct {
+ api *botAPI
+ logger *slog.Logger
+}
+
+func newSender(api *botAPI, logger *slog.Logger) *sender {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ return &sender{api: api, logger: logger}
+}
+
+// Send delivers a text reply, converting Markdown to Telegram HTML and
+// chunking under the per-message cap. The returned SendResult carries the id
+// of the LAST posted chunk. A rejected HTML payload falls back to plain text
+// so a conversion edge case can never eat the reply.
+func (s *sender) Send(ctx context.Context, out channel.OutboundMessage) (channel.SendResult, error) {
+ if s.api == nil {
+ return channel.SendResult{}, errors.New("telegram: api client not configured")
+ }
+ chatID, err := strconv.ParseInt(out.ChatID, 10, 64)
+ if err != nil {
+ return channel.SendResult{}, fmt.Errorf("telegram: bad chat id %q: %w", out.ChatID, err)
+ }
+ var threadID int64
+ if out.ThreadID != "" {
+ threadID, _ = strconv.ParseInt(out.ThreadID, 10, 64)
+ }
+ var replyTo int64
+ if out.ReplyTo != "" {
+ replyTo = parseMessageRef(out.ReplyTo)
+ }
+
+ var lastID string
+ for _, chunk := range chunkMessage(out.Text, maxMessageUnits) {
+ var reply *replyParameters
+ if replyTo != 0 {
+ reply = &replyParameters{MessageID: replyTo, AllowSendingWithoutReply: true}
+ }
+ m, err := sendMessageWithRetryAfter(ctx, s.api, sendMessageParams{
+ ChatID: chatID,
+ Text: formatHTML(chunk),
+ ParseMode: "HTML",
+ MessageThreadID: threadID,
+ ReplyParameters: reply,
+ })
+ if err != nil {
+ // HTML rejection fallback: send the raw markdown as plain text. Do
+ // not retry transport or unrelated API errors: the first request may
+ // already have reached Telegram, and retrying could duplicate it.
+ if !isHTMLParseError(err) {
+ return channel.SendResult{}, fmt.Errorf("telegram: sendMessage: %w", err)
+ }
+ m, err = sendMessageWithRetryAfter(ctx, s.api, sendMessageParams{
+ ChatID: chatID,
+ Text: chunk,
+ MessageThreadID: threadID,
+ ReplyParameters: reply,
+ })
+ if err != nil {
+ return channel.SendResult{}, fmt.Errorf("telegram: sendMessage: %w", err)
+ }
+ }
+ lastID = messageKey(chatID, m.MessageID)
+ replyTo = 0 // only the first chunk quotes
+ }
+ return channel.SendResult{MessageID: lastID}, nil
+}
+
+// parseMessageRef extracts the numeric message id from either a bare id or
+// the composite "chat:message" key this adapter stores.
+func parseMessageRef(ref string) int64 {
+ if _, after, ok := strings.Cut(ref, ":"); ok {
+ ref = after
+ }
+ id, _ := strconv.ParseInt(ref, 10, 64)
+ return id
+}
+
+// chunkMessage splits text into <=maxUnits UTF-16 code-unit pieces on rune
+// boundaries, preferring newline breaks so code blocks and paragraphs split
+// cleanly.
+func chunkMessage(text string, maxUnits int) []string {
+ runes := []rune(text)
+ if maxUnits <= 0 || utf16Units(text) <= maxUnits {
+ return []string{text}
+ }
+ var chunks []string
+ for len(runes) > 0 {
+ n := 0
+ end := 0
+ for i, r := range runes {
+ units := 1
+ if r > 0xFFFF {
+ units = 2
+ }
+ if n+units > maxUnits {
+ break
+ }
+ n += units
+ end = i + 1
+ }
+ if end == 0 {
+ end = 1
+ }
+ // Prefer the last newline in the window, but only when it leaves a
+ // substantial first chunk rather than producing tiny fragments.
+ if i := lastIndexRune(runes[:end], '\n'); i >= 0 && utf16Units(string(runes[:i])) > maxUnits/2 {
+ end = i + 1
+ }
+ chunks = append(chunks, strings.TrimRight(string(runes[:end]), "\n"))
+ runes = runes[end:]
+ }
+ return chunks
+}
+
+func utf16Units(s string) int {
+ n := 0
+ for _, r := range s {
+ if r > 0xFFFF {
+ n += 2
+ } else {
+ n++
+ }
+ }
+ return n
+}
+
+func isHTMLParseError(err error) bool {
+ var ae *apiError
+ if !errors.As(err, &ae) || ae.Code != http.StatusBadRequest {
+ return false
+ }
+ description := strings.ToLower(ae.Description)
+ return strings.Contains(description, "parse entities") ||
+ strings.Contains(description, "unsupported start tag") ||
+ strings.Contains(description, "can't find end tag")
+}
+
+func lastIndexRune(rs []rune, r rune) int {
+ for i := len(rs) - 1; i >= 0; i-- {
+ if rs[i] == r {
+ return i
+ }
+ }
+ return -1
+}
diff --git a/server/internal/integrations/telegram/telegram_channel.go b/server/internal/integrations/telegram/telegram_channel.go
new file mode 100644
index 0000000000..7004dc3da3
--- /dev/null
+++ b/server/internal/integrations/telegram/telegram_channel.go
@@ -0,0 +1,253 @@
+package telegram
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "strconv"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+)
+
+// telegramChannel is ONE installation's getUpdates long-polling loop. Telegram
+// has no WebSocket transport; long polling is the persistent-connection
+// equivalent — one blocking loop per bot token, supervised per-installation by
+// engine.Supervisor exactly like Feishu's WS long-conn and Slack's Socket
+// Mode. The single-consumer constraint (Telegram 409s a second getUpdates
+// consumer) maps 1:1 onto the Supervisor's WS-lease guarantee of at most one
+// active loop per installation across replicas.
+type telegramChannel struct {
+ botID int64
+ botUsername string
+ api *botAPI
+ handler channel.InboundHandler
+ logger *slog.Logger
+}
+
+// pollRetryDelay spaces retries after a transient getUpdates failure inside
+// one Connect attempt before giving the error to the Supervisor's backoff.
+const pollRetryDelay = 2 * time.Second
+
+func (c *telegramChannel) Type() channel.Type { return TypeTelegram }
+
+func (c *telegramChannel) Capabilities() channel.Capability {
+ return channel.CapText | channel.CapThreadReply | channel.CapQuoteReply |
+ channel.CapTypingIndicator | channel.CapMessageEdit
+}
+
+// Disconnect is a no-op: the polling loop's whole lifetime is scoped to
+// Connect (it returns when the run context is cancelled). Mirrors
+// slackChannel.Disconnect.
+func (c *telegramChannel) Disconnect(ctx context.Context) error { return nil }
+
+// Send posts an outbound reply with this installation's bot token, reusing
+// the shared sender (Markdown→Telegram HTML, chunking, threading).
+func (c *telegramChannel) Send(ctx context.Context, out channel.OutboundMessage) (channel.SendResult, error) {
+ return newSender(c.api, c.logger).Send(ctx, out)
+}
+
+// Connect runs the getUpdates long-polling receive loop until ctx is
+// cancelled (returns nil — graceful stop) or the link fails in a way the loop
+// cannot absorb (returns the error — the Supervisor reconnects under
+// backoff). A 409 Conflict is surfaced as ErrConflict with a precise message:
+// it means another consumer is polling this bot token, a state backoff cannot
+// fix but the operator can.
+func (c *telegramChannel) Connect(ctx context.Context) error {
+ if c.handler == nil {
+ return errors.New("telegram: inbound handler not configured")
+ }
+ // offset starts at 0: Telegram then delivers all pending updates, and the
+ // engine's (installation, message_id) dedup absorbs any the previous run
+ // already processed — the same replay tolerance the Feishu WS reconnect
+ // relies on.
+ var offset int64
+ for {
+ updates, err := c.api.GetUpdates(ctx, offset)
+ if err != nil {
+ if ctx.Err() != nil {
+ return nil
+ }
+ if errors.Is(err, ErrConflict) {
+ c.logger.WarnContext(ctx, "telegram: getUpdates conflict — this bot token is polled by another instance; stop the other consumer or use a distinct bot per environment",
+ "bot_id", c.botID)
+ return err
+ }
+ if wait, ok := retryAfter(err); ok {
+ c.logger.WarnContext(ctx, "telegram: getUpdates rate limited", "bot_id", c.botID, "retry_after", wait)
+ if !sleepCtx(ctx, wait) {
+ return nil
+ }
+ continue
+ }
+ // Transient network/API failure: one spaced retry loop inside the
+ // attempt keeps a momentary blip from churning the Supervisor's
+ // backoff; persistent failure still escalates via repeated errors.
+ c.logger.WarnContext(ctx, "telegram: getUpdates failed", "bot_id", c.botID, "error", err)
+ if !sleepCtx(ctx, pollRetryDelay) {
+ return nil
+ }
+ return fmt.Errorf("telegram: getUpdates: %w", err)
+ }
+ for _, u := range updates {
+ if u.UpdateID >= offset {
+ offset = u.UpdateID + 1
+ }
+ if err := c.dispatch(ctx, u); err != nil {
+ if ctx.Err() != nil {
+ return nil
+ }
+ return err
+ }
+ }
+ }
+}
+
+// dispatch translates one update and hands it to the engine. A non-nil
+// handler error is an infrastructure failure and propagates (Supervisor
+// reconnects; the un-advanced updates re-deliver and dedup absorbs
+// 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)
+ if !ok {
+ return nil
+ }
+ if msg.Type != channel.MsgTypeText {
+ if msg.Source.ChatType == channel.ChatTypeP2P || msg.AddressedToBot {
+ c.notifyUnsupported(ctx, u)
+ }
+ return nil
+ }
+ if msg.Text == "" {
+ return nil
+ }
+ if err := c.handler(ctx, msg); err != nil {
+ c.notifyIssueDispatchError(msg)
+ return err
+ }
+ return nil
+}
+
+const (
+ issueErrorReplyTimeout = 5 * time.Second
+ issueDispatchFailedText = "⚠️ 创建任务时发生内部错误,请稍后重试。"
+)
+
+// notifyIssueDispatchError prevents an addressed /issue command from failing
+// silently when the engine returns an infrastructure error before it can
+// produce a normal outcome. It is detached from the polling loop so the
+// Supervisor can reconnect without waiting on the best-effort notice.
+func (c *telegramChannel) notifyIssueDispatchError(msg channel.InboundMessage) {
+ if !isAddressedIssueCommand(msg) {
+ return
+ }
+ go func() {
+ ctx, cancel := context.WithTimeout(context.Background(), issueErrorReplyTimeout)
+ defer cancel()
+ chatID, err := strconv.ParseInt(msg.Source.ChatID, 10, 64)
+ if err != nil {
+ c.logger.Warn("telegram: issue dispatch-error reply has invalid chat id", "error", err)
+ return
+ }
+ var threadID int64
+ if msg.Source.ThreadID != "" {
+ threadID, _ = strconv.ParseInt(msg.Source.ThreadID, 10, 64)
+ }
+ if _, err := c.api.SendMessage(ctx, sendMessageParams{
+ ChatID: chatID,
+ Text: issueDispatchFailedText,
+ MessageThreadID: threadID,
+ ReplyParameters: optionalReplyParameters(parseMessageRef(msg.MessageID)),
+ }); err != nil {
+ c.logger.WarnContext(ctx, "telegram: issue dispatch-error reply failed", "error", err)
+ }
+ }()
+}
+
+// notifyUnsupported tells an interacting sender their non-text message type is
+// not handled yet. Preserve topic routing and quote the triggering message so
+// the notice remains unambiguous in a busy group. Best-effort; failures are
+// logged only.
+func (c *telegramChannel) notifyUnsupported(ctx context.Context, u Update) {
+ if u.Message == nil {
+ return
+ }
+ if _, err := c.api.SendMessage(ctx, sendMessageParams{
+ ChatID: u.Message.Chat.ID,
+ Text: msgUnsupportedType,
+ MessageThreadID: u.Message.MessageThreadID,
+ ReplyParameters: &replyParameters{
+ MessageID: u.Message.MessageID,
+ AllowSendingWithoutReply: true,
+ },
+ }); err != nil {
+ c.logger.WarnContext(ctx, "telegram: unsupported-type notice failed", "error", err)
+ }
+}
+
+// sleepCtx sleeps for d or until ctx is done; false means ctx ended first.
+func sleepCtx(ctx context.Context, d time.Duration) bool {
+ t := time.NewTimer(d)
+ defer t.Stop()
+ select {
+ case <-ctx.Done():
+ return false
+ case <-t.C:
+ return true
+ }
+}
+
+// ChannelDeps are the shared dependencies the Telegram Factory closes over.
+// The engine inbound handler is supplied per-build via channel.Config.Handler.
+type ChannelDeps struct {
+ Decrypt Decrypter
+ Logger *slog.Logger
+ // APIBase overrides the Bot API host (tests). Empty uses production.
+ APIBase string
+ // HTTPClient overrides the polling client (tests). Nil uses a default with
+ // a timeout sized for long polling.
+ HTTPClient *http.Client
+}
+
+// RegisterTelegram registers the per-installation Telegram Factory so the
+// engine.Supervisor builds + supervises one polling loop per active Telegram
+// installation. Same contract as lark.RegisterFeishu / slack.RegisterSlack —
+// no engine edit.
+func RegisterTelegram(reg *channel.Registry, deps ChannelDeps) {
+ reg.Register(TypeTelegram, newTelegramFactory(deps))
+}
+
+func newTelegramFactory(deps ChannelDeps) channel.Factory {
+ logger := deps.Logger
+ if logger == nil {
+ logger = slog.Default()
+ }
+ return func(cfg channel.Config) (channel.Channel, error) {
+ var ic installConfig
+ if err := json.Unmarshal(cfg.Raw, &ic); err != nil {
+ return nil, fmt.Errorf("telegram: decode installation config: %w", err)
+ }
+ token, err := decryptToken(ic.BotTokenEncrypted, deps.Decrypt)
+ if err != nil {
+ return nil, fmt.Errorf("telegram: decrypt bot token: %w", err)
+ }
+ if token == "" {
+ return nil, errors.New("telegram: installation has no bot token")
+ }
+ botID, err := strconv.ParseInt(ic.AppID, 10, 64)
+ if err != nil {
+ return nil, fmt.Errorf("telegram: installation app_id is not a bot id: %w", err)
+ }
+ return &telegramChannel{
+ botID: botID,
+ botUsername: ic.BotUsername,
+ api: newBotAPI(deps.APIBase, token, deps.HTTPClient),
+ handler: cfg.Handler,
+ logger: logger,
+ }, nil
+ }
+}
diff --git a/server/internal/integrations/telegram/telegram_test.go b/server/internal/integrations/telegram/telegram_test.go
new file mode 100644
index 0000000000..6ee745d69a
--- /dev/null
+++ b/server/internal/integrations/telegram/telegram_test.go
@@ -0,0 +1,675 @@
+package telegram
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+)
+
+func TestParseBotID(t *testing.T) {
+ cases := []struct {
+ token string
+ want string
+ wantOK bool
+ }{
+ {"8983760937:AAExampleSecretPart", "8983760937", true},
+ {" 12345:abc ", "12345", true},
+ {"no-colon-token", "", false},
+ {":empty-id", "", false},
+ {"12345:", "", false},
+ {"abc123:secret", "", false},
+ {"", "", false},
+ }
+ for _, c := range cases {
+ got, err := parseBotID(c.token)
+ if c.wantOK && (err != nil || got != c.want) {
+ t.Errorf("parseBotID(%q) = %q, %v; want %q", c.token, got, err, c.want)
+ }
+ if !c.wantOK && err == nil {
+ t.Errorf("parseBotID(%q) should fail", c.token)
+ }
+ }
+}
+
+func TestInboundFromUpdatePrivateText(t *testing.T) {
+ u := Update{
+ UpdateID: 42,
+ Message: &Message{
+ MessageID: 7,
+ From: &User{ID: 111, FirstName: "Ada", LastName: "L"},
+ Chat: Chat{ID: 555, Type: "private"},
+ Text: "hello there",
+ },
+ }
+ msg, ok := inboundFromUpdate(u, 999, "my_bot")
+ if !ok {
+ t.Fatal("expected ok")
+ }
+ if msg.EventID != "42" || msg.MessageID != "555:7" {
+ t.Errorf("ids: event=%q message=%q", msg.EventID, msg.MessageID)
+ }
+ if msg.Source.ChatType != channel.ChatTypeP2P || !msg.AddressedToBot {
+ t.Errorf("p2p should always be addressed: %+v", msg.Source)
+ }
+ if msg.Text != "hello there" || msg.CommandText != "hello there" || msg.Type != channel.MsgTypeText {
+ t.Errorf("text=%q type=%q", msg.Text, msg.Type)
+ }
+ var raw telegramRawEvent
+ if err := json.Unmarshal(msg.Raw, &raw); err != nil || raw.BotID != "999" || raw.SenderName != "Ada L" {
+ t.Errorf("raw = %+v, err %v", raw, err)
+ }
+}
+
+func TestInboundFromUpdateGroupAddressing(t *testing.T) {
+ base := func(text string, reply *Message) Update {
+ return Update{
+ UpdateID: 1,
+ Message: &Message{
+ MessageID: 2,
+ From: &User{ID: 111, FirstName: "U"},
+ Chat: Chat{ID: -100200, Type: "supergroup"},
+ Text: text,
+ ReplyToMessage: reply,
+ },
+ }
+ }
+ // Unaddressed group chatter: ingested but not addressed (Router drops it).
+ msg, ok := inboundFromUpdate(base("plain chatter", nil), 999, "my_bot")
+ if !ok || msg.AddressedToBot {
+ t.Errorf("plain group message must not be addressed: ok=%v addressed=%v", ok, msg.AddressedToBot)
+ }
+ // @-mention: addressed, mention token stripped.
+ msg, ok = inboundFromUpdate(base("@my_bot do the thing", nil), 999, "my_bot")
+ if !ok || !msg.AddressedToBot || msg.Text != "do the thing" {
+ t.Errorf("mention: ok=%v addressed=%v text=%q", ok, msg.AddressedToBot, msg.Text)
+ }
+ // Reply to the bot's own message: addressed.
+ botMsg := &Message{MessageID: 1, From: &User{ID: 999, IsBot: true}}
+ msg, ok = inboundFromUpdate(base("follow-up", botMsg), 999, "my_bot")
+ if !ok || !msg.AddressedToBot {
+ t.Errorf("reply-to-bot must be addressed: ok=%v addressed=%v", ok, msg.AddressedToBot)
+ }
+ if msg.Text != "follow-up" || msg.CommandText != "follow-up" {
+ t.Fatalf("reply-to-bot text/command = %q/%q", msg.Text, msg.CommandText)
+ }
+}
+
+func TestInboundGroupHumanReplyRequiresMentionAndPreservesQuotedContext(t *testing.T) {
+ humanReply := &Message{
+ MessageID: 9,
+ From: &User{ID: 222, FirstName: "Ada", LastName: "Lovelace"},
+ Text: "/issue historical command",
+ }
+ update := func(text string) Update {
+ return Update{UpdateID: 1, Message: &Message{
+ MessageID: 10,
+ From: &User{ID: 111, FirstName: "Grace"},
+ Chat: Chat{ID: -100200, Type: "supergroup"},
+ Text: text,
+ ReplyToMessage: humanReply,
+ }}
+ }
+
+ msg, ok := inboundFromUpdate(update("summarize this"), 999, "my_bot")
+ if !ok || msg.AddressedToBot {
+ t.Fatalf("human reply without mention must not address bot: ok=%v addressed=%v", ok, msg.AddressedToBot)
+ }
+ if msg.Text != "summarize this" {
+ t.Fatalf("unaddressed chatter was enriched: %q", msg.Text)
+ }
+
+ msg, ok = inboundFromUpdate(update("@my_bot summarize this"), 999, "my_bot")
+ if !ok || !msg.AddressedToBot {
+ t.Fatalf("mentioned human reply must address bot: ok=%v addressed=%v", ok, msg.AddressedToBot)
+ }
+ if msg.CommandText != "summarize this" {
+ t.Fatalf("CommandText = %q, want sender's instruction only", msg.CommandText)
+ }
+ for _, want := range []string{"sender=\"Ada Lovelace\"", "/issue historical command", "summarize this"} {
+ if !strings.Contains(msg.Text, want) {
+ t.Fatalf("enriched Text = %q, missing %q", msg.Text, want)
+ }
+ }
+}
+
+func TestInboundGroupHumanReplyNewCommandPreservesQuotedContext(t *testing.T) {
+ quoted := &Message{
+ MessageID: 9,
+ From: &User{ID: 222, FirstName: "Ada", LastName: "Lovelace"},
+ Text: "the deployment failed after the schema change",
+ }
+ msg, ok := inboundFromUpdate(Update{UpdateID: 1, Message: &Message{
+ MessageID: 10,
+ From: &User{ID: 111, FirstName: "Grace"},
+ Chat: Chat{ID: -100200, Type: "supergroup"},
+ Text: "@my_bot /new summarize this",
+ ReplyToMessage: quoted,
+ }}, 999, "my_bot")
+ if !ok || !msg.AddressedToBot {
+ t.Fatalf("message was not accepted: ok=%v addressed=%v", ok, msg.AddressedToBot)
+ }
+ if !msg.ForceFresh {
+ t.Fatal("/new human reply must request a fresh session before shared routing")
+ }
+ if msg.CommandText != "/new summarize this" {
+ t.Fatalf("CommandText = %q, want original cleaned command", msg.CommandText)
+ }
+ for _, want := range []string{
+ "sender=\"Ada Lovelace\"",
+ "the deployment failed after the schema change",
+ "summarize this",
+ } {
+ if !strings.Contains(msg.Text, want) {
+ t.Fatalf("enriched Text = %q, missing %q", msg.Text, want)
+ }
+ }
+ if strings.Contains(msg.Text, "/new") {
+ t.Fatalf("agent-readable Text still contains /new: %q", msg.Text)
+ }
+}
+
+func TestInboundGroupHumanReplyUsesCaptionAndHandlesNonText(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ reply *Message
+ wanted string
+ }{
+ {
+ name: "caption",
+ reply: &Message{MessageID: 9, From: &User{ID: 222, Username: "ada"},
+ Caption: "diagram caption", Photo: []any{struct{}{}},
+ },
+ wanted: "diagram caption",
+ },
+ {
+ name: "empty non-text",
+ reply: &Message{MessageID: 9, From: &User{ID: 222, Username: "ada"},
+ Document: &struct {
+ FileName string `json:"file_name"`
+ }{FileName: "notes.txt"},
+ },
+ wanted: "[empty or non-text message]",
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ msg, ok := inboundFromUpdate(Update{UpdateID: 1, Message: &Message{
+ MessageID: 10, From: &User{ID: 111, FirstName: "Grace"},
+ Chat: Chat{ID: -100200, Type: "supergroup"}, Text: "@my_bot inspect this",
+ ReplyToMessage: tc.reply,
+ }}, 999, "my_bot")
+ if !ok || !msg.AddressedToBot || msg.CommandText != "inspect this" ||
+ !strings.Contains(msg.Text, "sender=\"ada\"") || !strings.Contains(msg.Text, tc.wanted) {
+ t.Fatalf("message = %+v", msg)
+ }
+ })
+ }
+}
+
+func TestInboundFromUpdateDropsBotsAndChannels(t *testing.T) {
+ if _, ok := inboundFromUpdate(Update{Message: &Message{
+ From: &User{ID: 5, IsBot: true}, Chat: Chat{ID: 1, Type: "private"}, Text: "x",
+ }}, 999, "b"); ok {
+ t.Error("bot sender must be dropped")
+ }
+ if _, ok := inboundFromUpdate(Update{Message: &Message{
+ From: &User{ID: 5}, Chat: Chat{ID: 1, Type: "channel"}, Text: "x",
+ }}, 999, "b"); ok {
+ t.Error("channel post must be dropped")
+ }
+ if _, ok := inboundFromUpdate(Update{}, 999, "b"); ok {
+ t.Error("empty update must be dropped")
+ }
+}
+
+func TestInboundFreshAliasIsPlainText(t *testing.T) {
+ u := Update{UpdateID: 1, Message: &Message{
+ MessageID: 2, From: &User{ID: 3, FirstName: "U"},
+ Chat: Chat{ID: 4, Type: "private"}, Text: "/fresh start over please",
+ }}
+ msg, ok := inboundFromUpdate(u, 999, "my_bot")
+ if !ok || msg.ForceFresh || msg.Text != "/fresh start over please" || msg.CommandText != msg.Text {
+ t.Errorf("fresh: ok=%v force=%v text=%q", ok, msg.ForceFresh, msg.Text)
+ }
+}
+
+func TestInboundTelegramCommandSuffixes(t *testing.T) {
+ for _, tc := range []struct {
+ text string
+ wantText string
+ wantFresh bool
+ }{
+ {text: "/fresh@my_bot continue", wantText: "/fresh continue", wantFresh: false},
+ {text: "/new@my_bot continue", wantText: "continue", wantFresh: true},
+ {text: "/issue@my_bot fix login", wantText: "/issue fix login", wantFresh: false},
+ } {
+ u := Update{UpdateID: 1, Message: &Message{
+ MessageID: 2, From: &User{ID: 3, FirstName: "U"},
+ Chat: Chat{ID: -4, Type: "supergroup"}, Text: tc.text,
+ }}
+ msg, ok := inboundFromUpdate(u, 999, "my_bot")
+ if !ok || !msg.AddressedToBot || msg.ForceFresh != tc.wantFresh || msg.Text != tc.wantText {
+ t.Errorf("%q: ok=%v addressed=%v fresh=%v text=%q", tc.text, ok, msg.AddressedToBot, msg.ForceFresh, msg.Text)
+ }
+ }
+}
+
+func TestInboundUsesExactStructuredTelegramMentions(t *testing.T) {
+ tests := []struct {
+ name string
+ text string
+ entities []MessageEntity
+ addressed bool
+ wantText string
+ }{
+ {
+ name: "unicode prefix uses UTF-16 entity offsets",
+ text: "😀 @my_bot hello",
+ entities: []MessageEntity{{Type: "mention", Offset: 3, Length: 7}},
+ addressed: true,
+ wantText: "😀 hello",
+ },
+ {
+ name: "similar username is not the bot",
+ text: "@my_bot_extra hello",
+ entities: []MessageEntity{{Type: "mention", Offset: 0, Length: 13}},
+ addressed: false,
+ wantText: "@my_bot_extra hello",
+ },
+ {
+ name: "bot command suffix targets exact bot",
+ text: "/issue@my_bot fix",
+ entities: []MessageEntity{{Type: "bot_command", Offset: 0, Length: 13}},
+ addressed: true,
+ wantText: "/issue fix",
+ },
+ {
+ name: "bot command for a similar bot is ignored",
+ text: "/issue@my_bot_extra fix",
+ entities: []MessageEntity{{Type: "bot_command", Offset: 0, Length: 19}},
+ addressed: false,
+ wantText: "/issue@my_bot_extra fix",
+ },
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ u := Update{UpdateID: 1, Message: &Message{
+ MessageID: 2, From: &User{ID: 3, FirstName: "U"},
+ Chat: Chat{ID: -4, Type: "supergroup"}, Text: tc.text, Entities: tc.entities,
+ }}
+ msg, ok := inboundFromUpdate(u, 999, "my_bot")
+ if !ok || msg.AddressedToBot != tc.addressed || msg.Text != tc.wantText {
+ t.Fatalf("ok=%v addressed=%v text=%q", ok, msg.AddressedToBot, msg.Text)
+ }
+ })
+ }
+}
+
+func TestDispatchIssueErrorSendsFailureNotice(t *testing.T) {
+ notice := make(chan sendMessageParams, 1)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var got sendMessageParams
+ _ = json.NewDecoder(r.Body).Decode(&got)
+ notice <- got
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":1,"chat":{"id":42,"type":"private"}}}`))
+ }))
+ defer srv.Close()
+
+ wantErr := errors.New("database unavailable")
+ c := &telegramChannel{
+ botID: 999, botUsername: "my_bot",
+ api: newBotAPI(srv.URL, "123:abc", srv.Client()),
+ handler: func(context.Context, channel.InboundMessage) error { return wantErr },
+ logger: testLogger(),
+ }
+ err := c.dispatch(context.Background(), Update{UpdateID: 1, Message: &Message{
+ MessageID: 2, From: &User{ID: 3, FirstName: "U"},
+ Chat: Chat{ID: 42, Type: "private"}, Text: "/issue broken path",
+ }})
+ if !errors.Is(err, wantErr) {
+ t.Fatalf("dispatch error = %v, want %v", err, wantErr)
+ }
+ select {
+ case got := <-notice:
+ if got.Text != issueDispatchFailedText || got.ChatID != 42 ||
+ got.ReplyParameters == nil || got.ReplyParameters.MessageID != 2 {
+ t.Fatalf("notice = %+v", got)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("timed out waiting for issue failure notice")
+ }
+}
+
+func TestTelegramSessionRouting(t *testing.T) {
+ p2p := channel.InboundMessage{Source: channel.Source{
+ ChatID: "555", ChatType: channel.ChatTypeP2P,
+ }}
+ key, cfg, thread := telegramSessionRouting(p2p)
+ if key != "555" || thread != "" {
+ t.Errorf("p2p: key=%q thread=%q", key, thread)
+ }
+ var bc telegramBindingConfig
+ if err := json.Unmarshal(cfg, &bc); err != nil || bc.ChatID != "555" {
+ t.Errorf("binding config = %+v, err %v", bc, err)
+ }
+ topic := channel.InboundMessage{Source: channel.Source{
+ ChatID: "-100", ChatType: channel.ChatTypeGroup, ThreadID: "77",
+ }}
+ key, _, thread = telegramSessionRouting(topic)
+ if key != "-100:77" || thread != "77" {
+ t.Errorf("forum topic: key=%q thread=%q", key, thread)
+ }
+}
+
+func TestGetUpdates409IsErrConflict(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusConflict)
+ _, _ = w.Write([]byte(`{"ok":false,"error_code":409,"description":"Conflict: terminated by other getUpdates request"}`))
+ }))
+ defer srv.Close()
+ api := newBotAPI(srv.URL, "123:abc", srv.Client())
+ if _, err := api.GetUpdates(context.Background(), 0); err != ErrConflict {
+ t.Fatalf("expected ErrConflict, got %v", err)
+ }
+}
+
+func TestRetryAfterOn429(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":7}}`))
+ }))
+ defer srv.Close()
+ api := newBotAPI(srv.URL, "123:abc", srv.Client())
+ _, err := api.SendMessage(context.Background(), sendMessageParams{ChatID: 1, Text: "x"})
+ wait, ok := retryAfter(err)
+ if !ok || wait != 7*time.Second {
+ t.Fatalf("retryAfter = %v, %v; want 7s", wait, ok)
+ }
+}
+
+func TestGetWebhookInfo(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if !strings.HasSuffix(r.URL.Path, "/getWebhookInfo") {
+ t.Fatalf("path = %q, want getWebhookInfo", r.URL.Path)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"ok":true,"result":{"url":"https://example.test/telegram","pending_update_count":3}}`))
+ }))
+ defer srv.Close()
+
+ info, err := newBotAPI(srv.URL, "123:secret", srv.Client()).GetWebhookInfo(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if info.URL != "https://example.test/telegram" || info.PendingUpdateCount != 3 {
+ t.Fatalf("webhook info = %+v", info)
+ }
+}
+
+func TestTransportErrorDoesNotExposeBotToken(t *testing.T) {
+ transportErr := errors.New("dial tcp 123:[email protected]:443: connection refused")
+ client := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
+ return nil, transportErr
+ })}
+
+ _, err := newBotAPI("https://api.example.test", "123:secret", client).GetMe(context.Background())
+ if err == nil {
+ t.Fatal("expected transport error")
+ }
+ if strings.Contains(err.Error(), "123:secret") {
+ t.Fatalf("transport error exposed bot token: %v", err)
+ }
+ if !errors.Is(err, transportErr) {
+ t.Fatalf("errors.Is lost transport cause: %v", err)
+ }
+}
+
+func TestConnectDispatchesAndAdvancesOffset(t *testing.T) {
+ var calls atomic.Int64
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if !strings.Contains(r.URL.Path, "getUpdates") {
+ _, _ = w.Write([]byte(`{"ok":true,"result":{}}`))
+ return
+ }
+ n := calls.Add(1)
+ var body getUpdatesParams
+ _ = json.NewDecoder(r.Body).Decode(&body)
+ switch n {
+ case 1:
+ if body.Offset != 0 {
+ t.Errorf("first poll offset = %d, want 0", body.Offset)
+ }
+ _, _ = w.Write([]byte(`{"ok":true,"result":[{"update_id":10,"message":{"message_id":1,"from":{"id":42,"first_name":"A"},"chat":{"id":42,"type":"private"},"text":"hi"}}]}`))
+ case 2:
+ if body.Offset != 11 {
+ t.Errorf("second poll offset = %d, want 11", body.Offset)
+ }
+ _, _ = w.Write([]byte(`{"ok":true,"result":[]}`))
+ default:
+ // Park until the test cancels.
+ <-r.Context().Done()
+ }
+ }))
+ defer srv.Close()
+
+ var received []channel.InboundMessage
+ done := make(chan struct{})
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ ch := &telegramChannel{
+ botID: 999,
+ botUsername: "my_bot",
+ api: newBotAPI(srv.URL, "123:abc", srv.Client()),
+ handler: func(ctx context.Context, m channel.InboundMessage) error {
+ received = append(received, m)
+ close(done)
+ return nil
+ },
+ logger: testLogger(),
+ }
+ go func() { _ = ch.Connect(ctx) }()
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ t.Fatal("message not dispatched")
+ }
+ cancel()
+ if len(received) != 1 || received[0].Text != "hi" {
+ t.Fatalf("received = %+v", received)
+ }
+}
+
+func TestChunkMessagePrefersNewlines(t *testing.T) {
+ text := strings.Repeat("a", 60) + "\n" + strings.Repeat("b", 60)
+ chunks := chunkMessage(text, 100)
+ if len(chunks) != 2 {
+ t.Fatalf("want 2 chunks, got %d: %v", len(chunks), chunks)
+ }
+ if !strings.HasSuffix(chunks[0], "a") || !strings.HasPrefix(chunks[1], "b") {
+ t.Errorf("split should land on the newline: %q | %q", chunks[0], chunks[1])
+ }
+}
+
+func TestChunkMessageCountsUTF16Units(t *testing.T) {
+ chunks := chunkMessage("😀a😀", 3)
+ if len(chunks) != 2 || chunks[0] != "😀a" || chunks[1] != "😀" {
+ t.Fatalf("chunks = %#v", chunks)
+ }
+ for _, chunk := range chunks {
+ if got := utf16Units(chunk); got > 3 {
+ t.Errorf("chunk %q uses %d UTF-16 units", chunk, got)
+ }
+ }
+}
+
+func TestSenderFallsBackOnlyForHTMLParseErrors(t *testing.T) {
+ var calls int
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ w.Header().Set("Content-Type", "application/json")
+ if calls == 1 {
+ _, _ = w.Write([]byte(`{"ok":false,"error_code":400,"description":"Bad Request: can't parse entities"}`))
+ return
+ }
+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":7,"chat":{"id":42,"type":"private"}}}`))
+ }))
+ defer srv.Close()
+
+ s := newSender(newBotAPI(srv.URL, "123:secret", srv.Client()), testLogger())
+ result, err := s.Send(context.Background(), channel.OutboundMessage{ChatID: "42", Text: "literal <tag>"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if calls != 2 || result.MessageID != "42:7" {
+ t.Fatalf("calls=%d result=%+v", calls, result)
+ }
+}
+
+func TestSenderUsesCurrentReplyParametersOnlyOnFirstChunk(t *testing.T) {
+ var requests []map[string]any
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var body map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Errorf("decode request: %v", err)
+ }
+ requests = append(requests, body)
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = fmt.Fprintf(w, `{"ok":true,"result":{"message_id":%d,"chat":{"id":42,"type":"private"}}}`, len(requests))
+ }))
+ defer srv.Close()
+
+ s := newSender(newBotAPI(srv.URL, "123:secret", srv.Client()), testLogger())
+ _, err := s.Send(context.Background(), channel.OutboundMessage{
+ ChatID: "42", Text: strings.Repeat("x", maxMessageUnits+1), ReplyTo: "42:17",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(requests) != 2 {
+ t.Fatalf("requests = %d, want 2", len(requests))
+ }
+ if _, exists := requests[0]["reply_to_message_id"]; exists {
+ t.Fatal("legacy reply_to_message_id must not be sent")
+ }
+ reply, ok := requests[0]["reply_parameters"].(map[string]any)
+ if !ok || reply["message_id"] != float64(17) || reply["allow_sending_without_reply"] != true {
+ t.Fatalf("first reply_parameters = %#v", requests[0]["reply_parameters"])
+ }
+ if _, exists := requests[1]["reply_parameters"]; exists {
+ t.Fatalf("second chunk unexpectedly quotes: %#v", requests[1])
+ }
+}
+
+func TestDispatchUnsupportedMediaInAddressedGroupPreservesTopicAndReply(t *testing.T) {
+ var got []sendMessageParams
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var body sendMessageParams
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Errorf("decode request: %v", err)
+ }
+ got = append(got, body)
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":7,"chat":{"id":-42,"type":"supergroup"}}}`))
+ }))
+ defer srv.Close()
+
+ c := &telegramChannel{
+ botID: 999, botUsername: "my_bot", api: newBotAPI(srv.URL, "123:secret", srv.Client()),
+ handler: func(context.Context, channel.InboundMessage) error { t.Fatal("media reached handler"); return nil },
+ logger: testLogger(),
+ }
+ base := Message{
+ MessageID: 21, From: &User{ID: 3, FirstName: "U"}, Chat: Chat{ID: -42, Type: "supergroup"},
+ Photo: []any{struct{}{}}, IsTopicMessage: true, MessageThreadID: 8,
+ }
+ if err := c.dispatch(context.Background(), Update{UpdateID: 1, Message: &base}); err != nil {
+ t.Fatal(err)
+ }
+ if len(got) != 0 {
+ t.Fatalf("unaddressed group media produced notice: %+v", got)
+ }
+ base.Caption = "@my_bot look"
+ base.CaptionEntities = []MessageEntity{{Type: "mention", Offset: 0, Length: 7}}
+ if err := c.dispatch(context.Background(), Update{UpdateID: 2, Message: &base}); err != nil {
+ t.Fatal(err)
+ }
+ if len(got) != 1 || got[0].Text != msgUnsupportedType || got[0].MessageThreadID != 8 ||
+ got[0].ReplyParameters == nil || got[0].ReplyParameters.MessageID != 21 {
+ t.Fatalf("addressed group notice = %+v", got)
+ }
+}
+
+func TestSendChatActionPreservesForumTopic(t *testing.T) {
+ var got map[string]any
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
+ t.Errorf("decode request: %v", err)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"ok":true,"result":true}`))
+ }))
+ defer srv.Close()
+
+ if err := newBotAPI(srv.URL, "123:secret", srv.Client()).SendChatAction(context.Background(), -42, 8); err != nil {
+ t.Fatal(err)
+ }
+ if got["chat_id"] != float64(-42) || got["action"] != "typing" || got["message_thread_id"] != float64(8) {
+ t.Fatalf("sendChatAction params = %#v", got)
+ }
+}
+
+func TestSendChatActionOmitsEmptyForumTopic(t *testing.T) {
+ var got map[string]any
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
+ t.Errorf("decode request: %v", err)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"ok":true,"result":true}`))
+ }))
+ defer srv.Close()
+
+ if err := newBotAPI(srv.URL, "123:secret", srv.Client()).SendChatAction(context.Background(), 42, 0); err != nil {
+ t.Fatal(err)
+ }
+ if _, exists := got["message_thread_id"]; exists {
+ t.Fatalf("empty message_thread_id must be omitted: %#v", got)
+ }
+}
+
+func TestFormatHTML(t *testing.T) {
+ got := formatHTML("# Title\n**bold** and `code` and [link](https://e.co/a_b)\n```go\nx < 1\n```")
+ for _, want := range []string{
+ "<b>Title</b>",
+ "<b>bold</b>",
+ "<code>code</code>",
+ `<a href="https://e.co/a_b">link</a>`,
+ `<pre><code class="language-go">x &lt; 1</code></pre>`,
+ } {
+ if !strings.Contains(got, want) {
+ t.Errorf("formatHTML missing %q in:\n%s", want, got)
+ }
+ }
+ if plain := formatHTML("a < b & c"); !strings.Contains(plain, "a &lt; b &amp; c") {
+ t.Errorf("entities must be escaped: %q", plain)
+ }
+}
+
+func testLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) }
+
+type roundTripFunc func(*http.Request) (*http.Response, error)
+
+func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
diff --git a/server/internal/migrations/telegram_origin_migration_test.go b/server/internal/migrations/telegram_origin_migration_test.go
new file mode 100644
index 0000000000..3cfcdc31bb
--- /dev/null
+++ b/server/internal/migrations/telegram_origin_migration_test.go
@@ -0,0 +1,102 @@
+package migrations
+
+import (
+ "context"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+const telegramOriginMigrationTestSchema = "telegram_origin_migration_test"
+
+func TestTelegramOriginMigrationsUpDownAndCatalog(t *testing.T) {
+ dbURL := os.Getenv("DATABASE_URL")
+ if dbURL == "" {
+ t.Skip("integration test requires Postgres at DATABASE_URL")
+ }
+
+ ctx := context.Background()
+ pool, err := pgxpool.New(ctx, dbURL)
+ if err != nil {
+ t.Fatalf("connect to Postgres: %v", err)
+ }
+ defer pool.Close()
+
+ conn, err := pool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire Postgres connection: %v", err)
+ }
+ defer conn.Release()
+
+ cleanup := func() {
+ _, _ = pool.Exec(context.Background(), "DROP SCHEMA IF EXISTS "+telegramOriginMigrationTestSchema+" CASCADE")
+ }
+ cleanup()
+ t.Cleanup(cleanup)
+ if _, err := conn.Exec(ctx, "CREATE SCHEMA "+telegramOriginMigrationTestSchema); err != nil {
+ t.Fatalf("create isolated migration schema: %v", err)
+ }
+ if _, err := conn.Exec(ctx, `SELECT set_config('search_path', $1, false)`, telegramOriginMigrationTestSchema); err != nil {
+ t.Fatalf("set isolated migration search path: %v", err)
+ }
+
+ if _, err := conn.Exec(ctx, `
+ CREATE TABLE issue (
+ id UUID PRIMARY KEY,
+ origin_type TEXT NULL
+ );
+ ALTER TABLE issue ADD CONSTRAINT issue_origin_type_check
+ CHECK (origin_type IN ('autopilot', 'quick_create', 'lark_chat', 'slack_chat', 'agent_create', 'dingtalk_chat', 'wecom_chat'));
+ `); err != nil {
+ t.Fatalf("create pre-Telegram issue table: %v", err)
+ }
+
+ assertTelegramOriginRejected(t, ctx, conn.Conn(), "00000000-0000-4000-8000-000000000001")
+
+ applyMigrationFile(t, ctx, conn.Conn(), "366_issue_origin_telegram_chat.up.sql")
+ assertTelegramOriginConstraint(t, ctx, conn.Conn(), false, true)
+ if _, err := conn.Exec(ctx, `INSERT INTO issue (id, origin_type) VALUES ($1, 'telegram_chat')`, "00000000-0000-4000-8000-000000000002"); err != nil {
+ t.Fatalf("insert telegram_chat after widening constraint: %v", err)
+ }
+
+ applyMigrationFile(t, ctx, conn.Conn(), "367_issue_origin_telegram_chat_validate.up.sql")
+ assertTelegramOriginConstraint(t, ctx, conn.Conn(), true, true)
+
+ applyMigrationFile(t, ctx, conn.Conn(), "367_issue_origin_telegram_chat_validate.down.sql")
+ assertTelegramOriginConstraint(t, ctx, conn.Conn(), false, true)
+ if _, err := conn.Exec(ctx, `DELETE FROM issue WHERE origin_type = 'telegram_chat'`); err != nil {
+ t.Fatalf("remove Telegram row before narrowing rollback: %v", err)
+ }
+ applyMigrationFile(t, ctx, conn.Conn(), "366_issue_origin_telegram_chat.down.sql")
+ assertTelegramOriginConstraint(t, ctx, conn.Conn(), true, false)
+ assertTelegramOriginRejected(t, ctx, conn.Conn(), "00000000-0000-4000-8000-000000000003")
+}
+
+func assertTelegramOriginConstraint(t *testing.T, ctx context.Context, conn *pgx.Conn, wantValidated, wantTelegram bool) {
+ t.Helper()
+ var validated bool
+ var definition string
+ if err := conn.QueryRow(ctx, `
+ SELECT convalidated, pg_get_constraintdef(oid)
+ FROM pg_constraint
+ WHERE conrelid = 'issue'::regclass AND conname = 'issue_origin_type_check'
+ `).Scan(&validated, &definition); err != nil {
+ t.Fatalf("inspect issue origin constraint: %v", err)
+ }
+ if validated != wantValidated {
+ t.Fatalf("constraint validated = %t, want %t", validated, wantValidated)
+ }
+ if strings.Contains(definition, "telegram_chat") != wantTelegram {
+ t.Fatalf("constraint Telegram membership = %t, want %t: %s", strings.Contains(definition, "telegram_chat"), wantTelegram, definition)
+ }
+}
+
+func assertTelegramOriginRejected(t *testing.T, ctx context.Context, conn *pgx.Conn, id string) {
+ t.Helper()
+ if _, err := conn.Exec(ctx, `INSERT INTO issue (id, origin_type) VALUES ($1, 'telegram_chat')`, id); !isCheckViolation(err) {
+ t.Fatalf("insert telegram_chat under pre-Telegram constraint: got %v, want check violation", err)
+ }
+}
diff --git a/server/migrations/366_issue_origin_telegram_chat.down.sql b/server/migrations/366_issue_origin_telegram_chat.down.sql
new file mode 100644
index 0000000000..0ffa9f7a92
--- /dev/null
+++ b/server/migrations/366_issue_origin_telegram_chat.down.sql
@@ -0,0 +1,8 @@
+-- Restore the validated pre-Telegram constraint. This intentionally fails
+-- closed while telegram_chat rows remain, because a rollback must not leave a
+-- trusted constraint that existing rows violate.
+ALTER TABLE issue DROP CONSTRAINT IF EXISTS issue_origin_type_check;
+ALTER TABLE issue ADD CONSTRAINT issue_origin_type_check
+ CHECK (origin_type IN ('autopilot', 'quick_create', 'lark_chat', 'slack_chat', 'agent_create', 'dingtalk_chat', 'wecom_chat'))
+ NOT VALID;
+ALTER TABLE issue VALIDATE CONSTRAINT issue_origin_type_check;
diff --git a/server/migrations/366_issue_origin_telegram_chat.up.sql b/server/migrations/366_issue_origin_telegram_chat.up.sql
new file mode 100644
index 0000000000..626b91619e
--- /dev/null
+++ b/server/migrations/366_issue_origin_telegram_chat.up.sql
@@ -0,0 +1,11 @@
+-- Extend issue.origin_type for issues created by the Telegram `/issue`
+-- command. origin_id stores the chat_session id, matching the existing Lark,
+-- Slack, DingTalk, and WeCom channel origins.
+--
+-- This only widens the allowed set. Recreate the CHECK as NOT VALID so the
+-- ACCESS EXCLUSIVE lock is held briefly; migration 367 performs the table scan
+-- under SHARE UPDATE EXCLUSIVE without blocking normal reads and writes.
+ALTER TABLE issue DROP CONSTRAINT IF EXISTS issue_origin_type_check;
+ALTER TABLE issue ADD CONSTRAINT issue_origin_type_check
+ CHECK (origin_type IN ('autopilot', 'quick_create', 'lark_chat', 'slack_chat', 'agent_create', 'dingtalk_chat', 'wecom_chat', 'telegram_chat'))
+ NOT VALID;
diff --git a/server/migrations/367_issue_origin_telegram_chat_validate.down.sql b/server/migrations/367_issue_origin_telegram_chat_validate.down.sql
new file mode 100644
index 0000000000..9f9da894ec
--- /dev/null
+++ b/server/migrations/367_issue_origin_telegram_chat_validate.down.sql
@@ -0,0 +1,6 @@
+-- PostgreSQL cannot mark a validated constraint NOT VALID. Recreate the state
+-- immediately after migration 366: enforcing new writes but not yet validated.
+ALTER TABLE issue DROP CONSTRAINT IF EXISTS issue_origin_type_check;
+ALTER TABLE issue ADD CONSTRAINT issue_origin_type_check
+ CHECK (origin_type IN ('autopilot', 'quick_create', 'lark_chat', 'slack_chat', 'agent_create', 'dingtalk_chat', 'wecom_chat', 'telegram_chat'))
+ NOT VALID;
diff --git a/server/migrations/367_issue_origin_telegram_chat_validate.up.sql b/server/migrations/367_issue_origin_telegram_chat_validate.up.sql
new file mode 100644
index 0000000000..390fc3f344
--- /dev/null
+++ b/server/migrations/367_issue_origin_telegram_chat_validate.up.sql
@@ -0,0 +1,3 @@
+-- Validate the widened CHECK separately from migration 366 so the validation
+-- scan does not inherit migration 366's ACCESS EXCLUSIVE lock.
+ALTER TABLE issue VALIDATE CONSTRAINT issue_origin_type_check;
diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.go
index 0550971789..ea29a5f8ef 100644
--- a/server/pkg/protocol/events.go
+++ b/server/pkg/protocol/events.go
@@ -200,4 +200,9 @@ const (
// installations query on either.
EventWecomInstallationCreated = "wecom_installation:created"
EventWecomInstallationRevoked = "wecom_installation:revoked"
+
+ // Telegram installation lifecycle. Same contract as the Slack pair:
+ // front-ends invalidate the Telegram installations query on either.
+ EventTelegramInstallationCreated = "telegram_installation:created"
+ EventTelegramInstallationRevoked = "telegram_installation:revoked"
)