Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

feat: Telegram collaboration bridge (CHOO-1686) (#187)

Christian McDermott7d00b239a3b0
diff --git a/.env.example b/.env.example
index f77490580..182948124 100644
--- a/.env.example
+++ b/.env.example
@@ -60,8 +60,9 @@ GATEWAY_ADMIN_PASSWORD=
FRONTEND_BASE_URL=http://localhost:5173
# Public origin of the gateway HTTP API (used to build the switchdash:// deeplink
-# HTTP redirect so "Open in Switch Console" is clickable on Discord and other
-# http-only platforms). Leave unset to post the raw switchdash:// deeplink.
+# HTTP redirect so "Open in Switch Console" is clickable on Discord, Telegram
+# and other http-only platforms). Leave unset to post the raw switchdash://
+# deeplink.
# GATEWAY_PUBLIC_URL=http://localhost:8000
# ── Mattermost (local dev) ───────────────────────────────────────────────────
@@ -71,8 +72,8 @@ MATTERMOST_TEAM_NAME=switch
MATTERMOST_USER=user
MATTERMOST_USER_PASSWORD=
-# Teams has no local-dev env vars: a Teams workspace is connected per-bridge
-# through the gateway (all Azure app credentials live in the bridge's stored
+# Teams and Telegram have no local-dev env vars: both are connected per-bridge
+# through the gateway (all credentials live in the bridge's stored
# connection_config), never in global config.
# ── OIDC (optional — MCP OAuth token validation; bring your own IdP) ─────────
diff --git a/.github/workflows/pr-ci.yml b/.github/workflows/pr-ci.yml
index 67bba2b8e..7801e615b 100644
--- a/.github/workflows/pr-ci.yml
+++ b/.github/workflows/pr-ci.yml
@@ -160,8 +160,14 @@ jobs:
# nothing verified the sync had run — the two could drift with only a
# comment asking nicely, which is how it silently stopped running once
# already (CHOO-1865).
+ #
+ # The filter is the package name, not the directory. `pnpm --filter` on a
+ # name nothing matches prints a notice and exits 0, so getting it wrong
+ # does not fail the build — it just stops checking, which is how this
+ # died the second time (the directory was renamed to
+ # switch-console-desktop, the package is still @switch-console/desktop).
- name: Bundled standalone compose is current
- run: pnpm --filter switch-console-desktop run sync:compose:check
+ run: pnpm --filter @switch-console/desktop run sync:compose:check
- name: Build workspace packages
run: pnpm -r --filter './packages/**' run build
diff --git a/.gitleaks.toml b/.gitleaks.toml
index 5e077bcca..e97630c30 100644
--- a/.gitleaks.toml
+++ b/.gitleaks.toml
@@ -14,6 +14,9 @@ regexes = [
'''"mattermost", MattermostAdapter, MattermostConnectionConfig''',
]
paths = [
- # Log-redaction tests exercise deliberately fake vendor tokens.
- '''console/apps/switch-console-desktop/src/main/lib/file-logger\.test\.ts$''',
+ # Log-redaction tests exercise deliberately fake vendor tokens. Both spellings
+ # of the path: gitleaks scans history, where the file lived under
+ # `dash/apps/switchdash-desktop/` before the rename in CHOO-2008, and those
+ # commits still carry the fixtures.
+ '''(dash/apps/switchdash-desktop|console/apps/switch-console-desktop)/src/main/lib/file-logger\.test\.ts$''',
]
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dd224a99e..dedf5f760 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -47,7 +47,54 @@ version of their own to them without also giving them a release of their own.
### [0.14.0] - 2026-08-14
#### Added
-
+- Telegram collaboration bridge, at parity with Slack, Mattermost and Discord
+ (CHOO-1686). A single bot backs every agent — Telegram has no per-message
+ identity override — so an agent is named at the head of its messages, beside a
+ stable colour derived from that name, which is the closest thing to a
+ per-agent avatar Telegram allows. Inbound arrives by long polling, so no
+ public ingress is needed. Chats cannot be created by a bot, so a Telegram
+ connection declares that up front and rooms are provisioned when the bot is
+ added to a chat. Multi-file messages post as a
+ single album, and outbound Markdown is converted to Telegram's HTML subset
+ rather than its stricter MarkdownV2. See `docs/bridges/TELEGRAM_SETUP.md`.
+- One-click install links for a bridge, offered on the operator dashboard and
+ built by the adapter (`install_links`); empty for platforms installed through
+ their own admin UI. Telegram supplies one, for groups: pick the group, confirm,
+ done. It asks for **no permissions at all** — a bot posts and deletes its own
+ messages in a group as an ordinary member — so adding the bot no longer means
+ promoting it by hand. Setting a Telegram bridge up is now one BotFather setting
+ (Group Privacy off, once per bot, before the bot is added anywhere) and then a
+ link per group. Channels are added from their Administrators screen, and get no
+ link: that would need Telegram's `admin=` parameter, which not every client
+ implements, and the ones that do not open a chat with the bot instead — a link
+ that works for some people is worse than a documented step that works for all
+ of them. The dashboard's **Add to a chat** dialog says so: alongside the links,
+ a bridge can supply an `install_note` naming the chats no link reaches and the
+ route they take instead, so a missing button is never all the operator sees.
+- A bridged chat is told what the bridge can see in it, and told again whenever
+ that changes — so promoting the bot confirms itself and retracts the earlier
+ warning, and a demotion does not pass unmentioned. Visibility is settled per
+ chat rather than inferred from the bot's global privacy setting, which is what
+ made an administrator bot report a fault it did not have. A chat the bridge can
+ only see mentions in — no admin, privacy mode on — is a supported way to run
+ and is disclosed as one: a notice in the chat, and a warning naming each such
+ chat at startup. Where the answer rests on the global setting rather than on
+ admin status it is taken on trust and logged as such: Telegram reads that
+ setting when the bot joins and no API call reports which value a given chat
+ got, so a bot that predates the change is still filtered and only a re-add or a
+ promotion fixes it.
+
+- Whether a messaging-app connection may create channels is now declared rather
+ than discovered by failing, in two parts: what the platform can do at all
+ (Telegram cannot — the Bot API has no call for it) and what an operator
+ permits this connection to do, set when the app is registered and changeable
+ afterwards. The second can only narrow the first. A deployment can therefore
+ withhold channel creation from Slack or Teams as well, for a bot that holds no
+ such permission or an organisation that would rather channels were made by
+ people. The answer reaches everyone who acts on it: the room forms in the
+ dashboard and Switch Console stop offering the option and say which reason
+ applies, `list_bridges` carries `can_create_channels` so an agent can choose a
+ bridge that works, and a refused create is a `400` naming what to do instead.
- `opencode` is a registerable known agent type, alongside `claude-code` and
`codex`. It carries its own option set — auto-session, working directory and
notify-user — rather than borrowing another type's, and the start-session
@@ -55,7 +102,75 @@ version of their own to them without also giving them a release of their own.
its first positional argument as a directory to open.
#### Fixed
-
+- Creating a room on a bridge that cannot make channels returned "Internal
+ Server Error". The adapter's explanation — make the chat on the platform, add
+ the app, Switch adopts it — was thrown away at four of the six doors into room
+ creation, because `NotImplementedError` subclasses `RuntimeError` and every
+ caller catches only `ValueError`. It is now a `ValueError` subclass, so the
+ message survives to the caller as a 4xx. Opening a DM is governed the same way.
+- Telegram admin notices reached the chat as Markdown source, `**` and backticks
+ included. They are written in Switch Markdown like every other body but were
+ handed to the API without the conversion, and everything goes out with
+ parse_mode HTML. Two notices were also written with single-asterisk emphasis,
+ which no platform's converter recognises — Slack bolded them by accident and
+ Telegram italicised them.
+- The "Open in Switch Console" link on Telegram no longer disappears, and can no
+ longer take its message with it. It is a `switchdash://` URL and Telegram
+ renders only `http(s)`/`tg:`: the client dropped the link and kept the label,
+ or the API rejected the whole message. An unsupported scheme is now posted as
+ tap-to-copy text, and the bridge warns at startup when a platform that only
+ renders web links is running without `GATEWAY_PUBLIC_URL` — which is what
+ makes the link real, in the Telegram app and on Telegram Web alike.
+- A Telegram message Telegram rejects is retried unformatted whatever the
+ reason. The retry only fired when the error contained "parse", so a rejection
+ worded any other way — "unsupported URL protocol" among them — lost the entire
+ message to a single log line.
+- A Telegram command that needs an argument is usable from the `/` menu.
+ Telegram sends a command the instant it is tapped, with no chance to type one
+ and no way for a bot to declare that one is wanted, so `/invite_agent` always
+ arrived bare — and answering with its usage line left retyping the whole
+ command by hand as the only way through, which is what the menu was for. The
+ bot now asks for what is missing, with Telegram's own reply prompt so the
+ composer opens ready, and runs the command when you answer. Giving the
+ argument up front skips it; the prompt is one-shot, so talk that continues
+ under it stays ordinary chat.
+- The no-agents notice advertises `/invite_agent` on Telegram, the only spelling
+ Telegram will register and therefore the only one its command menu offers. It
+ named the hyphenated form, which the client will not autocomplete. All three
+ forms are now listed.
+- The Telegram brand icon renders correctly in Switch Console's dark theme. The
+ plane was a hole punched through the disc rather than a white shape, so it
+ showed the background through it and came out black.
+- Bridge row action icons line up down the column again. A row carries one icon
+ or two depending on whether its platform offers an install link, and the pair
+ was not anchored to the same edge as the single, so the delete buttons sat at
+ different positions on different rows.
+- Telegram links are built from the username the Bot API reports rather than the
+ one in the bridge's config. A configured name that is not the bot's resolves to
+ whichever account does own it, so every link opened a chat with a stranger —
+ and the mismatch was already detected and then ignored, with the wrong value
+ used anyway. The bot's own name wins and the correction is logged.
+- The "add to a Telegram group" link is withheld from a bot BotFather has barred
+ from groups. Telegram answers such a link by opening a chat with the bot, which
+ from the outside is indistinguishable from a link that does nothing; the reason
+ is logged with the setting to change instead.
+- The group install link no longer asks to be an administrator, which made it
+ unusable for the groups most people have. Telegram builds that picker from
+ groups the person already administers, excluding basic groups — promoting a
+ bot in one converts it to a supergroup — so for anyone whose groups are all
+ basic it offered nothing to pick and Telegram opened a chat with the bot
+ instead, reading as a link that did nothing. Admin was only ever bought for
+ the privacy-mode exemption, and turning Group Privacy off in BotFather buys
+ the same thing once per bot rather than once per group. Promotion remains
+ documented as the repair for a single chat that was added before that setting
+ was changed, and the bot asks for it in the chat when it applies.
+- A room follows its Telegram chat when the chat is reissued a new id, which
+ Telegram does silently whenever a group becomes a supergroup. The room was
+ left bound to the old id, so nothing anyone typed reached Switch again while
+ sends kept working — Telegram forwards those — leaving a bridge that looked
+ alive and was deaf. Adapters now report the change (`CollaborationAdapter`
+ gains `set_channel_migration_handler`) and the room is re-pointed, or the
+ refusal is logged with the id to re-point it at by hand.
- The OpenCode server-side connector no longer hangs when the OpenCode server
raises a tool permission request. The connector's event loop ignored
`permission.updated`, so no reply was ever sent, the session never went idle,
@@ -390,7 +505,9 @@ version of their own to them without also giving them a release of their own.
### [0.23.0] - 2026-08-14
#### Added
-
+- Telegram brand icon, platform label and setup-guide link, so Telegram-bridged
+ rooms show the "open channel" button and the attach form links the right guide
+ (CHOO-1686). Telegram bot tokens are also redacted from the diagnostic logs.
- **OpenCode is now a supported Switch agent type**, locally and on remote
hosts. An OpenCode session can be onboarded as a Switch agent, join rooms,
take injected prompts, and be reset, compacted or interrupted from a room.
@@ -456,6 +573,10 @@ version of their own to them without also giving them a release of their own.
can no longer be hidden. The shortcuts themselves are unchanged.
#### Fixed
+- Opening a room from a deeplink expands the sidebar groups hiding it
+ (CHOO-1686). The reveal ran once, before the room a session belongs to had
+ loaded, and never again — so the view routed correctly to a row that stayed
+ collapsed. Affects any bridge, not only Telegram.
- Add Agent no longer stalls with an unset agent type once more than one Switch
connector is installed. The form auto-selected a type only when exactly one
was available, so a second connector left it blank — and since the directory
@@ -1323,6 +1444,17 @@ compatibility signal. History for those is in the git log.
installs re-download.
+#### Changed
+- The room-workflow skill covers Telegram: attachments cross the bridge as real
+ uploads, chats cannot be created by a bot at all (so `create_room` fails there
+ for every channel type), forum topics thread natively, and formatting has no
+ tables and a 4096-character cap (CHOO-1686). It also warns that a Telegram
+ room may be mention-only, where unaddressed talk never reaches Switch at all
+ and `read_context` cannot recover it — the one place the skill's "pull the
+ rest with `read_context`" promise does not hold. The slash-command and
+ attachment platform lists now also name Discord, which had been left out of
+ both.
+
### [0.9.1] - 2026-08-12
#### Changed
@@ -1395,6 +1527,15 @@ manifest history.
### [0.3.3] - 2026-08-14
#### Changed
+- The room-workflow skill covers Telegram: attachments cross the bridge as real
+ uploads, chats cannot be created by a bot at all (so `create_room` fails there
+ for every channel type), forum topics thread natively, and formatting has no
+ tables and a 4096-character cap (CHOO-1686). It also warns that a Telegram
+ room may be mention-only, where unaddressed talk never reaches Switch at all
+ and `read_context` cannot recover it — the one place the skill's "pull the
+ rest with `read_context`" promise does not hold. The slash-command and
+ attachment platform lists now also name Discord, which had been left out of
+ both.
- The room-workflow skill lists `opencode` alongside `codex` and `claude-code`
wherever it enumerates known agent types — the `list_agents` filter and the
per-type options of `update_agent_detail` (#203). The plugin version bumps so
diff --git a/CLAUDE.md b/CLAUDE.md
index b4b1f282f..f062281f9 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -22,7 +22,7 @@ history — a later commit cannot take it back. Keep internal detail out of it:
## Project Overview
-Switch is an AI agent orchestration and governance platform. It onboards, orchestrates, and secures third-party AI agents using Matrix (Tuwunel) as the internal message bus. Agents register via the Agent Bridge API and communicate through Matrix rooms with room-scoped protection, observability, and collaboration bridges to external platforms (Slack, Mattermost).
+Switch is an AI agent orchestration and governance platform. It onboards, orchestrates, and secures third-party AI agents using Matrix (Tuwunel) as the internal message bus. Agents register via the Agent Bridge API and communicate through Matrix rooms with room-scoped protection, observability, and collaboration bridges to external platforms (Slack, Mattermost, Discord, Teams, Telegram).
The target architecture is documented in `docs/`.
@@ -80,7 +80,7 @@ just test -k "test_name" # run specific test
- `clients/` — Matrix clients (agent, user, resource manager, observe)
- `bridges/` — External integrations
- `agent/` — Agent Bridge (HTTP API, MCP server, server-side connectors)
- - `collaboration/` — Collaboration Bridge (Slack, Mattermost adapters)
+ - `collaboration/` — Collaboration Bridge (Slack, Mattermost, Discord, Teams, Telegram adapters)
- `observe/` — Observe Bridge (event sinks)
- `resource/` — Resource Bridge (platform resource management)
- `protect/` — Protection pipeline (checks, protect bridge, API)
@@ -234,7 +234,7 @@ exist:
event stream, room slots, failure handling). Authoritative where it and
`ARCHITECTURE.md` overlap
- `docs/bridges/` — collaboration bridge setup: `README.md` plus one page each
- for Slack, Mattermost, Discord, and Teams
+ for Slack, Mattermost, Discord, Teams, and Telegram
There is no separate schema, room-design, HTTP-API or MCP-surface document. Read
those from the code: `core/switch_core/db/models.py` for the schema,
diff --git a/README.md b/README.md
index c9084d1bc..925261809 100644
--- a/README.md
+++ b/README.md
@@ -19,7 +19,7 @@ your team, chat where you chat, take on tasks, and work under rules you set.
- 🤝 **Multi-agent, multi-human** — shared rooms where whole teams of people and agents work together, not 1:1 chatbot sessions.
- 🌍 **Any agent, anywhere** — on a laptop or a server, from any provider or company: Claude Code on your machine, LangChain, OpenCode, OpenAI Codex — anything that speaks MCP or HTTP.
-- 💬 **In your team's chat** — agents join your team in Slack and Microsoft Teams.
+- 💬 **In your team's chat** — agents join your team in Slack, Mattermost, Discord, Microsoft Teams and Telegram.
- 🧩 **Workflows on top** — roles, tasks, delegation, and shared context turn a room of agents into an operation.
- 🛡️ **Governed & observable** — every interaction is protected and visible by design.
@@ -36,12 +36,14 @@ flowchart LR
subgraph Humans["Humans"]
H1[Slack]
H2[Mattermost]
+ H3[Telegram]
end
A1 -->|Agent Bridge| CORE
A2 -->|Agent Bridge| CORE
H1 -->|Collaboration Bridge| CORE
H2 -->|Collaboration Bridge| CORE
+ H3 -->|Collaboration Bridge| CORE
subgraph Switch["Switch Core"]
CORE[Rooms · Protection · Observability]
diff --git a/connectors/claude-code-plugin/skills/switch/SKILL.md b/connectors/claude-code-plugin/skills/switch/SKILL.md
index 0747fc308..df52407a8 100644
--- a/connectors/claude-code-plugin/skills/switch/SKILL.md
+++ b/connectors/claude-code-plugin/skills/switch/SKILL.md
@@ -208,15 +208,16 @@ local operator is explicitly steering you outside the room conversation.
- Get ids from `read_context`'s `threads`, or from a notification's
`thread_id`. **When a message you receive carries a `thread_id`, reply with
that same `thread_id`** so the conversation stays in its thread.
-- Threads bridge to and from Mattermost natively. You are only notified of
- threaded replies that address you; pull the rest with `read_context`.
+- Threads bridge to and from Mattermost natively, and to Telegram forum
+ topics. You are only notified of threaded replies that address you; pull the
+ rest with `read_context`.
## Sending and receiving attachments
Messages can carry file attachments of **any type** — images, `.md`, `.csv`,
`.pdf`, logs, code — and a single message can carry **several**. Both
directions work in any room; on bridged rooms the attachment crosses the
-bridge as a real platform file upload (Slack, Mattermost).
+bridge as a real platform file upload (Slack, Mattermost, Discord, Telegram).
### Receiving
@@ -353,9 +354,14 @@ none of it is needed to take part in a conversation.
### Creating rooms
- **`list_bridges`** — the collaboration bridges configured on this instance:
- `{id, type, display_name, status, is_default}`. Only `status == "active"`
- bridges are usable. `is_default` marks the one `create_room` uses when no
- `bridge_id` is given (at most one per instance).
+ `{id, type, display_name, status, is_default, can_create_channels}`. Only
+ `status == "active"` bridges are usable. `is_default` marks the one
+ `create_room` uses when no `bridge_id` is given (at most one per instance).
+ `can_create_channels` is false when Switch cannot make a channel there —
+ either the platform has no such call (Telegram) or an operator has withheld
+ it, which can apply to any platform. Creating a room on one of those fails,
+ so read it before offering: the chat is made on the platform, the Switch app
+ added to it, and the room adopted from that.
- **`create_room`** — provision a room. Required: `name`, `description`,
`agent_names`. Commonly used: `bridge_id`, `internal_only`, `channel_type`
(`"channel_public"`, `"channel_private"`, `"direct"`), `user_names`,
@@ -366,8 +372,11 @@ none of it is needed to take part in a conversation.
- **`update_room`** — change an existing room, including its `aliases` map.
- **`invite_agent_to_room`** — add an existing agent to an existing room by
name. Humans and agents can do the same from inside a room with the
- `!invite-agent @agent-name` command (also the `/invite-agent` Slack slash
- command on bridged Slack channels).
+ `!invite-agent @agent-name` command (also the `/invite-agent` slash command
+ on bridged Slack, Discord and Telegram channels; Telegram registers it as
+ `/invite_agent`, since it will not accept a hyphen in a command). On Telegram
+ a command tapped from the `/` menu is sent immediately with no argument, so
+ the bot asks for the one it needs and runs when you reply with it.
- **`add_users_to_room`** — add human users to an existing room by name, the
counterpart to `invite_agent_to_room`. Names that cannot be resolved come
back in the response rather than failing silently — surface them.
@@ -414,7 +423,9 @@ agents to coordinate."
1. Call `list_bridges`.
2. Show them the active bridges (display name + type), noting which is
- `is_default`, and ask which to use — or whether to skip bridging.
+ `is_default`, and ask which to use — or whether to skip bridging. Leave out
+ any whose `can_create_channels` is false, or say what it needs instead;
+ offering one is offering a room that cannot be made.
3. Pass their chosen `bridge_id` and `channel_type` (usually
`"channel_public"` or `"channel_private"`) to `create_room`. Omit
`bridge_id` to accept the default; pass `internal_only=True` for no channel.
@@ -438,6 +449,14 @@ For a private 1:1 between one agent and one human, create a room with
- **Mattermost**: DMs are user-initiated from the client, so creating a
`direct` room here fails — the user starts the DM with the agent's bot and
Switch picks it up automatically.
+- **Telegram**: same as Mattermost — the user messages the bot first and
+ Switch adopts the chat. Telegram bots cannot create chats at all, so
+ `create_room` fails on a Telegram bridge for *every* channel type, not just
+ `direct`; the chat is made in a Telegram client and the bot added to it.
+ `list_bridges` reports this as `can_create_channels: false`, so check there
+ before offering to make a room rather than finding out from the failure —
+ and note an operator can withhold channel creation from any platform, so a
+ false answer is not Telegram-specific.
The user must already be known to Switch on the bridge (they have messaged the
workspace before). If not, creation fails loudly with `no user '<name>' is
@@ -635,6 +654,16 @@ Your messages render on whatever platform the room is bridged to
the bold identifier and separate fields with `·` or `—`.
- **Mattermost** renders full Markdown, tables included — **use a table** there
for a multi-item attribute list.
+- **Telegram** renders bold, italic, strikethrough, `inline code`, code blocks
+ and `[label](url)` links, but **no tables** — treat it like Slack. A message
+ over 4096 characters is split across several posts, so keep updates tight.
+ Every agent posts through one bot with its name at the head of the message,
+ so do not repeat your own name in the body.
+ - A Telegram room may be **mention-only**: where the bot is not an
+ administrator of the chat, Telegram delivers it nothing but messages
+ tagging it, replies and commands. Unaddressed talk never reaches Switch at
+ all there, so `read_context` cannot recover it — it is absent, not
+ filtered. The bridge says so in the chat when it applies.
When unsure, prefer the Slack-safe shape — it reads fine everywhere.
diff --git a/connectors/codex-plugin/skills/switch/SKILL.md b/connectors/codex-plugin/skills/switch/SKILL.md
index e452ad708..7aa8003ac 100644
--- a/connectors/codex-plugin/skills/switch/SKILL.md
+++ b/connectors/codex-plugin/skills/switch/SKILL.md
@@ -214,15 +214,16 @@ local operator is explicitly steering you outside the room conversation.
`thread_id` appears there only when the message is already in a thread.
**When a message you receive carries a `thread_id`, reply with that same
`thread_id`** so the conversation stays in its thread.
-- Threads bridge to and from Mattermost natively. You are only delivered
- threaded replies that address you; pull the rest with `read_context`.
+- Threads bridge to and from Mattermost natively, and to Telegram forum
+ topics. You are only delivered threaded replies that address you; pull the
+ rest with `read_context`.
## Sending and receiving attachments
Messages can carry file attachments of **any type** — images, `.md`, `.csv`,
`.pdf`, logs, code — and a single message can carry **several**. Both
directions work in any room; on bridged rooms the attachment crosses the
-bridge as a real platform file upload (Slack, Mattermost).
+bridge as a real platform file upload (Slack, Mattermost, Discord, Telegram).
### Receiving
@@ -357,9 +358,14 @@ none of it is needed to take part in a conversation.
### Creating rooms
- **`list_bridges`** — the collaboration bridges configured on this instance:
- `{id, type, display_name, status, is_default}`. Only `status == "active"`
- bridges are usable. `is_default` marks the one `create_room` uses when no
- `bridge_id` is given (at most one per instance).
+ `{id, type, display_name, status, is_default, can_create_channels}`. Only
+ `status == "active"` bridges are usable. `is_default` marks the one
+ `create_room` uses when no `bridge_id` is given (at most one per instance).
+ `can_create_channels` is false when Switch cannot make a channel there —
+ either the platform has no such call (Telegram) or an operator has withheld
+ it, which can apply to any platform. Creating a room on one of those fails,
+ so read it before offering: the chat is made on the platform, the Switch app
+ added to it, and the room adopted from that.
- **`create_room`** — provision a room. Required: `name`, `description`,
`agent_names`. Commonly used: `bridge_id`, `internal_only`, `channel_type`
(`"channel_public"`, `"channel_private"`, `"direct"`), `user_names`,
@@ -370,8 +376,11 @@ none of it is needed to take part in a conversation.
- **`update_room`** — change an existing room, including its `aliases` map.
- **`invite_agent_to_room`** — add an existing agent to an existing room by
name. Humans and agents can do the same from inside a room with the
- `!invite-agent @agent-name` command (also the `/invite-agent` Slack slash
- command on bridged Slack channels).
+ `!invite-agent @agent-name` command (also the `/invite-agent` slash command
+ on bridged Slack, Discord and Telegram channels; Telegram registers it as
+ `/invite_agent`, since it will not accept a hyphen in a command). On Telegram
+ a command tapped from the `/` menu is sent immediately with no argument, so
+ the bot asks for the one it needs and runs when you reply with it.
- **`add_users_to_room`** — add human users to an existing room by name, the
counterpart to `invite_agent_to_room`. Names that cannot be resolved come
back in the response rather than failing silently — surface them.
@@ -418,7 +427,9 @@ agents to coordinate."
1. Call `list_bridges`.
2. Show them the active bridges (display name + type), noting which is
- `is_default`, and ask which to use — or whether to skip bridging.
+ `is_default`, and ask which to use — or whether to skip bridging. Leave out
+ any whose `can_create_channels` is false, or say what it needs instead;
+ offering one is offering a room that cannot be made.
3. Pass their chosen `bridge_id` and `channel_type` (usually
`"channel_public"` or `"channel_private"`) to `create_room`. Omit
`bridge_id` to accept the default; pass `internal_only=True` for no channel.
@@ -442,6 +453,14 @@ For a private 1:1 between one agent and one human, create a room with
- **Mattermost**: DMs are user-initiated from the client, so creating a
`direct` room here fails — the user starts the DM with the agent's bot and
Switch picks it up automatically.
+- **Telegram**: same as Mattermost — the user messages the bot first and
+ Switch adopts the chat. Telegram bots cannot create chats at all, so
+ `create_room` fails on a Telegram bridge for *every* channel type, not just
+ `direct`; the chat is made in a Telegram client and the bot added to it.
+ `list_bridges` reports this as `can_create_channels: false`, so check there
+ before offering to make a room rather than finding out from the failure —
+ and note an operator can withhold channel creation from any platform, so a
+ false answer is not Telegram-specific.
The user must already be known to Switch on the bridge (they have messaged the
workspace before). If not, creation fails loudly with `no user '<name>' is
@@ -641,6 +660,16 @@ Your messages render on whatever platform the room is bridged to
the bold identifier and separate fields with `·` or `—`.
- **Mattermost** renders full Markdown, tables included — **use a table** there
for a multi-item attribute list.
+- **Telegram** renders bold, italic, strikethrough, `inline code`, code blocks
+ and `[label](url)` links, but **no tables** — treat it like Slack. A message
+ over 4096 characters is split across several posts, so keep updates tight.
+ Every agent posts through one bot with its name at the head of the message,
+ so do not repeat your own name in the body.
+ - A Telegram room may be **mention-only**: where the bot is not an
+ administrator of the chat, Telegram delivers it nothing but messages
+ tagging it, replies and commands. Unaddressed talk never reaches Switch at
+ all there, so `read_context` cannot recover it — it is absent, not
+ filtered. The bridge says so in the chat when it applies.
When unsure, prefer the Slack-safe shape — it reads fine everywhere.
diff --git a/connectors/opencode-plugin/skills/switch/SKILL.md b/connectors/opencode-plugin/skills/switch/SKILL.md
index 53eef6942..8a3dc7d12 100644
--- a/connectors/opencode-plugin/skills/switch/SKILL.md
+++ b/connectors/opencode-plugin/skills/switch/SKILL.md
@@ -222,15 +222,16 @@ local operator is explicitly steering you outside the room conversation.
`thread_id` appears there only when the message is already in a thread.
**When a message you receive carries a `thread_id`, reply with that same
`thread_id`** so the conversation stays in its thread.
-- Threads bridge to and from Mattermost natively. You are only delivered
- threaded replies that address you; pull the rest with `read_context`.
+- Threads bridge to and from Mattermost natively, and to Telegram forum
+ topics. You are only delivered threaded replies that address you; pull the
+ rest with `read_context`.
## Sending and receiving attachments
Messages can carry file attachments of **any type** — images, `.md`, `.csv`,
`.pdf`, logs, code — and a single message can carry **several**. Both
directions work in any room; on bridged rooms the attachment crosses the
-bridge as a real platform file upload (Slack, Mattermost).
+bridge as a real platform file upload (Slack, Mattermost, Discord, Telegram).
### Receiving
@@ -365,9 +366,14 @@ none of it is needed to take part in a conversation.
### Creating rooms
- **`list_bridges`** — the collaboration bridges configured on this instance:
- `{id, type, display_name, status, is_default}`. Only `status == "active"`
- bridges are usable. `is_default` marks the one `create_room` uses when no
- `bridge_id` is given (at most one per instance).
+ `{id, type, display_name, status, is_default, can_create_channels}`. Only
+ `status == "active"` bridges are usable. `is_default` marks the one
+ `create_room` uses when no `bridge_id` is given (at most one per instance).
+ `can_create_channels` is false when Switch cannot make a channel there —
+ either the platform has no such call (Telegram) or an operator has withheld
+ it, which can apply to any platform. Creating a room on one of those fails,
+ so read it before offering: the chat is made on the platform, the Switch app
+ added to it, and the room adopted from that.
- **`create_room`** — provision a room. Required: `name`, `description`,
`agent_names`. Commonly used: `bridge_id`, `internal_only`, `channel_type`
(`"channel_public"`, `"channel_private"`, `"direct"`), `user_names`,
@@ -378,8 +384,11 @@ none of it is needed to take part in a conversation.
- **`update_room`** — change an existing room, including its `aliases` map.
- **`invite_agent_to_room`** — add an existing agent to an existing room by
name. Humans and agents can do the same from inside a room with the
- `!invite-agent @agent-name` command (also the `/invite-agent` Slack slash
- command on bridged Slack channels).
+ `!invite-agent @agent-name` command (also the `/invite-agent` slash command
+ on bridged Slack, Discord and Telegram channels; Telegram registers it as
+ `/invite_agent`, since it will not accept a hyphen in a command). On Telegram
+ a command tapped from the `/` menu is sent immediately with no argument, so
+ the bot asks for the one it needs and runs when you reply with it.
- **`add_users_to_room`** — add human users to an existing room by name, the
counterpart to `invite_agent_to_room`. Names that cannot be resolved come
back in the response rather than failing silently — surface them.
@@ -426,7 +435,9 @@ agents to coordinate."
1. Call `list_bridges`.
2. Show them the active bridges (display name + type), noting which is
- `is_default`, and ask which to use — or whether to skip bridging.
+ `is_default`, and ask which to use — or whether to skip bridging. Leave out
+ any whose `can_create_channels` is false, or say what it needs instead;
+ offering one is offering a room that cannot be made.
3. Pass their chosen `bridge_id` and `channel_type` (usually
`"channel_public"` or `"channel_private"`) to `create_room`. Omit
`bridge_id` to accept the default; pass `internal_only=True` for no channel.
@@ -450,6 +461,14 @@ For a private 1:1 between one agent and one human, create a room with
- **Mattermost**: DMs are user-initiated from the client, so creating a
`direct` room here fails — the user starts the DM with the agent's bot and
Switch picks it up automatically.
+- **Telegram**: same as Mattermost — the user messages the bot first and
+ Switch adopts the chat. Telegram bots cannot create chats at all, so
+ `create_room` fails on a Telegram bridge for *every* channel type, not just
+ `direct`; the chat is made in a Telegram client and the bot added to it.
+ `list_bridges` reports this as `can_create_channels: false`, so check there
+ before offering to make a room rather than finding out from the failure —
+ and note an operator can withhold channel creation from any platform, so a
+ false answer is not Telegram-specific.
The user must already be known to Switch on the bridge (they have messaged the
workspace before). If not, creation fails loudly with `no user '<name>' is
@@ -650,6 +669,16 @@ Your messages render on whatever platform the room is bridged to
the bold identifier and separate fields with `·` or `—`.
- **Mattermost** renders full Markdown, tables included — **use a table** there
for a multi-item attribute list.
+- **Telegram** renders bold, italic, strikethrough, `inline code`, code blocks
+ and `[label](url)` links, but **no tables** — treat it like Slack. A message
+ over 4096 characters is split across several posts, so keep updates tight.
+ Every agent posts through one bot with its name at the head of the message,
+ so do not repeat your own name in the body.
+ - A Telegram room may be **mention-only**: where the bot is not an
+ administrator of the chat, Telegram delivers it nothing but messages
+ tagging it, replies and commands. Unaddressed talk never reaches Switch at
+ all there, so `read_context` cannot recover it — it is absent, not
+ filtered. The bridge says so in the chat when it applies.
When unsure, prefer the Slack-safe shape — it reads fine everywhere.
diff --git a/console/apps/switch-console-desktop/src/assets/images/bridges/telegram.svg b/console/apps/switch-console-desktop/src/assets/images/bridges/telegram.svg
new file mode 100644
index 000000000..480149bb5
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/assets/images/bridges/telegram.svg
@@ -0,0 +1,4 @@
+<svg width="127" height="127" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
+ <circle cx="12" cy="12" r="12" fill="#26A5E4"/>
+ <path fill="#fff" d="M16.906 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/console/apps/switch-console-desktop/src/main/core/app/service.ts b/console/apps/switch-console-desktop/src/main/core/app/service.ts
index 4da653b71..066b1f870 100644
--- a/console/apps/switch-console-desktop/src/main/core/app/service.ts
+++ b/console/apps/switch-console-desktop/src/main/core/app/service.ts
@@ -184,7 +184,8 @@ class AppService implements IInitializable, IDisposable {
}
// http/https plus the messaging-app schemes used by the sidebar "open in
// Slack/Mattermost" room deeplinks (links the gateway builds from a room's
- // bridge); other schemes (file:, javascript:, …) stay blocked.
+ // bridge); other schemes (file:, javascript:, …) stay blocked. Telegram
+ // needs no entry: its links are ordinary https `t.me` URLs.
if (!['http:', 'https:', 'slack:', 'mattermost:'].includes(parsedUrl.protocol)) {
throw new Error(
`Protocol "${parsedUrl.protocol}" is not allowed. Only http, https, ` +
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/bridge-home-url.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/bridge-home-url.test.ts
index 2a3748e8b..a5bf95a86 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/bridge-home-url.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/bridge-home-url.test.ts
@@ -17,6 +17,8 @@ function bridge(overrides: Partial<RemoteBridge>): RemoteBridge {
status: 'active',
isDefault: true,
homeUrl: null,
+ channelCreationSupported: true,
+ canCreateChannels: true,
...overrides,
};
}
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/bridge-home-url.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/bridge-home-url.ts
index 01a623e91..43336223e 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/bridge-home-url.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/bridge-home-url.ts
@@ -8,7 +8,7 @@ import type { RemoteBridge, SwitchServer } from '@shared/core/switch-servers/swi
* Switch Console can reach over one the server merely knows about.
*
* The gateway builds `home_url` from the bridge's connection config, which is
- * right for Slack, Discord and Teams — public platforms whose URLs are the
+ * right for Slack, Discord, Teams and Telegram — public platforms whose URLs are the
* same everywhere. It is *wrong* for a managed stack's bundled Mattermost: the
* configured `url` is the in-compose `http://mattermost:8065`, unreachable from
* the user's machine, and `public_url` is unset because the deployment does not
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
index f00b43222..9e0b09c45 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
@@ -46,6 +46,8 @@ import type {
ServerConnectionStatus,
SwitchAuthConfig,
SwitchServer,
+ UpdateBridgeParams,
+ UpdateBridgeResult,
UpdateServerParams,
UpdateServerResult,
} from '@shared/core/switch-servers/switch-servers';
@@ -87,6 +89,7 @@ import {
setActiveServerId,
updateServer,
} from './servers-store';
+import { updateBridgeOnServer } from './update-bridge';
async function requireServer(serverId: string): Promise<SwitchServer> {
const server = await getServer(serverId);
@@ -240,6 +243,20 @@ export const switchServersController = createRPCController({
displayName: params.displayName,
connectionConfig: params.connectionConfig,
setAsDefault: params.setAsDefault,
+ channelCreationEnabled: params.channelCreationEnabled,
+ });
+ },
+
+ /**
+ * Edit a bridge's operator-controlled switches — today, only whether the
+ * connection may create channels. Admin-only, like registering one; see
+ * `updateBridgeOnServer` for the recoverable-failure mapping.
+ */
+ updateBridge: async (params: UpdateBridgeParams): Promise<UpdateBridgeResult> => {
+ const server = await requireReachableServer(params.serverId);
+ return updateBridgeOnServer(server, {
+ bridgeId: params.bridgeId,
+ channelCreationEnabled: params.channelCreationEnabled,
});
},
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.ts
index 38a7d28c0..c617aa9b5 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.ts
@@ -34,6 +34,7 @@ const PARAMS = {
workspace_id: 'T123',
},
setAsDefault: false,
+ channelCreationEnabled: true,
};
/** A far-from-expiry JWT, so no renewal path is exercised here. */
@@ -88,6 +89,10 @@ describe('createBridgeOnServer', () => {
status: 'active',
isDefault: false,
homeUrl: null,
+ // Absent on CREATED, same as home_url — a server predating the
+ // capability behaves as if every bridge could create a channel.
+ channelCreationSupported: true,
+ canCreateChannels: true,
},
});
});
@@ -105,6 +110,36 @@ describe('createBridgeOnServer', () => {
display_name: 'Acme Slack',
connection_config: PARAMS.connectionConfig,
set_as_default: true,
+ channel_creation_enabled: true,
+ });
+ });
+
+ it('states the choice explicitly even when off, rather than omitting the field', async () => {
+ fetchMock.mockResolvedValue(response(200, CREATED));
+
+ await createBridgeOnServer(SERVER, { ...PARAMS, channelCreationEnabled: false });
+
+ const [, init] = fetchMock.mock.calls[0];
+ expect(JSON.parse(init.body)).toMatchObject({ channel_creation_enabled: false });
+ });
+
+ it("reports a platform's own refusal to create channels as invalid, not forbidden", async () => {
+ // Registering `channel_creation_enabled: true` for a platform whose
+ // adapter cannot create channels at all returns 400 with a message
+ // naming the platform — a rejected argument, not an admin-only failure.
+ fetchMock.mockResolvedValue(
+ response(400, {
+ detail:
+ 'telegram cannot create channels from Switch, so this connection cannot be allowed ' +
+ 'to. Create the chat on the platform and add the bot to it; Switch adopts it as a room.',
+ })
+ );
+
+ await expect(createBridgeOnServer(SERVER, PARAMS)).resolves.toEqual({
+ kind: 'invalid',
+ message:
+ 'telegram cannot create channels from Switch, so this connection cannot be allowed ' +
+ 'to. Create the chat on the platform and add the bot to it; Switch adopts it as a room.',
});
});
@@ -272,6 +307,20 @@ describe('fetchBridgeTypes', () => {
it('tolerates a type with no fields rather than throwing', async () => {
fetchMock.mockResolvedValue(response(200, [{ key: 'stub', config_schema: {} }]));
- await expect(fetchBridgeTypes(SERVER)).resolves.toEqual([{ key: 'stub', fields: [] }]);
+ // No `channel_creation_supported` in the fixture — a server predating the
+ // capability, which is the same "every platform could" default as the
+ // bridge list uses.
+ await expect(fetchBridgeTypes(SERVER)).resolves.toEqual([
+ { key: 'stub', fields: [], channelCreationSupported: true },
+ ]);
+ });
+
+ it('reports a platform that cannot create channels at all', async () => {
+ fetchMock.mockResolvedValue(
+ response(200, [{ key: 'telegram', config_schema: {}, channel_creation_supported: false }])
+ );
+
+ const [telegram] = await fetchBridgeTypes(SERVER);
+ expect(telegram.channelCreationSupported).toBe(false);
});
});
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.ts
index 25299dcb2..8b34fab8f 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.ts
@@ -26,6 +26,7 @@ export async function createBridgeOnServer(
displayName: params.displayName,
connectionConfig: params.connectionConfig,
setAsDefault: params.setAsDefault,
+ channelCreationEnabled: params.channelCreationEnabled,
});
return { kind: 'created', bridge };
} catch (cause) {
@@ -34,6 +35,9 @@ export async function createBridgeOnServer(
// Registering a bridge is admin-only. A non-admin cannot fix this by
// editing the form, so it is not a validation failure.
if (cause.kind === 'http' && cause.status === 403) return { kind: 'forbidden' };
+ // Also where a `true` for a platform that cannot create channels lands
+ // (400, naming the platform) — same "fix the form" shape as any other
+ // rejected argument, so it is not its own case.
if (cause.kind === 'http' && (cause.status === 400 || cause.status === 422)) {
return { kind: 'invalid', message: cause.detail ?? cause.message };
}
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.test.ts
index ff34efe95..305c70662 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.test.ts
@@ -107,6 +107,40 @@ describe('createRoomOnServer', () => {
});
});
+ it('reports a withheld channel-creation switch as invalid, not as a stopped bridge', async () => {
+ // Neither wording below contains "bridge", so `isBridgeFailure` must not
+ // match — the bridge itself is fine, the operator withheld the capability.
+ fetchMock.mockResolvedValue(
+ response(400, {
+ detail:
+ "Creating channels is turned off for the 'Mattermost' connection. Create the " +
+ 'channel on the platform and add the Switch app to it — Switch adopts it as a ' +
+ 'room — or ask an administrator to allow channel creation for this connection.',
+ })
+ );
+
+ await expect(createRoomOnServer(SERVER, PARAMS)).resolves.toEqual({
+ kind: 'invalid',
+ message:
+ "Creating channels is turned off for the 'Mattermost' connection. Create the " +
+ 'channel on the platform and add the Switch app to it — Switch adopts it as a ' +
+ 'room — or ask an administrator to allow channel creation for this connection.',
+ });
+ });
+
+ it('reports a platform that cannot create channels at all as invalid, not as a stopped bridge', async () => {
+ fetchMock.mockResolvedValue(
+ response(400, {
+ detail:
+ 'Telegram bots cannot create chats — the Bot API has no such call. Create the ' +
+ "group for 'design-review' in a Telegram client and add @switch_bot to it, and " +
+ 'Switch adopts it as a room as the bot lands.',
+ })
+ );
+
+ await expect(createRoomOnServer(SERVER, PARAMS)).resolves.toMatchObject({ kind: 'invalid' });
+ });
+
it('surfaces an unreachable gateway rather than failing silently', async () => {
fetchMock.mockRejectedValue(new Error('ECONNREFUSED'));
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.ts
index 6b89714f3..c1bc0b288 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.ts
@@ -7,7 +7,17 @@ import type {
/** The gateway reports an unknown bridge id and a configured-but-stopped bridge
* with the same 400, differing only in wording. Both mean "you cannot bridge to
- * that right now", which is the one failure the user can act on directly. */
+ * that right now", which is the one failure the user can act on directly.
+ *
+ * A room that cannot be created because the chosen bridge cannot make a
+ * channel (withheld by the operator, or the platform never supports it) is a
+ * different failure — the bridge itself is fine — so it falls through to
+ * `invalid` below rather than matching here. Both of those messages name the
+ * platform or connection, never the word "bridge", so this regex does not
+ * need to exclude them explicitly; `CreateRoomModal` already keeps
+ * channel-incapable bridges out of the picker, so a live user only hits this
+ * path in the race between loading the list and an operator's edit landing.
+ */
function isBridgeFailure(detail: string): boolean {
return /bridge/i.test(detail) && /not running|unavailable|not found/i.test(detail);
}
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts
index a25397057..cfa1c3c5f 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts
@@ -26,7 +26,8 @@ vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({
vi.mock('./servers-store', () => ({ getSessionCookie }));
vi.mock('./auth', () => ({ refreshSession, reauthenticateManagedServer }));
-const { createRoom, fetchBridges, fetchMe, registerKnownAgent } = await import('./gateway-client');
+const { createRoom, fetchBridges, fetchMe, registerKnownAgent, updateBridge } =
+ await import('./gateway-client');
const SERVER = {
id: 'srv-1',
@@ -322,6 +323,8 @@ describe('room creation', () => {
status: 'active',
is_default: true,
home_url: 'mattermost://chat.example.com/switch',
+ channel_creation_supported: true,
+ channel_creation_enabled: true,
},
{ bridge_id: 'b2', bridge_type: 'slack', display_name: 'Slack', status: 'stopped' },
]) as never
@@ -335,6 +338,8 @@ describe('room creation', () => {
status: 'active',
isDefault: true,
homeUrl: 'mattermost://chat.example.com/switch',
+ channelCreationSupported: true,
+ canCreateChannels: true,
},
{
id: 'b2',
@@ -343,10 +348,46 @@ describe('room creation', () => {
status: 'stopped',
isDefault: false,
homeUrl: null,
+ // Both fields post-date the pinned switch-core too, defaulting the
+ // same way home_url does: absent reads as the pre-capability world,
+ // where every bridge could create a channel.
+ channelCreationSupported: true,
+ canCreateChannels: true,
},
]);
});
+ it('reads the effective answer as the platform ceiling ANDed with the operator switch', async () => {
+ fetchMock.mockResolvedValue(
+ jsonResponse([
+ {
+ bridge_id: 'b1',
+ bridge_type: 'telegram',
+ display_name: 'Telegram',
+ status: 'active',
+ channel_creation_supported: false,
+ channel_creation_enabled: true,
+ },
+ {
+ bridge_id: 'b2',
+ bridge_type: 'slack',
+ display_name: 'Slack',
+ status: 'active',
+ channel_creation_supported: true,
+ channel_creation_enabled: false,
+ },
+ ]) as never
+ );
+
+ const [telegram, slack] = await fetchBridges(SERVER);
+
+ // Telegram: the platform ceiling is the binding constraint, regardless of
+ // what an operator's switch says.
+ expect(telegram).toMatchObject({ channelCreationSupported: false, canCreateChannels: false });
+ // Slack: the platform can, but the operator withheld it from this connection.
+ expect(slack).toMatchObject({ channelCreationSupported: true, canCreateChannels: false });
+ });
+
it('always names a bridge and a channel type, never the internal-only escape hatch', async () => {
fetchMock.mockResolvedValue(
jsonResponse({
@@ -466,3 +507,55 @@ describe('registerKnownAgent', () => {
});
});
});
+
+describe('updateBridge', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('fetch', fetchMock);
+ getSessionCookie.mockResolvedValue(makeJwt(24 * 60 * 60));
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('PATCHes only the field given, leaving an unset one out of the body', async () => {
+ fetchMock.mockResolvedValue(
+ jsonResponse({
+ bridge_id: 'b1',
+ bridge_type: 'slack',
+ display_name: 'Slack',
+ status: 'active',
+ channel_creation_supported: true,
+ channel_creation_enabled: false,
+ }) as never
+ );
+
+ const bridge = await updateBridge(SERVER, 'b1', { channelCreationEnabled: false });
+
+ const [url, init] = fetchMock.mock.calls[0] as unknown as [
+ string,
+ { method: string; body: string },
+ ];
+ expect(url).toBe('https://switch.example.com/gateway/collaborations/b1');
+ expect(init.method).toBe('PATCH');
+ expect(JSON.parse(init.body)).toEqual({ channel_creation_enabled: false });
+ expect(bridge).toMatchObject({ canCreateChannels: false, channelCreationSupported: true });
+ });
+
+ it('sends no field at all when nothing changed', async () => {
+ fetchMock.mockResolvedValue(
+ jsonResponse({
+ bridge_id: 'b1',
+ bridge_type: 'slack',
+ display_name: 'Slack',
+ status: 'active',
+ }) as never
+ );
+
+ await updateBridge(SERVER, 'b1', {});
+
+ const [, init] = fetchMock.mock.calls[0] as unknown as [string, { body: string }];
+ expect(JSON.parse(init.body)).toEqual({});
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
index 77e986019..7215693c1 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
@@ -527,6 +527,38 @@ export async function fetchRoomGroups(server: SwitchServer): Promise<RemoteRoomG
return json.map((g) => ({ id: g.id, name: g.name }));
}
+/** The gateway `BridgeDetail` wire shape, as returned by list, create, and
+ * update. One shape and one mapper for all three, so a field cannot reach one
+ * endpoint's response and miss another. */
+type BridgeJson = {
+ bridge_id: string;
+ bridge_type: string;
+ display_name: string;
+ status: string;
+ is_default?: boolean;
+ home_url?: string | null;
+ // Both absent on a server predating the capability — defaulting each to
+ // true reproduces how every bridge behaved before it existed: any platform
+ // could be asked to create a channel, and none had it withheld.
+ channel_creation_supported?: boolean;
+ channel_creation_enabled?: boolean;
+};
+
+function mapBridge(b: BridgeJson): RemoteBridge {
+ const channelCreationSupported = b.channel_creation_supported ?? true;
+ const channelCreationEnabled = b.channel_creation_enabled ?? true;
+ return {
+ id: b.bridge_id,
+ type: b.bridge_type,
+ displayName: b.display_name,
+ status: b.status,
+ isDefault: b.is_default ?? false,
+ homeUrl: b.home_url ?? null,
+ channelCreationSupported,
+ canCreateChannels: channelCreationSupported && channelCreationEnabled,
+ };
+}
+
/**
* List the collaboration bridges configured on a server (`GET /collaborations`).
* Returns every bridge regardless of status — callers that need a usable one
@@ -535,22 +567,8 @@ export async function fetchRoomGroups(server: SwitchServer): Promise<RemoteRoomG
*/
export async function fetchBridges(server: SwitchServer): Promise<RemoteBridge[]> {
const res = await gatewayFetch(server, '/collaborations', { authenticated: true });
- const json = (await res.json()) as Array<{
- bridge_id: string;
- bridge_type: string;
- display_name: string;
- status: string;
- is_default?: boolean;
- home_url?: string | null;
- }>;
- return json.map((b) => ({
- id: b.bridge_id,
- type: b.bridge_type,
- displayName: b.display_name,
- status: b.status,
- isDefault: b.is_default ?? false,
- homeUrl: b.home_url ?? null,
- }));
+ const json = (await res.json()) as BridgeJson[];
+ return json.map(mapBridge);
}
/** Field names that hold a credential and must be masked on input. Mirrors the
@@ -601,8 +619,15 @@ export async function fetchBridgeTypes(server: SwitchServer): Promise<RemoteBrid
const json = (await res.json()) as Array<{
key: string;
config_schema: BridgeConfigSchema;
+ channel_creation_supported?: boolean;
}>;
- return json.map((t) => ({ key: t.key, fields: toConfigFields(t.config_schema ?? {}) }));
+ return json.map((t) => ({
+ key: t.key,
+ fields: toConfigFields(t.config_schema ?? {}),
+ // Absent on a server predating the capability — every platform could be
+ // registered to create channels before it existed, so default true.
+ channelCreationSupported: t.channel_creation_supported ?? true,
+ }));
}
/**
@@ -625,6 +650,7 @@ export async function createBridge(
displayName: string;
connectionConfig: Record<string, string>;
setAsDefault: boolean;
+ channelCreationEnabled: boolean;
}
): Promise<RemoteBridge> {
const res = await gatewayFetch(server, '/collaborations', {
@@ -635,24 +661,34 @@ export async function createBridge(
display_name: params.displayName,
connection_config: params.connectionConfig,
set_as_default: params.setAsDefault,
+ channel_creation_enabled: params.channelCreationEnabled,
},
});
- const b = (await res.json()) as {
- bridge_id: string;
- bridge_type: string;
- display_name: string;
- status: string;
- is_default?: boolean;
- home_url?: string | null;
- };
- return {
- id: b.bridge_id,
- type: b.bridge_type,
- displayName: b.display_name,
- status: b.status,
- isDefault: b.is_default ?? false,
- homeUrl: b.home_url ?? null,
- };
+ return mapBridge((await res.json()) as BridgeJson);
+}
+
+/**
+ * Edit an existing bridge's operator-controlled switches
+ * (admin-only `PATCH /collaborations/{id}`). Only fields present in `params`
+ * are sent, so an unset one is left unchanged rather than reset — the gateway
+ * treats the request the same way.
+ *
+ * Posting `channelCreationEnabled: true` for a platform whose adapter cannot
+ * create channels at all returns 400 with a message naming the platform;
+ * callers map that like any other rejected edit rather than a bridge-specific
+ * case.
+ */
+export async function updateBridge(
+ server: SwitchServer,
+ bridgeId: string,
+ params: { channelCreationEnabled?: boolean }
+): Promise<RemoteBridge> {
+ const res = await gatewayFetch(server, `/collaborations/${encodeURIComponent(bridgeId)}`, {
+ authenticated: true,
+ method: 'PATCH',
+ body: { channel_creation_enabled: params.channelCreationEnabled },
+ });
+ return mapBridge((await res.json()) as BridgeJson);
}
/**
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.test.ts
new file mode 100644
index 000000000..8eaad67d0
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.test.ts
@@ -0,0 +1,151 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const getSessionCookie = vi.hoisted(() => vi.fn());
+const refreshSession = vi.hoisted(() => vi.fn());
+const reauthenticateManagedServer = vi.hoisted(() => vi.fn());
+
+const managedServerHostBlocked = vi.hoisted(() => vi.fn(() => null));
+const managedServerStoppedPhase = vi.hoisted(() => vi.fn(() => null));
+
+vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({
+ managedServerHostBlocked,
+ managedServerStoppedPhase,
+}));
+
+vi.mock('./servers-store', () => ({ getSessionCookie }));
+vi.mock('./auth', () => ({ refreshSession, reauthenticateManagedServer }));
+
+const { updateBridgeOnServer } = await import('./update-bridge');
+
+const SERVER = {
+ id: 'srv-1',
+ name: 'S',
+ gatewayUrl: 'https://switch.example.com',
+ managed: false,
+} as never;
+
+const PARAMS = {
+ bridgeId: 'bridge-1',
+ channelCreationEnabled: false,
+};
+
+/** A far-from-expiry JWT, so no renewal path is exercised here. */
+function validJwt(): string {
+ const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url');
+ const exp = Math.floor(Date.now() / 1000) + 24 * 60 * 60;
+ const payload = Buffer.from(JSON.stringify({ sub: 'u1', exp })).toString('base64url');
+ return `${header}.${payload}.sig`;
+}
+
+function response(status: number, body: unknown): Response {
+ const text = typeof body === 'string' ? body : JSON.stringify(body);
+ return {
+ status,
+ ok: status >= 200 && status < 300,
+ json: async () => (typeof body === 'string' ? {} : body),
+ headers: { getSetCookie: () => [] },
+ text: async () => text,
+ } as unknown as Response;
+}
+
+const UPDATED = {
+ bridge_id: 'bridge-1',
+ bridge_type: 'slack',
+ display_name: 'Acme Slack',
+ status: 'active',
+ is_default: false,
+ channel_creation_supported: true,
+ channel_creation_enabled: false,
+};
+
+const fetchMock = vi.fn();
+
+describe('updateBridgeOnServer', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('fetch', fetchMock);
+ getSessionCookie.mockResolvedValue(validJwt());
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('returns the updated bridge on success', async () => {
+ fetchMock.mockResolvedValue(response(200, UPDATED));
+
+ await expect(updateBridgeOnServer(SERVER, PARAMS)).resolves.toEqual({
+ kind: 'updated',
+ bridge: {
+ id: 'bridge-1',
+ type: 'slack',
+ displayName: 'Acme Slack',
+ status: 'active',
+ isDefault: false,
+ homeUrl: null,
+ channelCreationSupported: true,
+ canCreateChannels: false,
+ },
+ });
+ });
+
+ it('PATCHes the bridge by id with only the changed field', async () => {
+ fetchMock.mockResolvedValue(response(200, UPDATED));
+
+ await updateBridgeOnServer(SERVER, PARAMS);
+
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe('https://switch.example.com/gateway/collaborations/bridge-1');
+ expect(init.method).toBe('PATCH');
+ expect(JSON.parse(init.body)).toEqual({ channel_creation_enabled: false });
+ });
+
+ it('maps a rejected session onto unauthenticated so the caller prompts a sign-in', async () => {
+ fetchMock.mockResolvedValue(response(401, 'Token expired'));
+
+ await expect(updateBridgeOnServer(SERVER, PARAMS)).resolves.toEqual({
+ kind: 'unauthenticated',
+ });
+ });
+
+ it('reports a non-admin as forbidden, not as a bad form entry', async () => {
+ // Editing a bridge is admin-only, same as registering one.
+ fetchMock.mockResolvedValue(response(403, { detail: 'Admin access required' }));
+
+ await expect(updateBridgeOnServer(SERVER, PARAMS)).resolves.toEqual({ kind: 'forbidden' });
+ });
+
+ it("reports a platform's own refusal to create channels as invalid, not forbidden", async () => {
+ // Turning channel creation on for a connection whose platform cannot do
+ // it at all returns 400 with a message naming the platform — a rejected
+ // argument, not an admin-only failure.
+ fetchMock.mockResolvedValue(
+ response(400, {
+ detail:
+ 'telegram cannot create channels from Switch, so this connection cannot be allowed ' +
+ 'to. Create the chat on the platform and add the bot to it; Switch adopts it as a room.',
+ })
+ );
+
+ await expect(
+ updateBridgeOnServer(SERVER, { ...PARAMS, channelCreationEnabled: true })
+ ).resolves.toEqual({
+ kind: 'invalid',
+ message:
+ 'telegram cannot create channels from Switch, so this connection cannot be allowed ' +
+ 'to. Create the chat on the platform and add the bot to it; Switch adopts it as a room.',
+ });
+ });
+
+ it('surfaces an unreachable gateway rather than failing silently', async () => {
+ fetchMock.mockRejectedValue(new Error('ECONNREFUSED'));
+
+ await expect(updateBridgeOnServer(SERVER, PARAMS)).resolves.toMatchObject({ kind: 'error' });
+ });
+
+ it('rethrows a server fault rather than flattening it into a form error', async () => {
+ fetchMock.mockResolvedValue(response(500, 'Internal Server Error'));
+
+ await expect(updateBridgeOnServer(SERVER, PARAMS)).rejects.toMatchObject({ status: 500 });
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.ts
new file mode 100644
index 000000000..9b3e03d35
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.ts
@@ -0,0 +1,39 @@
+import { GatewayError, updateBridge } from '@main/core/switch-servers/gateway-client';
+import type {
+ SwitchServer,
+ UpdateBridgeParams,
+ UpdateBridgeResult,
+} from '@shared/core/switch-servers/switch-servers';
+
+/**
+ * Edit a bridge's operator-controlled switches on `server` and map recoverable
+ * gateway failures onto a typed {@link UpdateBridgeResult}, mirroring
+ * `createBridgeOnServer` — editing is admin-only for the same reason
+ * registering is, so the same recoverable cases apply.
+ *
+ * Unmapped failures still throw: an unexpected 500 is a bug, not a form error.
+ */
+export async function updateBridgeOnServer(
+ server: SwitchServer,
+ params: Omit<UpdateBridgeParams, 'serverId'>
+): Promise<UpdateBridgeResult> {
+ try {
+ const bridge = await updateBridge(server, params.bridgeId, {
+ channelCreationEnabled: params.channelCreationEnabled,
+ });
+ return { kind: 'updated', bridge };
+ } catch (cause) {
+ if (cause instanceof GatewayError) {
+ if (cause.kind === 'unauthorized') return { kind: 'unauthenticated' };
+ if (cause.kind === 'http' && cause.status === 403) return { kind: 'forbidden' };
+ // Also where turning channel creation on for a platform that cannot do
+ // it lands (400, naming the platform) — a rejected argument, not its
+ // own case.
+ if (cause.kind === 'http' && (cause.status === 400 || cause.status === 422)) {
+ return { kind: 'invalid', message: cause.detail ?? cause.message };
+ }
+ if (cause.kind === 'network') return { kind: 'error', message: cause.message };
+ }
+ throw cause;
+ }
+}
diff --git a/console/apps/switch-console-desktop/src/main/lib/file-logger.test.ts b/console/apps/switch-console-desktop/src/main/lib/file-logger.test.ts
index af2d78f0e..f6fe23034 100644
--- a/console/apps/switch-console-desktop/src/main/lib/file-logger.test.ts
+++ b/console/apps/switch-console-desktop/src/main/lib/file-logger.test.ts
@@ -26,6 +26,14 @@ vi.mock('electron', () => ({
const DISCORD_TOKEN_TAIL = 'abcdefghijklmnopqrstuvwxyz1';
const DISCORD_TOKEN_SHAPE = ['MTA5NjE4NzQ5NDI4Nzk0MjA5', 'GhIjKl', DISCORD_TOKEN_TAIL].join('.');
+/**
+ * A Telegram-bot-token-shaped fixture, assembled at runtime for the same reason
+ * as the Discord one: `<bot id>:<hmac>` is matched on sight by push protection
+ * and by gitleaks' own telegram-bot-api-token rule.
+ */
+const TELEGRAM_TOKEN_TAIL = 'AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw';
+const TELEGRAM_TOKEN_SHAPE = ['110201543', TELEGRAM_TOKEN_TAIL].join(':');
+
describe('redactDiagnosticLog', () => {
it('redacts common secrets in free-form text', () => {
const redacted = redactDiagnosticLog(
@@ -125,6 +133,18 @@ describe('redactDiagnosticLog', () => {
expect(redacted).toContain('[REDACTED_DISCORD_TOKEN]');
});
+ it('redacts a bare Telegram bot token', () => {
+ // Structural, like Discord's: a Telegram token carries no vendor prefix, so
+ // it has to be caught on shape alone or it reaches the log whenever it is
+ // not sitting behind a `bot_token=` key.
+ const redacted = redactDiagnosticLog(
+ `polling failed for ${TELEGRAM_TOKEN_SHAPE} after 3 attempts`
+ );
+
+ expect(redacted).toContain('[REDACTED_TELEGRAM_TOKEN]');
+ expect(redacted).not.toContain(TELEGRAM_TOKEN_TAIL);
+ });
+
it('redacts the token after a Bot auth scheme, not just Bearer', () => {
// `Authorization: Bot <token>` is Discord's canonical header. Redacting the
// scheme word and leaving the token behind is worse than useless.
diff --git a/console/apps/switch-console-desktop/src/main/lib/file-logger.ts b/console/apps/switch-console-desktop/src/main/lib/file-logger.ts
index 2eda1f004..2b535b140 100644
--- a/console/apps/switch-console-desktop/src/main/lib/file-logger.ts
+++ b/console/apps/switch-console-desktop/src/main/lib/file-logger.ts
@@ -74,6 +74,9 @@ const SECRET_PATTERNS: Array<[RegExp, RedactionReplacement]> = [
// so it is matched structurally. Kept after the JWT rule, whose middle
// segment is far longer than six characters, so the two cannot collide.
[/\b[A-Za-z0-9_-]{23,28}\.[A-Za-z0-9_-]{6}\.[A-Za-z0-9_-]{27,}\b/g, '[REDACTED_DISCORD_TOKEN]'],
+ // Telegram bot token: numeric bot id : 35-char hmac. Also unprefixed, so it
+ // is matched structurally. The colon keeps it clear of the Discord rule.
+ [/\b\d{6,12}:[A-Za-z0-9_-]{30,}\b/g, '[REDACTED_TELEGRAM_TOKEN]'],
];
const PII_PATTERNS: Array<[RegExp, RedactionReplacement]> = [
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-auto-scroll.test.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-auto-scroll.test.ts
index 4de54c3b0..0b6cfbfee 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-auto-scroll.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-auto-scroll.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, it, vi } from 'vitest';
-import { scrollDeltaFor } from './sidebar-auto-scroll';
+import {
+ attemptRevealSelection,
+ scrollDeltaFor,
+ type RevealAttemptIO,
+} from './sidebar-auto-scroll';
// The hook this module also exports reaches the app's singletons; the scroll
// rule under test does not.
@@ -36,3 +40,70 @@ describe('scrollDeltaFor', () => {
expect(scrollDeltaFor(viewport, { top: 50, bottom: 600 }, MARGIN)).toBe(-58);
});
});
+
+function io(overrides: Partial<RevealAttemptIO> = {}): RevealAttemptIO {
+ return {
+ reveal: vi.fn(),
+ dragging: () => false,
+ findRow: () => ({ top: 200, bottom: 232 }),
+ scroller: () => viewport,
+ scrollBy: vi.fn(),
+ ...overrides,
+ };
+}
+
+describe('attemptRevealSelection', () => {
+ it('settles once the row is rendered', () => {
+ const deps = io();
+
+ expect(attemptRevealSelection(deps)).toBe(true);
+ expect(deps.reveal).toHaveBeenCalledOnce();
+ });
+
+ it('scrolls a row that is out of view', () => {
+ const deps = io({ findRow: () => ({ top: 500, bottom: 532 }) });
+
+ attemptRevealSelection(deps);
+
+ expect(deps.scrollBy).toHaveBeenCalledWith(140);
+ });
+
+ it('leaves the viewport alone when the row is already visible', () => {
+ const deps = io();
+
+ attemptRevealSelection(deps);
+
+ expect(deps.scrollBy).not.toHaveBeenCalled();
+ });
+
+ it('reveals again on a later attempt rather than only the first', () => {
+ // The room a session belongs to can still be loading when the selection
+ // changes — a deeplink scopes to another server and navigates at once — so
+ // the first reveal knows of no room and opens nothing. Retrying the reveal
+ // alongside the scroll is what eventually opens the group; revealing once
+ // up front left the row hidden for good (CHOO-1686).
+ const deps = io({ findRow: () => null });
+
+ expect(attemptRevealSelection(deps)).toBe(false);
+ expect(attemptRevealSelection(deps)).toBe(false);
+
+ expect(deps.reveal).toHaveBeenCalledTimes(2);
+ });
+
+ it('still reveals when the row has not rendered yet', () => {
+ // Revealing is what makes it render, so it cannot be conditional on it.
+ const deps = io({ findRow: () => null });
+
+ attemptRevealSelection(deps);
+
+ expect(deps.reveal).toHaveBeenCalledOnce();
+ expect(deps.scrollBy).not.toHaveBeenCalled();
+ });
+
+ it('does not move the viewport out from under a drag', () => {
+ const deps = io({ dragging: () => true, findRow: () => ({ top: 500, bottom: 532 }) });
+
+ expect(attemptRevealSelection(deps)).toBe(false);
+ expect(deps.scrollBy).not.toHaveBeenCalled();
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-auto-scroll.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-auto-scroll.ts
index d0b2e041e..1b1a3c98f 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-auto-scroll.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-auto-scroll.ts
@@ -52,6 +52,43 @@ function activeRowIn(scroller: HTMLElement): HTMLElement | null {
return rows[0] ?? null;
}
+/** The effects one reveal attempt needs, injected so the rule below can be
+ * exercised without a DOM or a layout. */
+export interface RevealAttemptIO {
+ /** Re-derive the selection and open whatever is hiding it. */
+ reveal: () => void;
+ /** Whether a row is mid-drag, in which case the viewport is left alone. */
+ dragging: () => boolean;
+ /** The active row's edges, or null when it is not rendered yet. */
+ findRow: () => Edges | null;
+ /** The scroll container's edges. */
+ scroller: () => Edges;
+ scrollBy: (delta: number) => void;
+}
+
+/**
+ * One attempt at showing the selected row: open whatever hides it, then bring
+ * it into view. True once the row exists and has been settled.
+ *
+ * Revealing is repeated on every attempt rather than done once up front. The
+ * room a session belongs to may still be loading when the selection changes —
+ * a deeplink scopes to another server and navigates in the same breath — and a
+ * reveal computed before that arrives knows of no room to open, so it opens
+ * nothing and the row stays hidden for good. Reveals are idempotent, so
+ * repeating one costs nothing once it has taken effect.
+ */
+export function attemptRevealSelection(io: RevealAttemptIO): boolean {
+ io.reveal();
+ if (io.dragging()) return false;
+ const row = io.findRow();
+ if (!row) return false;
+ const delta = scrollDeltaFor(io.scroller(), row);
+ // Instant, never smooth: a glide under a held pointer travels far enough to
+ // cross the drag activation distance and turn a click into a drag.
+ if (delta !== 0) io.scrollBy(delta);
+ return true;
+}
+
export function useScrollSelectionIntoView(scrollerRef: RefObject<HTMLElement | null>): void {
// Read in render so the sidebar re-renders — and this effect re-runs — the
// moment the selection changes, wherever it was changed from.
@@ -62,19 +99,21 @@ export function useScrollSelectionIntoView(scrollerRef: RefObject<HTMLElement |
const scroller = scrollerRef.current;
if (!scroller || settledKey.current === selectionKey) return;
- const selection = currentSidebarSelection();
- if (selection) sidebarStore.revealSelection(selection);
-
const bringIntoView = (): boolean => {
- if (isSidebarRowDragging()) return false;
- const row = activeRowIn(scroller);
- if (!row) return false;
- settledKey.current = selectionKey;
- const delta = scrollDeltaFor(scroller.getBoundingClientRect(), row.getBoundingClientRect());
- // Instant, never smooth: a glide under a held pointer travels far enough
- // to cross the drag activation distance and turn a click into a drag.
- if (delta !== 0) scroller.scrollTop += delta;
- return true;
+ const settled = attemptRevealSelection({
+ reveal: () => {
+ const selection = currentSidebarSelection();
+ if (selection) sidebarStore.revealSelection(selection);
+ },
+ dragging: isSidebarRowDragging,
+ findRow: () => activeRowIn(scroller)?.getBoundingClientRect() ?? null,
+ scroller: () => scroller.getBoundingClientRect(),
+ scrollBy: (delta) => {
+ scroller.scrollTop += delta;
+ },
+ });
+ if (settled) settledKey.current = selectionKey;
+ return settled;
};
if (bringIntoView()) return;
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/view.tsx
index 8d49a4817..9eefc603a 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/view.tsx
@@ -3,6 +3,7 @@ import { observer } from 'mobx-react-lite';
import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
+import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
import { Titlebar } from '@renderer/lib/components/titlebar/Titlebar';
import { useParams } from '@renderer/lib/layout/navigation-provider';
import { Button } from '@renderer/lib/ui/button';
@@ -22,7 +23,7 @@ const OpenInMessagingApp = observer(function OpenInMessagingApp({ roomId }: { ro
const bridgeType = switchRoomsStore.roomBridgeTypeById(roomId);
if (!switchRoomsStore.roomChannelUrl(roomId)) return null;
- const platform = bridgeType ?? 'messaging app';
+ const platform = bridgePlatformLabel(bridgeType);
return (
<Tooltip>
<TooltipTrigger
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx
index 491c62fc0..068b89f5d 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx
@@ -25,6 +25,7 @@ import {
SelectTrigger,
SelectValue,
} from '@renderer/lib/ui/select';
+import { cn } from '@renderer/utils/utils';
import type { CreateBridgeResult } from '@shared/core/switch-servers/switch-servers';
import { switchServersStore } from './switch-servers-store';
@@ -52,6 +53,9 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod
// the modal, and the only thing that reads it is the submit call.
const [config, setConfig] = useState<Record<string, string>>({});
const [setAsDefault, setSetAsDefault] = useState(false);
+ // Defaults on: most platforms can create channels, and the server rejects
+ // this staying true for one that can't rather than us guessing wrong.
+ const [channelCreationEnabled, setChannelCreationEnabled] = useState(true);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -63,6 +67,9 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod
const types = useMemo(() => typesQuery.data ?? [], [typesQuery.data]);
const selectedType = types.find((t) => t.key === typeKey) ?? null;
+ // Unknown until the type list has loaded; assume supported so the checkbox
+ // isn't forced off while that request is in flight.
+ const channelCreationSupported = selectedType?.channelCreationSupported ?? true;
const handleTypeChange = useCallback((next: string | null) => {
// Switching platform drops whatever was typed for the previous one — those
@@ -70,6 +77,7 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod
// would silently submit a credential the user thinks they replaced.
setTypeKey(next);
setConfig({});
+ setChannelCreationEnabled(true);
setError(null);
}, []);
@@ -101,6 +109,10 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod
displayName: trimmedName,
connectionConfig,
setAsDefault,
+ // Forced off for a platform that can't create channels regardless of
+ // the checkbox state — the server rejects `true` there anyway, but
+ // sending what the form actually shows is the honest request.
+ channelCreationEnabled: channelCreationSupported && channelCreationEnabled,
});
if (result.kind !== 'created') {
@@ -121,6 +133,8 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod
trimmedName,
config,
setAsDefault,
+ channelCreationSupported,
+ channelCreationEnabled,
onSuccess,
setCloseGuard,
]);
@@ -237,6 +251,28 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod
</Field>
))}
+ <label
+ className={cn(
+ 'group/field flex items-start gap-2.5',
+ channelCreationSupported ? 'cursor-pointer' : 'cursor-not-allowed'
+ )}
+ >
+ <Checkbox
+ checked={channelCreationSupported && channelCreationEnabled}
+ disabled={!channelCreationSupported}
+ onCheckedChange={(checked) => setChannelCreationEnabled(checked === true)}
+ className="mt-0.5"
+ />
+ <span className="flex flex-col gap-0.5">
+ <span className="text-sm font-medium">Allow creating channels from Switch</span>
+ <span className="text-xs text-foreground-muted">
+ {channelCreationSupported
+ ? 'Lets a new room create its channel here directly. Turn off to only ever adopt channels made in the app.'
+ : `${bridgePlatformLabel(selectedType.key)} has no way to create channels from Switch, so this connection can only be used with channels made in the app.`}
+ </span>
+ </span>
+ </label>
+
<label className="group/field flex cursor-pointer items-start gap-2.5">
<Checkbox
checked={setAsDefault}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx
index 83de0c03e..d781f7175 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx
@@ -78,16 +78,26 @@ export const CreateRoomModal = observer(function CreateRoomModal({
enabled: !!serverId,
});
- // Only a running bridge can back a new room. Keeping the inactive ones out of
- // the picker (rather than letting the create call fail) means the one thing
- // shown is the one thing that works — and "no bridges" is stated outright.
- const bridges = (bridgesQuery.data ?? []).filter((b) => b.status === 'active');
+ // Only a running bridge can back a new room, and creating a room here means
+ // creating a channel on it — a bridge withheld from that (an operator's
+ // switch, or a platform like Telegram that has no such call at all) is just
+ // as unusable for this form. Keeping both kinds out of the picker (rather
+ // than letting the create call fail) means the one thing shown is the one
+ // thing that works — and each reason for an empty list is stated outright,
+ // rather than collapsed into one generic "no bridges".
+ const allBridges = bridgesQuery.data ?? [];
+ const activeBridges = allBridges.filter((b) => b.status === 'active');
+ const bridges = activeBridges.filter((b) => b.canCreateChannels);
const selectedBridge =
bridges.find((b) => b.id === bridgeId) ??
bridges.find((b) => b.isDefault) ??
bridges[0] ??
null;
- const noBridges = !bridgesQuery.isLoading && bridges.length === 0;
+ const loaded = !bridgesQuery.isLoading;
+ const noBridgesAtAll = loaded && allBridges.length === 0;
+ const noneRunning = loaded && allBridges.length > 0 && activeBridges.length === 0;
+ const noneCanCreateChannels = loaded && activeBridges.length > 0 && bridges.length === 0;
+ const noUsableBridge = noBridgesAtAll || noneRunning || noneCanCreateChannels;
const trimmedName = name.trim();
const trimmedDescription = description.trim();
@@ -198,7 +208,7 @@ export const CreateRoomModal = observer(function CreateRoomModal({
<Select
value={selectedBridge?.id ?? ''}
onValueChange={(next) => setBridgeId(next ?? null)}
- disabled={bridgesQuery.isLoading || noBridges}
+ disabled={bridgesQuery.isLoading || noUsableBridge}
>
<SelectTrigger>
{/* Resolve the label ourselves: the trigger shows the raw value
@@ -217,12 +227,26 @@ export const CreateRoomModal = observer(function CreateRoomModal({
))}
</SelectContent>
</Select>
- {noBridges && (
+ {noBridgesAtAll && (
<p className="text-destructive mt-1 text-xs">
This server has no messaging app connected, so a room created here would be
unreachable. Connect one first.
</p>
)}
+ {noneRunning && (
+ <p className="text-destructive mt-1 text-xs">
+ This server's messaging apps are not running, so a room created here would be
+ unreachable. Start one, or connect another.
+ </p>
+ )}
+ {noneCanCreateChannels && (
+ <p className="text-destructive mt-1 text-xs">
+ None of the running messaging apps can create a channel from Switch — for example, a
+ Telegram bot can't create chats on its own. Make the chat directly in the messaging
+ app instead (for Telegram, create the group and add the bot to it) and it becomes a
+ room here once it exists.
+ </p>
+ )}
{bridgesQuery.isError && (
<p className="text-destructive mt-1 text-xs">
Could not load messaging apps: {errorText(bridgesQuery.error)}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx
index 550a6c6a2..def606463 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx
@@ -1,6 +1,7 @@
import { useQueryClient, useQuery } from '@tanstack/react-query';
import { ExternalLink, MessageSquare, Plus } from 'lucide-react';
import { observer } from 'mobx-react-lite';
+import { useState } from 'react';
import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
import { rpc } from '@renderer/lib/ipc';
@@ -9,6 +10,9 @@ import { openExternalUrl } from '@renderer/lib/open-external';
import { Badge } from '@renderer/lib/ui/badge';
import { Button } from '@renderer/lib/ui/button';
import { Spinner } from '@renderer/lib/ui/spinner';
+import { Switch } from '@renderer/lib/ui/switch';
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@renderer/lib/ui/tooltip';
+import type { RemoteBridge } from '@shared/core/switch-servers/switch-servers';
import { BundledChatSignIn } from './BundledChatSignIn';
import { switchRoomsStore } from './switch-rooms-store';
import { switchServersStore } from './switch-servers-store';
@@ -44,6 +48,35 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
const bridges = bridgesQuery.data ?? [];
+ // Which bridge's channel-creation switch is mid-flight, so only that row
+ // disables rather than the whole list, and the surfaced error names the one
+ // connection that failed.
+ const [savingBridgeId, setSavingBridgeId] = useState<string | null>(null);
+ const [toggleError, setToggleError] = useState<string | null>(null);
+
+ const handleToggleChannelCreation = async (bridge: RemoteBridge, enabled: boolean) => {
+ setSavingBridgeId(bridge.id);
+ setToggleError(null);
+ try {
+ const result = await rpc.switchServers.updateBridge({
+ serverId,
+ bridgeId: bridge.id,
+ channelCreationEnabled: enabled,
+ });
+ if (result.kind !== 'updated') {
+ setToggleError(`Could not update ${bridge.displayName}: ${messageForUpdate(result)}`);
+ return;
+ }
+ await queryClient.invalidateQueries({ queryKey: ['remote-bridges', serverId] });
+ } catch (cause) {
+ setToggleError(
+ `Could not update ${bridge.displayName}: ${cause instanceof Error ? cause.message : String(cause)}`
+ );
+ } finally {
+ setSavingBridgeId(null);
+ }
+ };
+
return (
<div className={className}>
<div className="flex items-center justify-between gap-3">
@@ -123,6 +156,33 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
cannot back a new room, and the room-creation picker silently
omits it, so this is where that becomes visible. */}
{bridge.status !== 'active' && <Badge variant="destructive">{bridge.status}</Badge>}
+ <TooltipProvider delay={150}>
+ <Tooltip>
+ <TooltipTrigger>
+ <span className="flex shrink-0 items-center gap-1.5 text-xs text-foreground-muted">
+ Channels
+ <Switch
+ size="sm"
+ checked={bridge.canCreateChannels}
+ disabled={
+ !isAdmin ||
+ !bridge.channelCreationSupported ||
+ savingBridgeId === bridge.id
+ }
+ onCheckedChange={(next) => void handleToggleChannelCreation(bridge, next)}
+ aria-label={`${bridge.canCreateChannels ? 'Disallow' : 'Allow'} ${bridgePlatformLabel(bridge.type)} creating channels from Switch`}
+ />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="top" className="max-w-56 text-xs">
+ {!bridge.channelCreationSupported
+ ? `${bridgePlatformLabel(bridge.type)} cannot create channels from Switch — create the chat in the app and add the bot to it instead.`
+ : bridge.canCreateChannels
+ ? 'Can create a channel here for a new room. Turn off to only ever adopt channels made in the app.'
+ : 'Channel creation is turned off for this connection — a new room can only adopt a channel made in the app.'}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
</div>
{isManaged && bridge.type === 'mattermost' && (
<BundledChatSignIn serverId={serverId} />
@@ -131,6 +191,19 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
))}
</ul>
)}
+ {toggleError && <p className="text-destructive mt-2 text-xs">{toggleError}</p>}
</div>
);
});
+
+/** Turn a failed channel-creation toggle into something the user can act on. */
+function messageForUpdate(result: { kind: string; message?: string }): string {
+ switch (result.kind) {
+ case 'unauthenticated':
+ return 'Your session for this server expired. Sign in again, then retry.';
+ case 'forbidden':
+ return 'This requires an admin account on this server.';
+ default:
+ return result.message ?? 'The server rejected the change.';
+ }
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-platform.test.ts b/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-platform.test.ts
index 47e9f2579..9459a0827 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-platform.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-platform.test.ts
@@ -2,10 +2,11 @@ import { existsSync, readdirSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
+import { hasBridgeIcon } from './bridge-icon';
import { bridgePlatformLabel, bridgeSetupDocsUrl } from './bridge-platform';
/** Every bridge type switch-core registers today (`main.py` register_adapter). */
-const BRIDGE_TYPES = ['slack', 'mattermost', 'discord', 'teams'];
+const BRIDGE_TYPES = ['slack', 'mattermost', 'discord', 'teams', 'telegram'];
const BRIDGE_ICON_DIR = join(
dirname(fileURLToPath(import.meta.url)),
@@ -21,6 +22,7 @@ describe('bridgePlatformLabel', () => {
expect(bridgePlatformLabel('mattermost')).toBe('Mattermost');
expect(bridgePlatformLabel('discord')).toBe('Discord');
expect(bridgePlatformLabel('teams')).toBe('Microsoft Teams');
+ expect(bridgePlatformLabel('telegram')).toBe('Telegram');
});
it('falls back to the raw key for a type this build does not know', () => {
@@ -65,6 +67,21 @@ describe('bridge brand icons', () => {
expect(existsSync(join(BRIDGE_ICON_DIR, `${type}.svg`))).toBe(true);
});
+ it.each(BRIDGE_TYPES)('the icon loader actually resolves %s', (type) => {
+ // `existsSync` above only proves the file is on disk. The app reads these
+ // through a Vite glob keyed on filename, so an icon in the wrong directory,
+ // or one the raw loader hands back in an unexpected shape, would pass the
+ // check above and still leave the button hidden at runtime — which is the
+ // failure this pair is here to prevent.
+ expect(hasBridgeIcon(type)).toBe(true);
+ });
+
+ it('reports no icon for a type this build does not bundle', () => {
+ expect(hasBridgeIcon('zulip')).toBe(false);
+ expect(hasBridgeIcon(null)).toBe(false);
+ expect(hasBridgeIcon(undefined)).toBe(false);
+ });
+
it('has a label for every bundled icon', () => {
// The reverse direction: an icon with no label would render next to a raw
// slug in the picker.
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-platform.ts b/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-platform.ts
index 0e3008ad9..b95d3aa1a 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-platform.ts
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-platform.ts
@@ -11,6 +11,7 @@ const PLATFORM_LABELS: Record<string, string> = {
mattermost: 'Mattermost',
discord: 'Discord',
teams: 'Microsoft Teams',
+ telegram: 'Telegram',
};
/**
@@ -39,6 +40,7 @@ const PLATFORM_DOCS: Record<string, string> = {
mattermost: `${DOCS_BASE}/MATTERMOST_SETUP.md`,
discord: `${DOCS_BASE}/DISCORD_SETUP.md`,
teams: `${DOCS_BASE}/TEAMS_SETUP.md`,
+ telegram: `${DOCS_BASE}/TELEGRAM_SETUP.md`,
};
/**
diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-rooms/channel-links.ts b/console/apps/switch-console-desktop/src/shared/core/switch-rooms/channel-links.ts
index 886f7ea2b..f3413f458 100644
--- a/console/apps/switch-console-desktop/src/shared/core/switch-rooms/channel-links.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/switch-rooms/channel-links.ts
@@ -1,9 +1,10 @@
/**
* Translating a bridge's channel link into one that opens anywhere.
*
- * Each bridge hands out whichever link its platform prefers. Discord and Teams
- * use ordinary https URLs, which their desktop clients register for — the app
- * catches them when installed, the browser serves them when not. Mattermost and
+ * Each bridge hands out whichever link its platform prefers. Discord, Teams and
+ * Telegram use ordinary https URLs, which their desktop clients register for —
+ * the app catches them when installed, the browser serves them when not.
+ * Mattermost and
* Slack instead use a private scheme that only their desktop app answers, so on
* a machine without that app the click reaches nobody and nothing happens.
*
diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
index a57468a71..384f2eef2 100644
--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
@@ -250,6 +250,22 @@ export type RemoteBridge = {
* absence as "no action to offer", not as an error.
*/
homeUrl: string | null;
+ /**
+ * Whether the platform this connection runs on can create a channel at all
+ * (e.g. false for Telegram — the Bot API has no such call). Fixed per
+ * platform; not something an operator can change. Defaults to true for a
+ * server predating the field, matching how every bridge behaved before the
+ * capability existed.
+ */
+ channelCreationSupported: boolean;
+ /**
+ * Whether this connection may actually be used to create a channel —
+ * `channelCreationSupported` ANDed with the operator's own switch for this
+ * connection. This is the one callers creating a room should read;
+ * `channelCreationSupported` exists only to explain *why* when this is
+ * false (a platform ceiling vs. an operator's choice).
+ */
+ canCreateChannels: boolean;
};
/**
@@ -298,6 +314,10 @@ export type RemoteBridgeType = {
/** Platform key (`slack`, `mattermost`, …). */
key: string;
fields: BridgeConfigField[];
+ /** Whether this platform can create channels at all — read from the
+ * adapter class, so it is answerable before any connection of this type
+ * exists, which is exactly when the attach form needs it. */
+ channelCreationSupported: boolean;
};
/**
@@ -316,6 +336,11 @@ export type CreateBridgeParams = {
connectionConfig: Record<string, string>;
/** Make this the bridge new rooms land on when none is named. */
setAsDefault: boolean;
+ /** Whether this connection may create channels on the platform. The
+ * gateway defaults this to true when omitted, but Switch Console always
+ * states it explicitly, forced off for a platform that cannot create
+ * channels at all — registering `true` there returns 400. */
+ channelCreationEnabled: boolean;
};
/**
@@ -334,6 +359,28 @@ export type CreateBridgeResult =
| { kind: 'invalid'; message: string }
| { kind: 'error'; message: string };
+/**
+ * Parameters for editing an existing bridge's operator-controlled switches
+ * (`PATCH /collaborations/{id}`). Only `channelCreationEnabled` is wired up
+ * today; leave a field unset to leave it unchanged, matching the gateway's
+ * own partial-update contract.
+ */
+export type UpdateBridgeParams = {
+ serverId: string;
+ bridgeId: string;
+ channelCreationEnabled?: boolean;
+};
+
+/** Outcome of editing a bridge. Mirrors {@link CreateBridgeResult}'s recoverable
+ * cases: editing is admin-only like registering, so a non-admin gets the same
+ * `forbidden` rather than a validation error. */
+export type UpdateBridgeResult =
+ | { kind: 'updated'; bridge: RemoteBridge }
+ | { kind: 'unauthenticated' }
+ | { kind: 'forbidden' }
+ | { kind: 'invalid'; message: string }
+ | { kind: 'error'; message: string };
+
/** A bridged (external) human identity on a server. The `users` dimension of an
* addressing policy keys off these ids. */
export type RemoteExternalUser = {
diff --git a/console/packages/plugins/src/agents/impl/opencode/skill-file.ts b/console/packages/plugins/src/agents/impl/opencode/skill-file.ts
index 4725434fe..bff923aea 100644
--- a/console/packages/plugins/src/agents/impl/opencode/skill-file.ts
+++ b/console/packages/plugins/src/agents/impl/opencode/skill-file.ts
@@ -230,15 +230,16 @@ local operator is explicitly steering you outside the room conversation.
\`thread_id\` appears there only when the message is already in a thread.
**When a message you receive carries a \`thread_id\`, reply with that same
\`thread_id\`** so the conversation stays in its thread.
-- Threads bridge to and from Mattermost natively. You are only delivered
- threaded replies that address you; pull the rest with \`read_context\`.
+- Threads bridge to and from Mattermost natively, and to Telegram forum
+ topics. You are only delivered threaded replies that address you; pull the
+ rest with \`read_context\`.
## Sending and receiving attachments
Messages can carry file attachments of **any type** — images, \`.md\`, \`.csv\`,
\`.pdf\`, logs, code — and a single message can carry **several**. Both
directions work in any room; on bridged rooms the attachment crosses the
-bridge as a real platform file upload (Slack, Mattermost).
+bridge as a real platform file upload (Slack, Mattermost, Discord, Telegram).
### Receiving
@@ -373,9 +374,14 @@ none of it is needed to take part in a conversation.
### Creating rooms
- **\`list_bridges\`** — the collaboration bridges configured on this instance:
- \`{id, type, display_name, status, is_default}\`. Only \`status == "active"\`
- bridges are usable. \`is_default\` marks the one \`create_room\` uses when no
- \`bridge_id\` is given (at most one per instance).
+ \`{id, type, display_name, status, is_default, can_create_channels}\`. Only
+ \`status == "active"\` bridges are usable. \`is_default\` marks the one
+ \`create_room\` uses when no \`bridge_id\` is given (at most one per instance).
+ \`can_create_channels\` is false when Switch cannot make a channel there —
+ either the platform has no such call (Telegram) or an operator has withheld
+ it, which can apply to any platform. Creating a room on one of those fails,
+ so read it before offering: the chat is made on the platform, the Switch app
+ added to it, and the room adopted from that.
- **\`create_room\`** — provision a room. Required: \`name\`, \`description\`,
\`agent_names\`. Commonly used: \`bridge_id\`, \`internal_only\`, \`channel_type\`
(\`"channel_public"\`, \`"channel_private"\`, \`"direct"\`), \`user_names\`,
@@ -386,8 +392,11 @@ none of it is needed to take part in a conversation.
- **\`update_room\`** — change an existing room, including its \`aliases\` map.
- **\`invite_agent_to_room\`** — add an existing agent to an existing room by
name. Humans and agents can do the same from inside a room with the
- \`!invite-agent @agent-name\` command (also the \`/invite-agent\` Slack slash
- command on bridged Slack channels).
+ \`!invite-agent @agent-name\` command (also the \`/invite-agent\` slash command
+ on bridged Slack, Discord and Telegram channels; Telegram registers it as
+ \`/invite_agent\`, since it will not accept a hyphen in a command). On Telegram
+ a command tapped from the \`/\` menu is sent immediately with no argument, so
+ the bot asks for the one it needs and runs when you reply with it.
- **\`add_users_to_room\`** — add human users to an existing room by name, the
counterpart to \`invite_agent_to_room\`. Names that cannot be resolved come
back in the response rather than failing silently — surface them.
@@ -434,7 +443,9 @@ agents to coordinate."
1. Call \`list_bridges\`.
2. Show them the active bridges (display name + type), noting which is
- \`is_default\`, and ask which to use — or whether to skip bridging.
+ \`is_default\`, and ask which to use — or whether to skip bridging. Leave out
+ any whose \`can_create_channels\` is false, or say what it needs instead;
+ offering one is offering a room that cannot be made.
3. Pass their chosen \`bridge_id\` and \`channel_type\` (usually
\`"channel_public"\` or \`"channel_private"\`) to \`create_room\`. Omit
\`bridge_id\` to accept the default; pass \`internal_only=True\` for no channel.
@@ -458,6 +469,14 @@ For a private 1:1 between one agent and one human, create a room with
- **Mattermost**: DMs are user-initiated from the client, so creating a
\`direct\` room here fails — the user starts the DM with the agent's bot and
Switch picks it up automatically.
+- **Telegram**: same as Mattermost — the user messages the bot first and
+ Switch adopts the chat. Telegram bots cannot create chats at all, so
+ \`create_room\` fails on a Telegram bridge for *every* channel type, not just
+ \`direct\`; the chat is made in a Telegram client and the bot added to it.
+ \`list_bridges\` reports this as \`can_create_channels: false\`, so check there
+ before offering to make a room rather than finding out from the failure —
+ and note an operator can withhold channel creation from any platform, so a
+ false answer is not Telegram-specific.
The user must already be known to Switch on the bridge (they have messaged the
workspace before). If not, creation fails loudly with \`no user '<name>' is
@@ -658,6 +677,16 @@ Your messages render on whatever platform the room is bridged to
the bold identifier and separate fields with \`·\` or \`—\`.
- **Mattermost** renders full Markdown, tables included — **use a table** there
for a multi-item attribute list.
+- **Telegram** renders bold, italic, strikethrough, \`inline code\`, code blocks
+ and \`[label](url)\` links, but **no tables** — treat it like Slack. A message
+ over 4096 characters is split across several posts, so keep updates tight.
+ Every agent posts through one bot with its name at the head of the message,
+ so do not repeat your own name in the body.
+ - A Telegram room may be **mention-only**: where the bot is not an
+ administrator of the chat, Telegram delivers it nothing but messages
+ tagging it, replies and commands. Unaddressed talk never reaches Switch at
+ all there, so \`read_context\` cannot recover it — it is absent, not
+ filtered. The bridge says so in the chat when it applies.
When unsure, prefer the Slack-safe shape — it reads fine everywhere.
diff --git a/core/pyproject.toml b/core/pyproject.toml
index 28954e42f..4cda42e78 100644
--- a/core/pyproject.toml
+++ b/core/pyproject.toml
@@ -40,6 +40,7 @@ dependencies = [
"itsdangerous>=2.1,<3",
"PyYAML>=6,<7",
"discord-py>=2.4,<3",
+ "python-telegram-bot>=21,<22",
]
# Repo coordinates point at the public switch repo — see RELEASING.md.
diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.py
index 41334b83e..ad91374a7 100644
--- a/core/switch_core/bridges/agent/operations/definitions.py
+++ b/core/switch_core/bridges/agent/operations/definitions.py
@@ -1356,10 +1356,17 @@ async def list_bridges() -> list[dict[str, Any]]:
the list to the user and let them choose, rather than guessing.
Returns:
- List of `{id, type, display_name, status, is_default}` dicts. Only
- `status` == "active" bridges are usable for new rooms; others are
- shown for context. `is_default` marks the bridge that `create_room`
- uses when no `bridge_id` is given (at most one).
+ List of `{id, type, display_name, status, is_default,
+ can_create_channels}` dicts. Only `status` == "active" bridges are
+ usable for new rooms; others are shown for context. `is_default`
+ marks the bridge that `create_room` uses when no `bridge_id` is given
+ (at most one).
+
+ `can_create_channels` is false when Switch cannot make a channel on
+ that bridge — either the platform has no such call (Telegram) or an
+ operator has withheld it. Creating a room on one of those fails, so
+ offer an existing channel instead: the chat is made on the platform,
+ the Switch app is added to it, and the room is adopted from that.
"""
protocol = get_protocol()
return await protocol.list_bridges()
diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.py
index aee3763d9..7a145dd36 100644
--- a/core/switch_core/bridges/agent/protocol/service.py
+++ b/core/switch_core/bridges/agent/protocol/service.py
@@ -1963,6 +1963,13 @@ class ProtocolService:
"display_name": b.display_name,
"status": b.status,
"is_default": b.is_default,
+ # The platform's ceiling and the operator's switch, ANDed: an
+ # agent asking "can I make a room here?" wants one answer, and
+ # gets it before spending a create_room call to find out.
+ "can_create_channels": (
+ b.channel_creation_enabled
+ and self.collab_lifecycle.supports_channel_creation(b.type)
+ ),
}
for b in bridges
]
diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.py
index a2f4be0b7..c1547fe50 100644
--- a/core/switch_core/bridges/collaboration/adapter.py
+++ b/core/switch_core/bridges/collaboration/adapter.py
@@ -5,8 +5,11 @@ import logging
from abc import ABC, abstractmethod
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, replace
+from typing import ClassVar
from switch_core.bridges.collaboration.models import (
+ BridgeInstallLink,
+ ChannelCreationUnsupported,
ChannelType,
InboundAgentJoin,
InboundAppJoin,
@@ -41,6 +44,26 @@ class LiveRuntimeIndicator:
class CollaborationAdapter(ABC):
+ #: Whether this platform can create a channel from Switch at all.
+ #:
+ #: A ceiling, not a preference: an operator may withhold channel creation
+ #: from a connection whose platform allows it, but cannot grant it to one
+ #: that does not. Declared on the class rather than resolved from a running
+ #: bridge so the answer is available before a connection is registered and
+ #: while it is stopped — the operator asks "can this platform do it?" at
+ #: exactly those moments.
+ supports_channel_creation: ClassVar[bool] = True
+
+ #: Whether this platform renders a link whose scheme is not http(s).
+ #:
+ #: False for platforms that linkify only the web schemes. It matters
+ #: because the "Open in Switch Console" deeplink is a `switchdash://` URL:
+ #: where this is False that link cannot work as written, and the deployment
+ #: needs `GATEWAY_PUBLIC_URL` set so Switch can rewrite it to the https
+ #: redirect. Declared here so the lifecycle can say so once at startup
+ #: instead of each bridge discovering it in its own way.
+ renders_custom_url_schemes: ClassVar[bool] = True
+
def __init__(self) -> None:
self._on_message: Callable[[InboundMessage], Awaitable[None]] | None = None
self._on_command: Callable[[InboundCommand], Awaitable[None]] | None = None
@@ -49,6 +72,9 @@ class CollaborationAdapter(ABC):
)
self._on_user_joined: Callable[[InboundUserJoin], Awaitable[None]] | None = None
self._on_app_joined: Callable[[InboundAppJoin], Awaitable[None]] | None = None
+ # Set by set_channel_migration_handler. Called with (old_id, new_id)
+ # when the platform reissues a channel's id.
+ self._on_channel_migrated: Callable[[str, str], Awaitable[None]] | None = None
# Inbound attachment size ceiling, set by the lifecycle service from
# config.agent_media_max_bytes. Adapters check a platform-reported file
# size against this before downloading so an oversize file is rejected
@@ -114,9 +140,20 @@ class CollaborationAdapter(ABC):
can special-case rendering per platform; adapters that don't simply
render the default `content`. The default implementation posts via
`send_message` under the bridge display name; adapters whose platform
- has a distinct bot identity should override to use it."""
+ has a distinct bot identity should override to use it.
+
+ **`content` is Switch Markdown, and this method renders it.** Unlike
+ `send_message`, whose caller translates, every caller here passes an
+ unrendered body — the notices in `bridge_core`, the adapters' own
+ notices, and the relayed admin events alike. An override must therefore
+ run `translate_outbound` itself. Splitting that responsibility between
+ callers is what once sent a body through the conversion twice, and the
+ second pass escapes the markup the first one produced."""
return await self.send_message(
- channel_id, self._bridge_display_name(), content, thread_root_id
+ channel_id,
+ self._bridge_display_name(),
+ self.translate_outbound(content),
+ thread_root_id,
)
def _bridge_display_name(self) -> str:
@@ -126,11 +163,12 @@ class CollaborationAdapter(ABC):
"""How to run `invite-agent` as a native slash command here, if at all.
Native slash commands are per-platform: Slack declares them in its app
- manifest and Discord registers them per guild, while Mattermost and
- Teams have none — so the no-agents notice must not advertise a `/` form
- on a bridge that has none to offer. The invocation differs too, since
- Slack takes a free-text tail where Discord names each argument as its
- own field, so each adapter spells out its own.
+ manifest, Discord registers them per guild and Telegram publishes a bot
+ command menu, while Mattermost and Teams have none — so the no-agents
+ notice must not advertise a `/` form on a bridge that has none to offer.
+ The invocation differs too, since Slack and Telegram take a free-text
+ tail where Discord names each argument as its own field, so each adapter
+ spells out its own.
Returns the body of the bullet; the caller owns the list formatting.
None means this platform has no slash commands.
@@ -416,7 +454,7 @@ class CollaborationAdapter(ABC):
Used for outbound-created DM rooms (`channel_type="direct"`). Platforms
where DMs can only be initiated by the user — and so cannot be created
from Switch — raise instead of pretending to succeed."""
- raise NotImplementedError(
+ raise ChannelCreationUnsupported(
f"{type(self).__name__} cannot create DM channels — on this platform "
"DMs are initiated by the user from the messaging client"
)
@@ -442,6 +480,26 @@ class CollaborationAdapter(ABC):
URL is exposed."""
return None
+ async def install_links(self) -> list[BridgeInstallLink]:
+ """One-click links that add this bridge's app to a chat, if the
+ platform has them.
+
+ Empty by default: on most platforms installation is an app-directory or
+ OAuth flow the operator runs elsewhere, and inventing a link for it
+ would be a link to nowhere. An adapter overrides this only when the
+ platform accepts a URL that selects the chat and works on every client
+ of that platform."""
+ return []
+
+ async def install_note(self) -> str | None:
+ """What the links do not cover, in the platform's own terms.
+
+ Rendered under :meth:`install_links` in the operator dashboard. Some
+ kinds of chat cannot be reached by a link at all, and the operator is
+ better told where to go instead than left to conclude a button is
+ missing. Markdown-free plain text; None when there is nothing to add."""
+ return None
+
@abstractmethod
async def get_channel_type(self, channel_id: str) -> ChannelType: ...
@@ -509,3 +567,15 @@ class CollaborationAdapter(ABC):
from inbound activities (Teams, whose Bot Connector ``serviceUrl`` is
carried on inbound activities) override this to persist it."""
return None
+
+ def set_channel_migration_handler(
+ self, handler: Callable[[str, str], Awaitable[None]]
+ ) -> None:
+ """Install the callback an adapter calls when the platform reissues a
+ channel's id, so the room bound to the old one follows it.
+
+ Stored for every adapter and used by those whose platform does this:
+ Telegram reissues a chat's id when a basic group becomes a supergroup.
+ The symptom without it is one-way traffic — sends still arrive, because
+ the platform forwards them, while nothing inbound matches a room again."""
+ self._on_channel_migrated = handler
diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.py
index cc09816a7..039072f97 100644
--- a/core/switch_core/bridges/collaboration/bridge_core.py
+++ b/core/switch_core/bridges/collaboration/bridge_core.py
@@ -91,7 +91,7 @@ def _no_agents_notice(slash_hint: str | None) -> str:
return (
"👋 I've linked this channel to a new Switch room, but there are no agents "
"in it yet — so no one is here to respond to messages.\n\n"
- "*To add an agent*, invite one by name (swap in the agent you want):\n"
+ "**To add an agent**, invite one by name (swap in the agent you want):\n"
f"{invites}\n\n"
"Once an agent is in the room, @-mention it here and it'll pick up the "
"conversation."
@@ -170,6 +170,7 @@ class BridgeCore:
async def start(self) -> None:
await self._load_channel_map()
await self._load_existing_puppets()
+ self._adapter.set_channel_migration_handler(self._handle_channel_migrated)
await self._adapter.start(
on_message=self._handle_inbound_message,
on_command=self._handle_inbound_command,
@@ -293,7 +294,7 @@ class BridgeCore:
content = (
f"👋 You tagged {app_mention} directly — I'm not linked to an agent "
"in this channel yet.\n\n"
- f"*Agents you can tag directly:*\n{agent_list}"
+ f"**Agents you can tag directly:**\n{agent_list}"
)
# The `!set-alias` shortcut only makes sense when the bot handle is a
# valid alias token. Some platforms (e.g. Teams) use a bot id containing
@@ -305,7 +306,7 @@ class BridgeCore:
pass
else:
content += (
- "\n\n*To make me an agent's entry point*, copy the line below and "
+ "\n\n**To make me an agent's entry point**, copy the line below and "
"swap in the agent's name — after that, tagging me here routes to "
f"that agent:\n!set-alias @agent_name {app_mention}"
)
@@ -641,6 +642,67 @@ class BridgeCore:
channel_name=join.channel_name,
)
+ async def _handle_channel_migrated(self, old_id: str, new_id: str) -> None:
+ """The platform reissued a channel's id: move the room onto the new one.
+
+ Only the id changes — it is the same conversation, with the same people
+ and the same history — so the room follows it rather than a second room
+ being created beside it. Without this the room stays bound to an id
+ nothing arrives from again, while sends keep working because the
+ platform forwards them: the bridge looks alive and is deaf.
+ """
+ lock = self._channel_locks.setdefault(old_id, asyncio.Lock())
+ async with lock:
+ async with self._session_factory() as session:
+ room = await self._room_store.get_by_external_channel(
+ session, self._bridge_id, old_id
+ )
+ if room is None:
+ logger.info(
+ "Channel %s migrated to %s but no room is bound to it",
+ old_id,
+ new_id,
+ )
+ return
+ occupant = await self._room_store.get_by_external_channel(
+ session, self._bridge_id, new_id
+ )
+ if occupant is not None:
+ # The unique index would reject the update anyway. Report it
+ # rather than leaving both rooms looking correct: one of them
+ # is bound to an id that is now dead.
+ logger.error(
+ "Channel %s migrated to %s, but room %s is already bound "
+ "to %s. Room %s is left on the old id and will not "
+ "receive anything from the chat",
+ old_id,
+ new_id,
+ occupant.id,
+ new_id,
+ room.id,
+ )
+ return
+ await self._room_store.update_external_channel(session, room.id, new_id)
+ await session.commit()
+
+ key = (room.id, room.matrix_room_id)
+ self._channel_to_room.pop(old_id, None)
+ self._channel_to_room[new_id] = key
+ self._room_to_channel[key] = new_id
+ logger.warning(
+ "Re-pointed room %s from channel %s to %s after the platform "
+ "reissued the id",
+ room.id,
+ old_id,
+ new_id,
+ )
+
+ await self._adapter.admin_message(
+ new_id,
+ "This chat has been given a new id by the platform. Its Switch room "
+ "has been moved onto it, so messages here reach the agents again.",
+ )
+
# ── Auto-room creation ────────────────────────────────────────────────────
async def _adopt_existing_room(self, channel_id: str) -> tuple[str, str] | None:
@@ -1030,21 +1092,28 @@ class BridgeCore:
event_content, channel_id
)
- content = self._adapter.translate_outbound(event.body)
if admin_marker is not None:
message_type = (
admin_marker.get("type") if isinstance(admin_marker, dict) else None
)
+ # Raw, not translated: `admin_message` renders its own body, the
+ # same way the notices posted directly through it do. Translating
+ # here as well ran the body through twice, and the second pass
+ # escapes the markup the first one produced — a command reply
+ # arrived showing its own `<b>` tags.
message_ref = await self._adapter.admin_message(
channel_id,
- content,
+ event.body,
thread_root_ref,
message_type=message_type,
)
else:
assert sender_name is not None # guarded above
message_ref = await self._adapter.send_message(
- channel_id, sender_name, content, thread_root_id=thread_root_ref
+ channel_id,
+ sender_name,
+ self._adapter.translate_outbound(event.body),
+ thread_root_id=thread_root_ref,
)
if message_ref is not None:
diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.py
index f8892bc5c..5b1225564 100644
--- a/core/switch_core/bridges/collaboration/discord/adapter.py
+++ b/core/switch_core/bridges/collaboration/discord/adapter.py
@@ -8,7 +8,7 @@ import time
from collections import OrderedDict
from collections.abc import Awaitable, Callable, Coroutine
from dataclasses import replace
-from typing import Any
+from typing import Any, ClassVar
import discord
from discord import app_commands
@@ -67,6 +67,10 @@ class DiscordAdapter(CollaborationAdapter):
rather than eagerly for the whole guild.
"""
+ # Discord linkifies only http(s), so the `switchdash://` deeplink needs the
+ # https redirect (`GATEWAY_PUBLIC_URL`) to be clickable here.
+ renders_custom_url_schemes: ClassVar[bool] = False
+
def __init__(self, *, config: DiscordConnectionConfig) -> None:
super().__init__()
self._config = config
@@ -456,6 +460,10 @@ class DiscordAdapter(CollaborationAdapter):
*,
message_type: str | None = None,
) -> str | None:
+ # Renders its own body: every caller of `admin_message` passes Switch
+ # Markdown, so the conversion belongs here rather than at each of
+ # them — one of them forgetting is how a notice reached a chat with
+ # its markup showing.
# Admin/system messages post as the bot application itself — no
# webhook username override — so they read as the platform speaking,
# not an agent.
@@ -477,7 +485,7 @@ class DiscordAdapter(CollaborationAdapter):
return None
return await self._send_chunked(
- content,
+ self.translate_outbound(content),
lambda part: target.send(part, suppress_embeds=True),
where=f"channel {channel_id}",
)
diff --git a/core/switch_core/bridges/collaboration/discord/chunking.py b/core/switch_core/bridges/collaboration/discord/chunking.py
index 536a59f40..f70170315 100644
--- a/core/switch_core/bridges/collaboration/discord/chunking.py
+++ b/core/switch_core/bridges/collaboration/discord/chunking.py
@@ -1,7 +1,8 @@
"""Split outbound text to fit Discord's per-message character limit.
Discord caps a message at 2,000 characters and rejects anything longer with a
-400 — an order of magnitude tighter than Slack, Mattermost or Teams, and well
+400 — an order of magnitude tighter than Slack, Mattermost, Teams or
+Telegram, and well
under what an agent writes when it answers a real question. Without splitting,
the adapter's `HTTPException` handler logs the rejection and returns, so the
message never reaches the channel and the user is shown nothing at all.
diff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.py
index 745b2edb0..2e27dc5d5 100644
--- a/core/switch_core/bridges/collaboration/lifecycle_service.py
+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py
@@ -81,6 +81,20 @@ class CollaborationBridgeLifecycleService:
bridge = self._bridges.get(bridge_id)
return bridge.adapter if bridge is not None else None
+ def supports_channel_creation(self, bridge_type: str) -> bool:
+ """Whether this platform can create a channel from Switch at all.
+
+ Answered from the registered adapter *class*, so it holds for a bridge
+ that is stopped and for a type nobody has registered a connection for
+ yet — both moments where an operator needs the answer. An unknown type
+ is reported as capable: the registration that follows rejects it by
+ name, which is a better error than a capability claim about a platform
+ Switch does not have."""
+ adapter_cls = self._adapter_registry.get(bridge_type)
+ if adapter_cls is None:
+ return True
+ return adapter_cls.supports_channel_creation
+
def get_config_schema(self, bridge_type: str) -> dict[str, object]:
config_cls = self._config_registry.get(bridge_type)
if config_cls is None:
@@ -104,12 +118,20 @@ class CollaborationBridgeLifecycleService:
bridge_type: str,
display_name: str,
connection_config: dict[str, object],
+ channel_creation_enabled: bool,
) -> CollaborationBridge:
adapter_cls = self._adapter_registry.get(bridge_type)
config_cls = self._config_registry.get(bridge_type)
if adapter_cls is None or config_cls is None:
raise ValueError(f"Unknown bridge type: {bridge_type}")
+ if channel_creation_enabled and not adapter_cls.supports_channel_creation:
+ raise ValueError(
+ f"{bridge_type} cannot create channels from Switch, so this "
+ "connection cannot be allowed to. Create the chat on the "
+ "platform and add the bot to it; Switch adopts it as a room."
+ )
+
config_cls.model_validate(connection_config)
safe_name = re.sub(r"[^a-z0-9._=-]", "-", display_name.lower())[:16]
@@ -125,6 +147,7 @@ class CollaborationBridgeLifecycleService:
connection_config=connection_config, # type: ignore[arg-type]
client_id=bridge_client_record.id,
status="active",
+ channel_creation_enabled=channel_creation_enabled,
)
async with self._session_factory() as session:
await self._bridge_store.create(session, bridge)
@@ -158,6 +181,20 @@ class CollaborationBridgeLifecycleService:
)
adapter.set_max_attachment_bytes(self._config.agent_media_max_bytes)
+ if (
+ not adapter_cls.renders_custom_url_schemes
+ and not self._config.gateway_public_url
+ ):
+ logger.warning(
+ "GATEWAY_PUBLIC_URL is not set and %s only renders http(s) links, "
+ "so the 'Open in Switch Console' deeplink cannot be clickable on "
+ "bridge %s — it is posted as copyable text instead. Set "
+ "GATEWAY_PUBLIC_URL to the Switch API's public origin (scheme + "
+ "host, no path) to turn it into a real link",
+ bridge.type,
+ bridge_id,
+ )
+
async with self._session_factory() as session:
bridge_client_record = await self._client_store.get(
session, bridge.client_id
diff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.py
index b63d97410..ae10819eb 100644
--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py
+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py
@@ -163,7 +163,13 @@ class MattermostAdapter(CollaborationAdapter):
In a normal channel it goes out as the dedicated Switch Admin bot. A
1:1 DM channel cannot admit a third bot, so there it falls back to the
agent bot that owns the DM, lightly marked so it reads as a system
- notice rather than the agent's own voice."""
+ notice rather than the agent's own voice.
+
+ Renders its own body: every caller passes Switch Markdown, so the
+ conversion belongs here rather than at each of them — one of them
+ forgetting is how a notice reached a channel with its markup showing.
+ """
+ content = self.translate_outbound(content)
loop = self._main_loop
if loop is None:
logger.error("Cannot post admin message: event loop not initialized")
diff --git a/core/switch_core/bridges/collaboration/models.py b/core/switch_core/bridges/collaboration/models.py
index 70b47e81f..53feecbb8 100644
--- a/core/switch_core/bridges/collaboration/models.py
+++ b/core/switch_core/bridges/collaboration/models.py
@@ -5,6 +5,18 @@ from pydantic import BaseModel
ChannelType = Literal["lobby", "channel_public", "channel_private", "group", "direct"]
+class ChannelCreationUnsupported(ValueError):
+ """Raised when a bridge will not create a channel for a new room.
+
+ Either the platform has no such call — a Telegram bot cannot create a chat
+ — or an operator has withheld it from this connection. Both are answers to
+ a caller's request rather than faults, so this is a ``ValueError``: every
+ door into room creation already turns one into a 4xx carrying the message,
+ where an unexpected exception becomes an opaque 500 and the explanation
+ never leaves the server.
+ """
+
+
class Attachment(BaseModel):
"""An inbound file attachment of any type, with its raw bytes.
@@ -104,5 +116,22 @@ class InboundAppJoin(BaseModel):
channel_name: str | None = None
+class BridgeInstallLink(BaseModel):
+ """A link that adds this bridge's app to a channel in one step.
+
+ Some platforms can express the whole install — pick a chat, grant the
+ permissions the bridge needs, confirm — as a single URL, which is strictly
+ better than a documented sequence of clicks an operator performs by hand.
+ Adapters that can build one return it here and the operator dashboard
+ offers it; the rest return nothing and the platform's own admin UI remains
+ the way in.
+ """
+
+ key: str
+ label: str
+ description: str
+ url: str
+
+
class BridgeConnectionConfig(BaseModel):
pass
diff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.py
index e1fab7ab3..32119aa64 100644
--- a/core/switch_core/bridges/collaboration/slack/adapter.py
+++ b/core/switch_core/bridges/collaboration/slack/adapter.py
@@ -160,7 +160,7 @@ class SlackAdapter(CollaborationAdapter):
try:
result = await self._web_client.chat_postMessage(
channel=channel_id,
- text=content,
+ text=self.translate_outbound(content),
username=sender_name,
icon_url=self._get_agent_icon(sender_name),
thread_ts=thread_ts,
@@ -188,6 +188,10 @@ class SlackAdapter(CollaborationAdapter):
*,
message_type: str | None = None,
) -> str | None:
+ # Renders its own body: every caller of `admin_message` passes Switch
+ # Markdown, so the conversion belongs here rather than at each of
+ # them — one of them forgetting is how a notice reached a chat with
+ # its markup showing.
# On Slack an admin/system message renders as the Switch app itself —
# no per-message username/icon override — so it reads as the platform
# speaking, not an agent. message_type is available for future
diff --git a/core/switch_core/bridges/collaboration/telegram/__init__.py b/core/switch_core/bridges/collaboration/telegram/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/core/switch_core/bridges/collaboration/telegram/adapter.py b/core/switch_core/bridges/collaboration/telegram/adapter.py
new file mode 100644
index 000000000..924cf3325
--- /dev/null
+++ b/core/switch_core/bridges/collaboration/telegram/adapter.py
@@ -0,0 +1,1918 @@
+from __future__ import annotations
+
+import hashlib
+import html
+import logging
+import re
+import time
+from collections import OrderedDict
+from collections.abc import Awaitable, Callable, Coroutine
+from dataclasses import replace
+from typing import Any, ClassVar, NamedTuple
+
+from telegram import (
+ BotCommand,
+ ForceReply,
+ InputMediaDocument,
+ InputMediaPhoto,
+ LinkPreviewOptions,
+ ReplyParameters,
+ Update,
+)
+from telegram.constants import ChatAction, ChatType, ParseMode
+from telegram.error import BadRequest, Conflict, TelegramError
+from telegram.ext import Application, ApplicationBuilder, TypeHandler
+
+from switch_core.bridges.agent.commands import COMMANDS, COMMANDS_BY_NAME, CommandArg
+from switch_core.bridges.collaboration.adapter import (
+ CollaborationAdapter,
+ LiveRuntimeIndicator,
+)
+from switch_core.bridges.collaboration.models import (
+ Attachment,
+ AttachmentFailure,
+ BridgeConnectionConfig,
+ BridgeInstallLink,
+ ChannelCreationUnsupported,
+ ChannelType,
+ InboundAgentJoin,
+ InboundAppJoin,
+ InboundCommand,
+ InboundMessage,
+ InboundUserJoin,
+ OutboundAttachment,
+)
+from switch_core.bridges.collaboration.telegram.chunking import (
+ MAX_MESSAGE,
+ chunk_message,
+)
+
+logger = logging.getLogger(__name__)
+
+# A caption over this is posted as its own message ahead of the file. The
+# message-length cap lives in `chunking`, which owns the splitting.
+_MAX_CAPTION_CHARS = 1024
+
+# The Bot API refuses to serve a file larger than this, whatever the bridge's
+# own ceiling is set to.
+_MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024
+
+# sendMediaGroup takes between two and ten items, all of the same kind.
+_MEDIA_GROUP_MIN = 2
+_MEDIA_GROUP_MAX = 10
+
+_ALLOWED_UPDATES = ["message", "channel_post", "my_chat_member"]
+
+# Switch's own in-room prefix, plus Telegram's native one.
+_COMMAND_PREFIXES = ("!", "/")
+
+# The payload the dashboard's one-click links carry, delivered back to the bot
+# as `/start <payload>` once it has been added. It authorises nothing — anyone
+# able to add a bot to a chat can do so without it — it only distinguishes an
+# install started from Switch from someone adding the bot by hand, which is
+# worth saying in the chat and in the logs.
+_INSTALL_PAYLOAD = "switch"
+
+# Telegram will only register a command spelled in these characters, and caps a
+# description at 256. A name it rejects is left out of the menu rather than
+# taking the whole call down.
+_TELEGRAM_COMMAND_RE = re.compile(r"[a-z0-9_-]{1,32}")
+_MAX_COMMAND_DESCRIPTION = 256
+
+# Supergroup and channel ids are the internal id with a -100 prefix; t.me/c/
+# links carry the internal id alone.
+_SUPERGROUP_PREFIX = "-100"
+
+_NO_PREVIEW = LinkPreviewOptions(is_disabled=True)
+
+# The URL schemes Telegram will actually turn into a link. An `<a>` carrying
+# anything else is not rendered as written: the API rejects the message with
+# "unsupported URL protocol", or the client keeps the label and drops the link,
+# and which of the two you get is not ours to decide. A `switchdash://` deeplink
+# is exactly that case, so it is rendered as copyable text instead of an anchor
+# that may quietly vanish along with the message around it.
+_LINKABLE_SCHEMES = ("http://", "https://", "tg://", "mailto:")
+
+# The palette agent marks are drawn from. Solid colour circles, because they
+# stay legible at the size Telegram renders an emoji inline and carry no meaning
+# of their own to be misread — a mark says "same speaker as before", nothing
+# more. Eight is enough to make neighbouring agents in one chat almost always
+# differ without the colours becoming hard to tell apart.
+_AGENT_MARKERS = (
+ "\U0001f535",
+ "\U0001f7e2",
+ "\U0001f7e3",
+ "\U0001f7e0",
+ "\U0001f534",
+ "\U0001f7e1",
+ "\U0001f7e4",
+ "\u26ab",
+)
+
+
+class _ChatVisibility(NamedTuple):
+ """What the bridge can see in one chat, and how certain that is.
+
+ ``status`` is ``"full"``, ``"mention_only"`` or ``"unknown"``.
+ ``via_admin`` is True only when it was settled by the bot's administrator
+ status *in this chat*, which is the one conclusive answer — see
+ ``_chat_visibility``.
+ """
+
+ status: str
+ via_admin: bool
+
+
+class TelegramConnectionConfig(BridgeConnectionConfig):
+ bot_token: str
+ bot_username: str
+
+
+class TelegramAdapter(CollaborationAdapter):
+ """Telegram collaboration bridge adapter.
+
+ Single-bot identity model. Telegram has no per-message identity override —
+ no equivalent of a Discord webhook's username/avatar — so every agent posts
+ through the one bot and is distinguished by its name rendered at the head of
+ the message. Inbound arrives by long polling (an outbound connection, no
+ public ingress); outbound goes through the Bot API.
+
+ The bot has to be able to see the conversation, and Telegram offers two
+ routes to that: privacy mode is disabled in BotFather for the bot globally,
+ or the bot is an administrator of the chat, which exempts it whatever the
+ setting says. Setup takes the first — one setting per bot rather than a
+ promotion per group — and the dashboard's install link therefore asks for
+ no rights at all; admin is offered only as the repair for a chat the bot
+ joined before the setting was changed. A bot that is neither runs
+ mention-only — it receives commands, replies to itself and messages that
+ tag it, and nothing else — which is disclosed in the chat rather than left
+ to be deduced from silence.
+
+ Chats are adopted, never created: the Bot API gives a bot no way to create a
+ group or channel, so ``supports_channel_creation`` is False and a chat's
+ Switch room is provisioned when the bot is added to it or on its first
+ bridged message.
+ """
+
+ supports_channel_creation: ClassVar[bool] = False
+ renders_custom_url_schemes: ClassVar[bool] = False
+
+ def __init__(self, *, config: TelegramConnectionConfig) -> None:
+ super().__init__()
+ self._config = config
+ self._app: Application | None = None # type: ignore[type-arg]
+ self._bot: Any = None
+ self._bot_user_id: int = 0
+ self._bot_username = config.bot_username.lstrip("@")
+ self._seen_ids: OrderedDict[tuple[str, int], None] = OrderedDict()
+ self._seen_ids_max = 1000
+ # Telegram user id ↔ username caches, for rendering outbound mentions of
+ # people who address by numeric id rather than handle.
+ self._user_names: dict[int, str] = {}
+ self._username_to_id: dict[str, int] = {}
+ # Whether BotFather's privacy mode is off for this bot, read from getMe
+ # at startup. It is a global setting and says nothing about any one
+ # chat, so it is only half of what _chat_visibility decides.
+ self._privacy_mode_disabled = False
+ # Whether BotFather allows this bot into groups at all, also from
+ # getMe. Assumed until the bot answers, which is BotFather's default.
+ self._can_join_groups = True
+ # chat id -> the visibility last announced in it, so a reconnect or a
+ # second join repeats nothing while a real change is always said.
+ self._visibility_announced: dict[str, str] = {}
+ # (chat id, our prompt's message id) -> the command that prompt is
+ # waiting on an argument for. Bounded like _seen_ids: an unanswered
+ # prompt is abandoned rather than remembered forever.
+ self._awaiting_args: OrderedDict[tuple[str, int], str] = OrderedDict()
+ self._awaiting_args_max = 200
+ # The bot can delete its own messages, so runtime state renders as a
+ # persistent message (the base class's _working_msg) rather than the
+ # one-shot typing action.
+
+ # ── Lifecycle ────────────────────────────────────────────────────────────
+
+ async def start(
+ self,
+ on_message: Callable[[InboundMessage], Awaitable[None]],
+ on_command: Callable[[InboundCommand], Awaitable[None]],
+ on_agent_joined: Callable[[InboundAgentJoin], Awaitable[None]],
+ on_user_joined: Callable[[InboundUserJoin], Awaitable[None]],
+ on_app_joined: Callable[[InboundAppJoin], Awaitable[None]],
+ ) -> None:
+ self._on_message = on_message
+ self._on_command = on_command
+ # Single-bot identity model, so there is no per-agent join to detect.
+ # Unlike Discord, Telegram does signal when the bot itself is added to a
+ # chat, so app joins and user joins are both wired.
+ self._on_agent_joined = on_agent_joined
+ self._on_user_joined = on_user_joined
+ self._on_app_joined = on_app_joined
+
+ app = ApplicationBuilder().token(self._config.bot_token).build()
+ app.add_handler(TypeHandler(Update, self._make_on_update()))
+ self._app = app
+ self._bot = app.bot
+
+ await app.initialize()
+ me = await app.bot.get_me()
+ self._bot_user_id = me.id
+ if me.username and me.username != self._bot_username:
+ # The configured value used to win, and every link built from it
+ # pointed at whatever account that name resolves to — which is not
+ # this bot, and on Telegram is quite possibly somebody else's. The
+ # token identifies the bot; the name is a label an operator typed.
+ logger.warning(
+ "Configured Telegram bot_username %r is not this bot's username "
+ "%r — using the one the Bot API reports, so links resolve. Fix "
+ "the bridge's configuration: the field wants the @handle, not "
+ "the display name",
+ self._bot_username,
+ me.username,
+ )
+ if me.username:
+ self._bot_username = str(me.username)
+ self._privacy_mode_disabled = bool(
+ getattr(me, "can_read_all_group_messages", False)
+ )
+ # A bot with "Allow Groups?" turned off in BotFather cannot be added to
+ # one at all, and Telegram answers an add-to-group link by opening a
+ # chat with the bot — a link that looks like it did nothing.
+ self._can_join_groups = bool(getattr(me, "can_join_groups", True))
+ self._report_privacy_mode()
+ if not self._can_join_groups:
+ logger.warning(
+ "Telegram bot @%s has groups disabled in BotFather, so it cannot "
+ "be added to one and the 'Add to a Telegram group' link is not "
+ "offered. Enable it in BotFather: /mybots -> select the bot -> "
+ "Bot Settings -> Allow Groups?",
+ self._bot_username,
+ )
+ await app.start()
+ if app.updater is None:
+ raise RuntimeError("Telegram application was built without an updater")
+ await app.updater.start_polling(
+ allowed_updates=_ALLOWED_UPDATES, error_callback=self._on_polling_error
+ )
+ logger.info("Telegram adapter connected as @%s (id %s)", me.username, me.id)
+ await self._publish_command_menu()
+
+ async def _publish_command_menu(self) -> None:
+ """Publish the in-room command set so Telegram offers it as you type.
+
+ Telegram only accepts `[a-z0-9_]` in a registered command, so the
+ hyphenated names are published in their underscore spelling —
+ `/invite_agent` — and `_parse_command` accepts either. Without this the
+ commands still work when typed in full, but nothing suggests them, and
+ a `/` menu that lists none implies the bot has none.
+
+ A failure here is logged and left non-fatal, as Discord's sync is: the
+ bridge is fully usable without the menu, and losing it is a far better
+ outcome than refusing to start.
+ """
+ menu = [
+ BotCommand(
+ command=command.name.replace("-", "_"),
+ description=command.description[:_MAX_COMMAND_DESCRIPTION],
+ )
+ for command in COMMANDS
+ if not command.hidden and _TELEGRAM_COMMAND_RE.fullmatch(command.name)
+ ]
+ try:
+ await self._require_bot().set_my_commands(menu)
+ except Exception:
+ logger.exception(
+ "Could not publish the Telegram command menu — commands still "
+ "work when typed, but will not be suggested"
+ )
+ return
+ logger.info("Published %d Telegram commands", len(menu))
+
+ @staticmethod
+ def _on_polling_error(error: TelegramError) -> None:
+ """Report a polling failure, naming the one that looks like nothing.
+
+ Telegram hands each update to a single getUpdates caller, so a second
+ process on the same bot token silently takes a share of the traffic —
+ outbound keeps working, inbound goes intermittent or dead, and the only
+ evidence is a Conflict the poller would otherwise swallow and retry.
+ """
+ if isinstance(error, Conflict):
+ logger.error(
+ "Another process is polling Telegram with this bot token. "
+ "Telegram gives each update to only ONE caller, so this bridge "
+ "is now missing inbound messages while still able to send. "
+ "Stop the other instance — an old deployment still running, a "
+ "local run, or a second replica — or give it its own bot. "
+ "Telegram said: %s",
+ error,
+ )
+ return
+ logger.warning("Telegram polling error: %s", error)
+
+ def _report_privacy_mode(self) -> None:
+ """Record what the global privacy setting does and does not settle.
+
+ BotFather enables privacy mode by default, and a bot in that state
+ receives only `/`-prefixed messages, replies to itself and messages
+ tagging it. That used to be reported here as a fault, but it is not one
+ on its own: Telegram exempts a bot that is an administrator of a chat,
+ so a bridge whose chats were joined through the dashboard's install
+ link sees everything with privacy mode left exactly as BotFather set
+ it. Whether any one chat is readable is therefore a per-chat question,
+ answered by _chat_visibility as chats are joined and audited.
+ """
+ if self._privacy_mode_disabled:
+ logger.info(
+ "Telegram privacy mode is disabled for @%s: the bridge sees all "
+ "messages in every chat it is in",
+ self._bot_username,
+ )
+ return
+ logger.info(
+ "Telegram privacy mode is enabled for @%s (BotFather's default): the "
+ "bridge sees the whole conversation only in chats where the bot is an "
+ "administrator, and mentions, replies and commands everywhere else. "
+ "Each chat is checked as it is joined",
+ self._bot_username,
+ )
+
+ async def _chat_visibility(self, channel_id: str) -> _ChatVisibility:
+ """What the bridge can actually see in one chat.
+
+ ``"full"`` — every message. ``"mention_only"`` — commands, replies to
+ the bot and messages tagging it, which is Telegram filtering before the
+ update ever reaches us and cannot be worked around in code.
+ ``"unknown"`` — the lookup failed, so nothing is claimed either way.
+
+ Two things grant full visibility: the bot is an administrator of this
+ chat, or privacy mode is off for the bot globally. A 1:1 chat is always
+ fully visible — privacy mode has never applied to private chats.
+
+ ``via_admin`` says which of the two it was, because they are not equally
+ certain. Administrator status is read from this chat and is conclusive.
+ The global setting is not: Telegram only re-reads it when the bot
+ **joins**, so a bot that was already in a chat before privacy mode was
+ disabled is still filtered there, and no Bot API call distinguishes
+ that from a working one. Callers that can act on the difference say so
+ rather than reporting certainty nothing has.
+ """
+ if self._bot is None:
+ return _ChatVisibility("unknown", via_admin=False)
+ try:
+ chat = await self._bot.get_chat(self._chat_id(channel_id))
+ except Exception:
+ logger.debug(
+ "Could not resolve Telegram chat %s while checking visibility",
+ channel_id,
+ exc_info=True,
+ )
+ return _ChatVisibility("unknown", via_admin=False)
+ if self._channel_type_of(chat) == "lobby":
+ return _ChatVisibility("full", via_admin=False)
+ try:
+ member = await self._bot.get_chat_member(
+ chat_id=self._chat_id(channel_id), user_id=self._bot_user_id
+ )
+ except Exception:
+ logger.debug(
+ "Could not read the bot's membership of Telegram chat %s",
+ channel_id,
+ exc_info=True,
+ )
+ return _ChatVisibility("unknown", via_admin=False)
+ status = str(getattr(member, "status", "") or "")
+ if status in ("administrator", "creator"):
+ return _ChatVisibility("full", via_admin=True)
+ if self._privacy_mode_disabled:
+ return _ChatVisibility("full", via_admin=False)
+ return _ChatVisibility("mention_only", via_admin=False)
+
+ async def announce_visibility(self, channel_id: str) -> None:
+ """Tell a chat what the bridge can see in it, when that changes.
+
+ A mention-only bridge works — agents are addressed by `@name`, which is
+ one of the few things Telegram does deliver — but it will not follow a
+ conversation nobody tags it in, and the failure is otherwise
+ indistinguishable from agents ignoring people. So it is said in the
+ chat, where whoever just added the bot is looking, along with the one
+ action that fixes it.
+
+ Said again only when the answer actually changes, so promoting the bot
+ confirms itself and retracts the warning, and demoting it does not go
+ unmentioned — while a reconnect or a second join stays silent.
+ """
+ visibility = await self._chat_visibility(channel_id)
+ if visibility.status == "unknown":
+ return
+ previous = self._visibility_announced.get(channel_id)
+ if previous == visibility.status:
+ return
+ self._visibility_announced[channel_id] = visibility.status
+ if visibility.status == "full":
+ logger.info("Telegram chat %s is fully visible to the bridge", channel_id)
+ if previous == "mention_only":
+ await self.admin_message(
+ channel_id,
+ "✅ **I can see the whole conversation here now.** Agents "
+ "will follow this chat without having to be tagged.",
+ )
+ return
+ logger.warning(
+ "Telegram chat %s is mention-only: the bot is not an administrator "
+ "there and privacy mode is on, so ordinary messages are never "
+ "delivered to the bridge",
+ channel_id,
+ )
+ await self.admin_message(
+ channel_id,
+ "⚠️ **I can only see messages that tag me here.** Telegram is "
+ "filtering this chat before anything reaches me, so agents will "
+ f"follow whatever is addressed to `@{self._bot_username}` "
+ "or to an agent by name, and nothing else.\n\n"
+ "**To fix it everywhere, once:** in @BotFather, "
+ "`/mybots` → this bot → Bot Settings → Group Privacy → "
+ "**Turn off**. Telegram reads that when I join a chat, so I have "
+ "to be removed from this one and added back for it to take here — "
+ "but every group you add me to afterwards just works.\n\n"
+ "**To fix only this chat, now:** make me an administrator of it. "
+ "No particular permission is needed. If Telegram converts the group "
+ "to a supergroup when you do, that is expected — the Switch room "
+ "follows it.",
+ )
+
+ async def ensure_channel_subscriptions(
+ self, channels: list[tuple[str, str]]
+ ) -> None:
+ """Audit what the bridge can see in each chat it is already bridging.
+
+ Telegram needs no subscriptions — long polling delivers everything the
+ bot is entitled to — but this is the one call that arrives on startup
+ holding the bridge's known chats, and a chat can lose visibility
+ between runs: the bot is demoted, or privacy mode is turned back on.
+ Logged rather than posted, so a restart does not repost a notice in
+ every chat.
+ """
+ for channel_id, channel_type in channels:
+ if channel_type == "lobby":
+ continue
+ visibility = await self._chat_visibility(channel_id)
+ if visibility.status == "mention_only":
+ logger.warning(
+ "Telegram chat %s is mention-only: the bot is not an "
+ "administrator there and privacy mode is on. Ordinary "
+ "messages in it never reach Switch",
+ channel_id,
+ )
+ elif visibility.status == "full" and not visibility.via_admin:
+ # Taken on trust: Telegram reads the global privacy setting
+ # when the bot joins, and nothing in the Bot API reports which
+ # value was read for this chat. A bot that was already here
+ # before privacy mode was disabled is still being filtered, and
+ # this line is the only place that says so.
+ logger.info(
+ "Telegram chat %s is assumed fully visible because privacy "
+ "mode is off for the bot; if messages from it never arrive, "
+ "the bot was in the chat before that was changed — remove "
+ "it and add it back, or make it an administrator",
+ channel_id,
+ )
+
+ async def install_links(self) -> list[BridgeInstallLink]:
+ """The link that adds this bot to a group.
+
+ `?startgroup` opens a chat picker, so adding the bot is one choice and
+ one confirmation rather than a documented sequence of clicks. It asks
+ for no rights, because the bridge needs none: a bot posts and deletes
+ its own messages in a group as an ordinary member.
+
+ **Nothing here uses Telegram's `admin=` parameter, deliberately.** Two
+ earlier versions did — adding the bot to a group as an administrator to
+ bypass privacy mode, and to a channel because a bot can only be in one
+ as an administrator. Both were withdrawn after a client was found that
+ ignores the parameter and opens a chat with the bot instead, which is
+ indistinguishable from a link that does nothing. A group needs no rights
+ anyway, so it loses nothing. A channel cannot be done this way at all,
+ so no link is offered for one and the guide gives the by-hand route:
+ the channel's Administrators screen, which works on every client.
+
+ The username is the one the Bot API reports, not the configured one —
+ a link built from a name that resolves to some other account opens a
+ chat with *it* and looks like the link did nothing.
+
+ The link is withheld from a bot BotFather has barred from groups,
+ because Telegram answers that by opening a chat with the bot too.
+ """
+ if not self._bot_username or not self._can_join_groups:
+ return []
+ return [
+ BridgeInstallLink(
+ key="group",
+ label="Add to a Telegram group",
+ description=(
+ "Pick a group and confirm — the bot needs no permissions "
+ "there. Switch creates the room as it lands, and the bot "
+ "says in the chat whether it can see the conversation."
+ ),
+ url=(
+ f"https://t.me/{self._bot_username}?startgroup={_INSTALL_PAYLOAD}"
+ ),
+ )
+ ]
+
+ async def install_note(self) -> str | None:
+ """Where to go for a broadcast channel, which has no link.
+
+ Telegram admits a bot to a channel as an administrator or not at all,
+ and the parameter that would grant that in a link is not honoured by
+ every Telegram client. So there is nothing to click, and the operator
+ is told the route that does work rather than left looking for a button.
+ """
+ return (
+ "Broadcast channels have no link: Telegram only admits a bot to one "
+ "as an administrator, and no link does that on every Telegram "
+ "client. Add the bot from the channel itself — Administrators → Add "
+ "Admin → the bot → Post Messages, Edit Messages, Delete Messages — "
+ "and Switch adopts it as a room the moment it lands."
+ )
+
+ def _make_on_update(self) -> Callable[[Any, Any], Coroutine[Any, Any, None]]:
+ async def on_update(update: Any, _context: Any) -> None:
+ try:
+ await self._handle_update(update)
+ except Exception:
+ logger.exception("Failed to handle inbound Telegram update")
+
+ return on_update
+
+ async def stop(self) -> None:
+ app = self._app
+ self._app = None
+ if app is not None:
+ for shutdown in (
+ app.updater.stop if app.updater else None,
+ app.stop,
+ app.shutdown,
+ ):
+ if shutdown is None:
+ continue
+ try:
+ await shutdown()
+ except Exception:
+ logger.exception("Error while stopping the Telegram adapter")
+ self._bot = None
+ logger.info("Telegram adapter stopped")
+
+ def _require_bot(self) -> Any:
+ if self._bot is None:
+ raise RuntimeError("Telegram bot not connected")
+ return self._bot
+
+ # ── Messaging ────────────────────────────────────────────────────────────
+
+ async def send_message(
+ self,
+ channel_id: str,
+ sender_name: str,
+ content: str,
+ thread_root_id: str | None = None,
+ ) -> str | None:
+ """Post as the bot with the agent's name at the head of the message.
+
+ Telegram offers no per-message identity, so the name is part of the body
+ — the same degradation Discord falls back to in DMs, applied everywhere.
+ """
+ body = self._attribute(sender_name, content)
+ return await self._send_text(channel_id, body, thread_root_id)
+
+ async def send_attachment(
+ self,
+ channel_id: str,
+ sender_name: str,
+ filename: str,
+ mimetype: str,
+ data: bytes,
+ caption: str | None = None,
+ thread_root_id: str | None = None,
+ ) -> str | None:
+ """Relay one file, as a photo when Telegram will render it inline.
+
+ Images go through sendPhoto so they preview in the timeline; everything
+ else goes through sendDocument, which preserves the bytes as uploaded.
+ Falls back to the base text notice on failure so a file is never
+ silently dropped.
+ """
+ attributed = self._attribute(
+ sender_name, self.translate_outbound(caption or "")
+ )
+ caption_text, overflow_ref = await self._split_caption(
+ channel_id, attributed, thread_root_id
+ )
+
+ bot = self._require_bot()
+ kwargs = self._reply_kwargs(thread_root_id)
+ try:
+ if self._is_photo(mimetype, len(data)):
+ sent = await bot.send_photo(
+ chat_id=self._chat_id(channel_id),
+ photo=data,
+ caption=caption_text or None,
+ parse_mode=ParseMode.HTML,
+ **kwargs,
+ )
+ else:
+ sent = await bot.send_document(
+ chat_id=self._chat_id(channel_id),
+ document=data,
+ filename=filename,
+ caption=caption_text or None,
+ parse_mode=ParseMode.HTML,
+ **kwargs,
+ )
+ return overflow_ref or self._ref(sent)
+ except TelegramError as e:
+ logger.error(
+ "Failed to send attachment '%s' to Telegram chat %s: %s",
+ filename,
+ channel_id,
+ e,
+ )
+ return await super().send_attachment(
+ channel_id,
+ sender_name,
+ filename,
+ mimetype,
+ data,
+ # An overflowing caption has already been posted on its own;
+ # handing it to the fallback would send it a second time.
+ None if overflow_ref else caption,
+ thread_root_id,
+ )
+
+ async def send_attachments(
+ self,
+ channel_id: str,
+ sender_name: str,
+ files: list[OutboundAttachment],
+ caption: str | None = None,
+ thread_root_id: str | None = None,
+ ) -> str | None:
+ """Relay several files as one Telegram album.
+
+ sendMediaGroup posts two to ten items as a single message, but will not
+ mix photos with documents — so a mixed or out-of-range batch falls back
+ to the base one-at-a-time behaviour rather than being rejected.
+ """
+ if not files:
+ return None
+ if len(files) == 1:
+ file = files[0]
+ return await self.send_attachment(
+ channel_id,
+ sender_name,
+ file.filename,
+ file.mimetype,
+ file.data,
+ caption,
+ thread_root_id,
+ )
+
+ photos = [self._is_photo(f.mimetype, len(f.data)) for f in files]
+ groupable = (
+ _MEDIA_GROUP_MIN <= len(files) <= _MEDIA_GROUP_MAX and len(set(photos)) == 1
+ )
+ if not groupable:
+ return await super().send_attachments(
+ channel_id, sender_name, files, caption, thread_root_id
+ )
+
+ attributed = self._attribute(
+ sender_name, self.translate_outbound(caption or "")
+ )
+ caption_text, overflow_ref = await self._split_caption(
+ channel_id, attributed, thread_root_id
+ )
+
+ media: list[Any] = []
+ for index, file in enumerate(files):
+ # Only the first item's caption is shown for the album as a whole.
+ item_caption = caption_text or None if index == 0 else None
+ if photos[0]:
+ media.append(
+ InputMediaPhoto(
+ media=file.data,
+ caption=item_caption,
+ parse_mode=ParseMode.HTML,
+ )
+ )
+ else:
+ media.append(
+ InputMediaDocument(
+ media=file.data,
+ filename=file.filename,
+ caption=item_caption,
+ parse_mode=ParseMode.HTML,
+ )
+ )
+
+ bot = self._require_bot()
+ try:
+ sent = await bot.send_media_group(
+ chat_id=self._chat_id(channel_id),
+ media=media,
+ **self._reply_kwargs(thread_root_id),
+ )
+ except TelegramError as e:
+ logger.error(
+ "Failed to send a %d-file album to Telegram chat %s: %s — "
+ "falling back to one message per file",
+ len(files),
+ channel_id,
+ e,
+ )
+ return await super().send_attachments(
+ channel_id,
+ sender_name,
+ files,
+ None if overflow_ref else caption,
+ thread_root_id,
+ )
+ first = sent[0] if sent else None
+ return overflow_ref or (self._ref(first) if first is not None else None)
+
+ def slash_invite_hint(self) -> str:
+ # Telegram hands a command's whole tail through as message text, so the
+ # invocation reads exactly like the `!` form.
+ #
+ # The underscore spelling leads because it is the only one Telegram
+ # itself will offer: a registered command may not contain a hyphen, so
+ # `/invite_agent` is what the command menu autocompletes and what the
+ # client renders as a tappable command. The hyphenated form is still
+ # accepted — `_parse_command` translates it back — and is named so that
+ # someone copying it from the docs or from another platform is not left
+ # thinking they typed it wrong.
+ return (
+ "`/invite_agent @agent-name` — the Telegram slash command, as the "
+ "menu offers it (`/invite-agent` works too)"
+ )
+
+ async def admin_message(
+ self,
+ channel_id: str,
+ content: str,
+ thread_root_id: str | None = None,
+ *,
+ message_type: str | None = None,
+ ) -> str | None:
+ # Admin/system notices post unattributed, so they read as the bridge
+ # speaking rather than as one of the agents.
+ #
+ # They arrive as Switch Markdown, like every other body, and have to be
+ # converted the same way: everything here goes out with parse_mode HTML,
+ # so an unconverted notice reaches the chat with its `**` and backticks
+ # showing. Platforms with a Markdown-ish native format got away with
+ # skipping this; Telegram does not.
+ return await self._send_text(
+ channel_id, self.translate_outbound(content), thread_root_id
+ )
+
+ async def update_message(
+ self, channel_id: str, message_ref: str, new_content: str
+ ) -> None:
+ chat_ref, message_id = self._parse_message_ref(message_ref)
+ if not message_id:
+ logger.error("Cannot update message: invalid message ref %s", message_ref)
+ return
+ bot = self._require_bot()
+ try:
+ await bot.edit_message_text(
+ chat_id=self._chat_id(chat_ref or channel_id),
+ message_id=int(message_id),
+ text=self._clamp(new_content),
+ parse_mode=ParseMode.HTML,
+ link_preview_options=_NO_PREVIEW,
+ )
+ except BadRequest as e:
+ # An edit that changes nothing is reported as an error; it is not one.
+ if "not modified" in str(e).lower():
+ return
+ # Same disclosed fallback as a send, and for the same reason it is
+ # not conditioned on the word "parse": markup Telegram will not
+ # accept must not cost the edit entirely, or a status message stays
+ # stale for good with nothing on screen saying why.
+ logger.warning(
+ "Telegram rejected the formatting of an edit to %s (%s) — "
+ "resending it unformatted",
+ message_ref,
+ e,
+ )
+ try:
+ await bot.edit_message_text(
+ chat_id=self._chat_id(chat_ref or channel_id),
+ message_id=int(message_id),
+ text=html.unescape(
+ re.sub(r"<[^>]+>", "", self._clamp(new_content))
+ ),
+ link_preview_options=_NO_PREVIEW,
+ )
+ except TelegramError as retry_error:
+ logger.error(
+ "Failed to update Telegram message %s: %s",
+ message_ref,
+ retry_error,
+ )
+ except TelegramError as e:
+ logger.error("Failed to update Telegram message %s: %s", message_ref, e)
+
+ async def delete_message(self, channel_id: str, message_ref: str) -> None:
+ chat_ref, message_id = self._parse_message_ref(message_ref)
+ if not message_id:
+ logger.error("Cannot delete message: invalid message ref %s", message_ref)
+ return
+ bot = self._require_bot()
+ try:
+ await bot.delete_message(
+ chat_id=self._chat_id(chat_ref or channel_id),
+ message_id=int(message_id),
+ )
+ except TelegramError as e:
+ logger.error("Failed to delete Telegram message %s: %s", message_ref, e)
+
+ # ── Typing ───────────────────────────────────────────────────────────────
+
+ async def send_typing(
+ self, channel_id: str, sender_name: str, is_typing: bool
+ ) -> None:
+ if not is_typing:
+ # Telegram's chat action is a one-shot (~5s) trigger with no cancel
+ # API; it simply expires.
+ return
+ try:
+ bot = self._require_bot()
+ await bot.send_chat_action(
+ chat_id=self._chat_id(channel_id), action=ChatAction.TYPING
+ )
+ except Exception:
+ logger.exception("Failed to trigger typing in Telegram chat %s", channel_id)
+
+ # ── Runtime state ────────────────────────────────────────────────────────
+
+ async def _apply_runtime_state(
+ self,
+ channel_id: str,
+ agent_name: str,
+ state: str,
+ *,
+ notify_user: str | None,
+ thread_root_id: str | None,
+ deeplink_url: str | None = None,
+ detail: str | None = None,
+ ) -> None:
+ """Render runtime state as persistent, deletable status messages.
+
+ A Telegram bot deletes its own messages cleanly (no tombstone), so — like
+ Slack and Discord — the "working on it…" indicator and any "needs your
+ input" pings are posted while relevant and removed when the turn ends.
+ The working indicator stays up through `awaiting-input` (the agent is
+ mid-turn, just paused) and the pings go with it when the turn ends or
+ resumes.
+ """
+ key = (channel_id, agent_name)
+ if state == "working":
+ await self._clear_input_pings(channel_id, agent_name)
+ body = self._working_body(detail, deeplink_url)
+ existing = self._working_msg.get(key)
+ if existing is not None:
+ await self.update_message(
+ channel_id,
+ existing.message_ref,
+ self._attribute(agent_name, body),
+ )
+ self._working_msg[key] = replace(existing, body=body)
+ return
+ ref = await self.send_message(channel_id, agent_name, body, thread_root_id)
+ if ref is not None:
+ self._working_msg[key] = LiveRuntimeIndicator(
+ message_ref=ref,
+ body=body,
+ thread_root_id=thread_root_id,
+ started_at=time.monotonic(),
+ )
+ elif state == "awaiting-input":
+ ref = await self._ping_operator(
+ channel_id, agent_name, notify_user, thread_root_id, deeplink_url
+ )
+ if ref is not None:
+ self._input_pings.setdefault(key, []).append(ref)
+ else:
+ await self._clear_working(channel_id, agent_name)
+ await self._clear_input_pings(channel_id, agent_name)
+
+ async def _clear_working(self, channel_id: str, agent_name: str) -> None:
+ live = self._working_msg.pop((channel_id, agent_name), None)
+ if live is not None:
+ await self.delete_message(channel_id, live.message_ref)
+
+ async def _clear_input_pings(self, channel_id: str, agent_name: str) -> None:
+ refs = self._input_pings.pop((channel_id, agent_name), [])
+ for ref in refs:
+ await self.delete_message(channel_id, ref)
+
+ # ── Channels ─────────────────────────────────────────────────────────────
+
+ async def create_channel(
+ self,
+ name: str,
+ topic: str,
+ *,
+ channel_type: ChannelType = "channel_public",
+ ) -> str:
+ raise ChannelCreationUnsupported(
+ "Telegram bots cannot create chats — the Bot API has no such call. "
+ f"Create the group for '{name}' in a Telegram client and add "
+ f"@{self._bot_username} to it — from the group itself, or with the "
+ "'Add to a chat' link on the bridge in the operator dashboard — and "
+ "Switch adopts it as a room as the bot lands."
+ )
+
+ async def channel_deeplink(self, external_channel_id: str) -> str | None:
+ """A link that opens this chat in Telegram, or None when it has none.
+
+ A chat with a public username has a real `t.me/<name>` address that
+ works anywhere. A private supergroup or channel only has the internal
+ form, which needs a message id — bare `t.me/c/<id>` does not reliably
+ resolve — and opens only for members. A basic group (one that has never
+ been upgraded to a supergroup) has no address at all, so it gets none
+ rather than a button that goes nowhere.
+ """
+ if not external_channel_id:
+ return None
+
+ username = await self._chat_username(external_channel_id)
+ if username:
+ return f"https://t.me/{username}"
+
+ if not external_channel_id.startswith(_SUPERGROUP_PREFIX):
+ return None
+ internal = external_channel_id[len(_SUPERGROUP_PREFIX) :]
+ if not internal.isdigit():
+ return None
+ return f"https://t.me/c/{internal}/1"
+
+ async def _chat_username(self, channel_id: str) -> str | None:
+ """The chat's public `@name`, if it has one.
+
+ Best effort: a failed lookup falls through to the id-derived link
+ rather than costing the caller its button."""
+ if self._bot is None:
+ return None
+ try:
+ chat = await self._bot.get_chat(self._chat_id(channel_id))
+ except Exception:
+ logger.debug(
+ "Could not resolve Telegram chat %s while building a deeplink",
+ channel_id,
+ exc_info=True,
+ )
+ return None
+ username = getattr(chat, "username", None)
+ return str(username) if username else None
+
+ async def home_deeplink(self) -> str | None:
+ """`https://t.me/<bot username>` — the bot's own chat, which is the
+ closest thing Telegram has to a workspace. Built from the configured
+ username; the token never appears in it."""
+ if not self._bot_username:
+ return None
+ return f"https://t.me/{self._bot_username}"
+
+ async def get_channel_type(self, channel_id: str) -> ChannelType:
+ bot = self._require_bot()
+ chat = await bot.get_chat(self._chat_id(channel_id))
+ return self._channel_type_of(chat)
+
+ def _channel_type_of(self, chat: Any) -> ChannelType:
+ """Map a Telegram chat to the bridge's ChannelType.
+
+ 1:1 chats with the bot are the lobby, matching Slack's im and Discord's
+ DM. A group is public when it has a username (a `t.me/<name>` handle
+ anyone can follow) and private otherwise.
+ """
+ chat_type = getattr(chat, "type", None)
+ if chat_type == ChatType.PRIVATE:
+ return "lobby"
+ if chat_type == ChatType.GROUP:
+ # Basic groups are invite-only and cannot have a username.
+ return "channel_private"
+ if getattr(chat, "username", None):
+ return "channel_public"
+ return "channel_private"
+
+ async def add_agents_to_channel(
+ self, channel_id: str, agent_names: list[str]
+ ) -> None:
+ pass
+
+ async def add_users_to_channel(
+ self,
+ channel_id: str,
+ user_names: list[str],
+ user_external_ids: list[str],
+ ) -> None:
+ # The Bot API has no call that adds a member to a chat — a person joins
+ # from a Telegram client or an invite link. Say so rather than reporting
+ # a membership change that never happened.
+ if not user_names:
+ return
+ logger.warning(
+ "Cannot add %s to Telegram chat %s — the Bot API cannot add members; "
+ "they must join from a Telegram client or an invite link",
+ ", ".join(user_names),
+ channel_id,
+ )
+
+ # ── Agent identity ───────────────────────────────────────────────────────
+
+ async def create_agent_identity(
+ self, agent_name: str, agent_description: str
+ ) -> None:
+ pass
+
+ async def remove_agent_identity(self, agent_name: str) -> None:
+ pass
+
+ async def get_channel_agent_names(self, channel_id: str) -> list[str]:
+ return []
+
+ # ── Mentions ─────────────────────────────────────────────────────────────
+
+ def prime_mention_targets(self, targets: dict[str, str]) -> None:
+ """Seed the handle → numeric id map used to render outbound mentions.
+
+ Telegram only notifies a person from a bare `@handle` when they have a
+ public username; everyone else has to be addressed by numeric id. Taking
+ the mapping up front means a person who has not yet spoken in the chat
+ is still mentioned properly, rather than seeing their name as plain text.
+ """
+ for username, user_id in targets.items():
+ if not username or not str(user_id).lstrip("-").isdigit():
+ continue
+ numeric = int(user_id)
+ self._username_to_id[username] = numeric
+ self._user_names.setdefault(numeric, username)
+
+ # ── Translation ──────────────────────────────────────────────────────────
+
+ _CODE_BLOCK_RE = re.compile(r"```[A-Za-z0-9_+.-]*\n?(.*?)```", re.DOTALL)
+ _INLINE_CODE_RE = re.compile(r"`([^`\n]+)`")
+ _HEADING_RE = re.compile(r"^ {0,3}#{1,6}[ \t]+(.*)$", re.MULTILINE)
+ _BULLET_RE = re.compile(r"^([ \t]*)[-*+][ \t]+", re.MULTILINE)
+ # `[` is excluded from the label and `(` from the target deliberately: with
+ # them allowed, a run of unmatched `[` makes the engine retry the whole tail
+ # from every position, which is quadratic — seconds of blocked event loop on
+ # a paste of bracketed log lines, and a denial of service on a hostile one.
+ _LINK_RE = re.compile(r"\[([^\[\]\n]*)\]\(([^()\s]*)\)")
+ _BOLD_RE = re.compile(r"\*\*([^\n]+?)\*\*")
+ _STRIKE_RE = re.compile(r"~~([^\n]+?)~~")
+ _ITALIC_STAR_RE = re.compile(r"(?<![\w*])\*([^*\n]+?)\*(?![\w*])")
+ _ITALIC_USCORE_RE = re.compile(r"(?<![\w_])_([^_\n]+?)_(?![\w_])")
+ _MENTION_RE = re.compile(r"@([A-Za-z0-9][A-Za-z0-9._-]*)")
+
+ def translate_outbound(self, content: str) -> str:
+ """Render Switch's Markdown as the HTML subset Telegram accepts.
+
+ Telegram's own MarkdownV2 is not Markdown — it requires escaping a long
+ list of ordinary punctuation, and a single stray character makes the API
+ reject the whole message. HTML has one escaping rule and a small, stable
+ tag set, so the body is converted once here and sent with parse_mode
+ HTML. Tables are left alone: Telegram has no table rendering, so they go
+ out as the plain text they already are.
+ """
+ if not content:
+ return ""
+
+ # Code spans are extracted before anything else so their contents are
+ # never treated as markup, then restored at the end.
+ stash: list[str] = []
+
+ def _stash(rendered: str) -> str:
+ stash.append(rendered)
+ return f"\x00{len(stash) - 1}\x00"
+
+ def _block(match: re.Match[str]) -> str:
+ code = html.escape(match.group(1).strip("\n"), quote=False)
+ return _stash(f"<pre>{code}</pre>")
+
+ def _inline(match: re.Match[str]) -> str:
+ return _stash(f"<code>{html.escape(match.group(1), quote=False)}</code>")
+
+ text = self._CODE_BLOCK_RE.sub(_block, content)
+ text = self._INLINE_CODE_RE.sub(_inline, text)
+
+ text = html.escape(text, quote=False)
+
+ text = self._HEADING_RE.sub(r"<b>\1</b>", text)
+ text = self._BULLET_RE.sub(r"\1• ", text)
+ text = self._BOLD_RE.sub(r"<b>\1</b>", text)
+ text = self._STRIKE_RE.sub(r"<s>\1</s>", text)
+ text = self._ITALIC_STAR_RE.sub(r"<i>\1</i>", text)
+ text = self._ITALIC_USCORE_RE.sub(r"<i>\1</i>", text)
+
+ # Links are rendered after the inline marks — so a formatted label still
+ # converts — and stashed like code spans, because the mention pass that
+ # follows would otherwise rewrite an `@name` sitting in the label or the
+ # target, nesting an anchor inside an anchor. Telegram rejects that, and
+ # a rejected caption or edit has no plain-text retry to fall back on.
+ def _link(match: re.Match[str]) -> str:
+ label, href = match.group(1), match.group(2)
+ # Already HTML-escaped by the pass above, so only the quote needs
+ # handling here — escaping again would double up the entities.
+ if not href.lower().startswith(_LINKABLE_SCHEMES):
+ # Disclosed degradation: the address stays in the message as a
+ # code span, which Telegram makes tap-to-copy, rather than
+ # being swallowed with the anchor.
+ shown = _stash(f"<code>{href}</code>")
+ return f"{label}: {shown}" if label else shown
+ attr = href.replace('"', "&quot;")
+ return _stash(f'<a href="{attr}">{label}</a>')
+
+ text = self._LINK_RE.sub(_link, text)
+ text = self._MENTION_RE.sub(self._render_mention, text)
+
+ for index, rendered in enumerate(stash):
+ text = text.replace(f"\x00{index}\x00", rendered)
+ return text
+
+ def _render_mention(self, match: re.Match[str]) -> str:
+ """An `@name` we can resolve becomes a real mention; anything else is
+ left as written.
+
+ A bare `@handle` is linked by the Telegram client itself when the
+ username exists, so leaving an unresolved name alone still works for
+ anyone with a public handle — and an agent's name, which is not a
+ Telegram user at all, correctly stays plain text."""
+ user_id = self._username_to_id.get(match.group(1))
+ if user_id is None:
+ return match.group(0)
+ return f'<a href="tg://user?id={user_id}">{match.group(0)}</a>'
+
+ def translate_inbound(self, raw_message: str) -> str:
+ """Telegram delivers plain text with `@handle` mentions already written
+ the way Switch expects, so there is nothing to rewrite. Formatting is
+ carried out-of-band in message entities, which the bridge does not
+ consume."""
+ return raw_message
+
+ # ── Update handling ──────────────────────────────────────────────────────
+
+ async def _handle_update(self, update: Any) -> None:
+ # That Telegram delivered something, and for which chat. With privacy
+ # mode on, the absence of a line here for a message someone can see in
+ # the chat is the whole diagnosis — which needs the shape of the update,
+ # not its contents, so the body and sender are deliberately left out.
+ logger.debug(
+ "Telegram update %s received (%s)",
+ getattr(update, "update_id", "?"),
+ self._update_shape(update),
+ )
+ chat_member = getattr(update, "my_chat_member", None)
+ if chat_member is not None:
+ await self._handle_my_chat_member(chat_member)
+ return
+
+ message = getattr(update, "message", None) or getattr(
+ update, "channel_post", None
+ )
+ if message is not None:
+ await self._handle_message(message)
+
+ async def _handle_my_chat_member(self, event: Any) -> None:
+ """The bot's own membership changed. Being added is Telegram's
+ equivalent of Slack's "app added to channel", and is what provisions the
+ chat's room — Discord has no such signal and has to wait for a message.
+
+ Promotion and demotion arrive here too, and they change what the bridge
+ can see, so this is also where that is re-checked: being promoted is the
+ documented way to turn a mention-only chat into a full one, and nothing
+ else would ever retract the warning that said so."""
+ new_status = getattr(getattr(event, "new_chat_member", None), "status", None)
+ if new_status not in ("member", "administrator"):
+ return
+ chat = getattr(event, "chat", None)
+ if chat is None or self._channel_type_of(chat) == "lobby":
+ return
+ channel_id = str(chat.id)
+ if self._on_app_joined is not None:
+ await self._on_app_joined(
+ InboundAppJoin(
+ channel_id=channel_id,
+ channel_type=self._channel_type_of(chat),
+ channel_name=getattr(chat, "title", None),
+ )
+ )
+ # After provisioning, so the notice cannot arrive before the room it
+ # refers to exists.
+ await self.announce_visibility(channel_id)
+
+ async def _handle_message(self, message: Any) -> None:
+ chat = message.chat
+ chat_id = str(chat.id)
+ if await self._handle_migration(message, chat_id):
+ return
+ channel_type = self._channel_type_of(chat)
+ channel_name = getattr(chat, "title", None)
+
+ author = getattr(message, "from_user", None)
+ if author is not None and author.id == self._bot_user_id:
+ return
+
+ key = (chat_id, int(message.message_id))
+ if key in self._seen_ids:
+ return
+ self._seen_ids[key] = None
+ if len(self._seen_ids) > self._seen_ids_max:
+ self._seen_ids.popitem(last=False)
+
+ new_members = getattr(message, "new_chat_members", None) or []
+ if new_members:
+ await self._handle_new_members(
+ new_members, chat_id, channel_type, channel_name
+ )
+ return
+
+ if author is None:
+ # Channel posts are authored by the channel, not a person; there is
+ # no sender to attribute them to.
+ return
+
+ username = self._display_name(author)
+ self._user_names[author.id] = username
+ self._username_to_id[username] = author.id
+
+ content = str(
+ getattr(message, "text", None) or getattr(message, "caption", None) or ""
+ )
+ root_id = self._root_id_of(message)
+ message_ref = f"{chat_id}:{message.message_id}"
+
+ if await self._handle_start(content.strip(), chat_id, channel_type):
+ return
+
+ # A reply to one of our "what should I use?" prompts carries the
+ # argument the command was missing. Resolved before anything else, so
+ # the answer is not bridged into the room as an ordinary message.
+ answered = self._take_awaited_command(message)
+ if answered is not None and self._on_command:
+ await self._on_command(
+ InboundCommand(
+ channel_id=chat_id,
+ channel_type=channel_type,
+ sender_id=str(author.id),
+ sender_name=username,
+ command=answered,
+ args=content.strip(),
+ message_ref=message_ref,
+ root_id=root_id,
+ channel_name=channel_name,
+ )
+ )
+ return
+
+ parsed = self._parse_command(content.strip())
+ if parsed is not None and self._on_command:
+ name, args = parsed
+ if not args and self._missing_argument(name) is not None:
+ await self._prompt_for_argument(chat_id, name, message.message_id)
+ return
+ await self._on_command(
+ InboundCommand(
+ channel_id=chat_id,
+ channel_type=channel_type,
+ sender_id=str(author.id),
+ sender_name=username,
+ command=name,
+ args=args,
+ message_ref=message_ref,
+ root_id=root_id,
+ channel_name=channel_name,
+ )
+ )
+ return
+
+ if self._on_message is None:
+ return
+
+ attachments, attachment_failures = await self._fetch_attachments(message)
+ if not content and not attachments and not attachment_failures:
+ # A service message — someone left, the title changed, a message was
+ # pinned — carries a real sender and no body. Telegram has no such
+ # thing as an empty user message, so nothing to bridge means nothing
+ # was said. Relaying it puts a blank line in the room.
+ logger.debug(
+ "Skipping Telegram service message %s in %s",
+ message.message_id,
+ chat_id,
+ )
+ return
+
+ await self._on_message(
+ InboundMessage(
+ channel_id=chat_id,
+ channel_type=channel_type,
+ sender_id=str(author.id),
+ sender_name=username,
+ content=content,
+ message_ref=message_ref,
+ root_id=root_id,
+ channel_name=channel_name,
+ attachments=attachments,
+ attachment_failures=attachment_failures,
+ self_mention_token=(
+ self._bot_username
+ if self._bot_username
+ and f"@{self._bot_username}".lower() in content.lower()
+ else None
+ ),
+ )
+ )
+
+ @staticmethod
+ def _update_shape(update: Any) -> str:
+ """Which kind of update this is and which chat it belongs to.
+
+ Enough to tell whether Telegram is delivering, without putting message
+ bodies or sender names into the log — this runs server-side, where the
+ desktop app's redaction does not reach."""
+ for field in ("message", "channel_post", "my_chat_member"):
+ payload = getattr(update, field, None)
+ if payload is None:
+ continue
+ chat = getattr(payload, "chat", None)
+ return f"{field} in chat {getattr(chat, 'id', '?')}"
+ return "no recognised payload"
+
+ async def _handle_migration(self, message: Any, chat_id: str) -> bool:
+ """Follow the chat when Telegram gives it a new id.
+
+ A basic group becomes a supergroup the moment it outgrows one — adding
+ members, promoting a bot, enabling history — and Telegram issues it a
+ brand new chat id when that happens. The room stays keyed to the old
+ one, so inbound stops matching any room while outbound keeps working,
+ because Telegram forwards sends addressed to the old id. Nobody can
+ read that asymmetry from the outside, so the room is re-pointed at the
+ new id here rather than left for an operator to notice and repair.
+
+ Telegram announces the change from both sides — `migrate_to_chat_id` on
+ the last message of the old chat, `migrate_from_chat_id` on the first
+ of the new one — and either is enough; the second finds the work done.
+
+ Returns True when the message is the migration notice itself and should
+ not be bridged.
+ """
+ migrated_to = getattr(message, "migrate_to_chat_id", None)
+ if migrated_to:
+ await self._repoint(chat_id, str(migrated_to))
+ return True
+ migrated_from = getattr(message, "migrate_from_chat_id", None)
+ if migrated_from:
+ await self._repoint(str(migrated_from), chat_id)
+ return True
+ return False
+
+ async def _repoint(self, old_id: str, new_id: str) -> None:
+ if self._on_channel_migrated is None:
+ logger.error(
+ "Telegram chat %s has been reissued the id %s and nothing is "
+ "installed to follow it. The room is still bound to the old id, "
+ "so messages from the chat no longer reach Switch. Re-point the "
+ "room's external channel id at %s",
+ old_id,
+ new_id,
+ new_id,
+ )
+ return
+ logger.warning(
+ "Telegram chat %s has been upgraded to a supergroup and reissued the "
+ "id %s; re-pointing its room",
+ old_id,
+ new_id,
+ )
+ # The new chat is a different chat as far as Telegram is concerned, so
+ # anything said about the old one no longer holds.
+ self._visibility_announced.pop(old_id, None)
+ await self._on_channel_migrated(old_id, new_id)
+
+ async def _handle_new_members(
+ self,
+ members: list[Any],
+ chat_id: str,
+ channel_type: ChannelType,
+ channel_name: str | None,
+ ) -> None:
+ for member in members:
+ if member.id == self._bot_user_id:
+ if self._on_app_joined is not None:
+ await self._on_app_joined(
+ InboundAppJoin(
+ channel_id=chat_id,
+ channel_type=channel_type,
+ channel_name=channel_name,
+ )
+ )
+ continue
+ if self._on_user_joined is None:
+ continue
+ await self._on_user_joined(
+ InboundUserJoin(
+ channel_id=chat_id,
+ channel_type=channel_type,
+ external_user_id=str(member.id),
+ external_username=self._display_name(member),
+ channel_name=channel_name,
+ )
+ )
+
+ async def _handle_start(
+ self, text: str, chat_id: str, channel_type: ChannelType
+ ) -> bool:
+ """Absorb Telegram's own `/start` handshake, and read its payload.
+
+ Adding a bot through a `?startgroup=<payload>` link makes Telegram send
+ the bot `/start@<bot> <payload>` in the chat it was just added to. That
+ is the platform greeting the bot, not somebody running a Switch
+ command, so it is answered here instead of being dispatched into the
+ room as an unknown one. The payload is what distinguishes an install
+ begun from the dashboard, which is worth recording; it authorises
+ nothing.
+
+ A bare `/start` in a 1:1 chat is left alone — it is how a person opens
+ a conversation with the bot, and swallowing it would leave the DM
+ unbridged until they typed again.
+
+ Only groups reach this at all. A channel add sends no `/start` — the
+ start parameter is group-only — and a channel post has no sender, so it
+ is dropped before here; a channel's visibility is announced from the
+ membership event instead.
+
+ Returns True when the message was the handshake and must not be
+ bridged.
+ """
+ parsed = self._parse_command(text)
+ if parsed is None or parsed[0] != "start":
+ return False
+ payload = parsed[1]
+ if channel_type == "lobby" and payload != _INSTALL_PAYLOAD:
+ return False
+ if payload == _INSTALL_PAYLOAD:
+ logger.info(
+ "Telegram chat %s was added from a Switch install link", chat_id
+ )
+ else:
+ logger.debug("Ignoring a bare Telegram /start in chat %s", chat_id)
+ await self.announce_visibility(chat_id)
+ return True
+
+ @staticmethod
+ def _missing_argument(name: str) -> CommandArg | None:
+ """The first required argument of `name`, or None if it takes none.
+
+ Telegram's command menu **sends** a command the instant it is tapped —
+ there is no way to have the client put it in the composer for the user
+ to finish, and no API to say a command takes arguments. So a command
+ that needs one always arrives bare from the menu, and answering with
+ its usage line is a dead end: the only way out is to type the whole
+ thing by hand, which is what the menu was for.
+ """
+ command = COMMANDS_BY_NAME.get(name)
+ if command is None:
+ return None
+ return next((arg for arg in command.args_spec if arg.required), None)
+
+ async def _prompt_for_argument(
+ self, channel_id: str, name: str, replying_to: int
+ ) -> None:
+ """Ask for the argument a bare command did not carry, and remember that
+ we did, so the answer can be run as the command.
+
+ `ForceReply` opens the composer already replying to the prompt, which
+ makes answering one tap rather than a retyped command. `selective` aims
+ it at the person who ran the command, so a busy group is not forced to
+ reply on their behalf. It also survives a mention-only chat: a reply to
+ the bot is one of the few things Telegram still delivers there.
+ """
+ arg = self._missing_argument(name)
+ if arg is None:
+ return
+ body = self.translate_outbound(
+ f"`/{name.replace('-', '_')}` needs one more thing — "
+ f"{arg.description[0].lower() + arg.description[1:]}.\n\n"
+ "Reply to this message with it."
+ )
+ try:
+ sent = await self._require_bot().send_message(
+ chat_id=self._chat_id(channel_id),
+ text=body,
+ parse_mode=ParseMode.HTML,
+ link_preview_options=_NO_PREVIEW,
+ reply_parameters=ReplyParameters(
+ message_id=replying_to, allow_sending_without_reply=True
+ ),
+ reply_markup=ForceReply(
+ selective=True, input_field_placeholder=arg.name
+ ),
+ )
+ except TelegramError as e:
+ # Falling back to running the command bare would answer with its
+ # usage line, which is the dead end this exists to avoid — so say
+ # what happened rather than pretending the prompt went out.
+ logger.error(
+ "Could not ask for the %s argument of /%s in chat %s: %s",
+ arg.name,
+ name,
+ channel_id,
+ e,
+ )
+ return
+ self._awaiting_args[(channel_id, int(sent.message_id))] = name
+ if len(self._awaiting_args) > self._awaiting_args_max:
+ self._awaiting_args.popitem(last=False)
+
+ def _take_awaited_command(self, message: Any) -> str | None:
+ """The command this message answers, if it replies to a prompt of ours.
+
+ One shot: a second reply to the same prompt is an ordinary message, so
+ a conversation that happens to continue under it is not swallowed as
+ repeated command invocations.
+ """
+ replied = getattr(message, "reply_to_message", None)
+ if replied is None:
+ return None
+ key = (str(message.chat.id), int(replied.message_id))
+ return self._awaiting_args.pop(key, None)
+
+ @staticmethod
+ def _parse_command(text: str) -> tuple[str, str] | None:
+ """Split an in-room command out of a message, or None if it is not one.
+
+ Telegram's native command convention is `/name`: the client renders it
+ as a tappable link and offers autocomplete for it, and — with privacy
+ mode left enabled — a `/`-prefixed message is the *only* text a bot
+ reliably receives in a group. So `/name` is accepted as a first-class
+ command alongside Switch's own `!name`, both mapping to the same
+ dispatcher, exactly as Slack's native slash commands already do.
+ """
+ if not text or text[0] not in _COMMAND_PREFIXES:
+ return None
+ parts = text.split(None, 1)
+ # Picked from Telegram's autocomplete in a group, a command arrives
+ # addressed to the bot: `/invite-agent@acme_switch_bot`.
+ name = parts[0][1:].split("@", 1)[0]
+ if not name:
+ return None
+ # Telegram will not register a command containing a hyphen, so the menu
+ # publishes `invite_agent` for `invite-agent`. Only the `/` form needs
+ # that translation back — `!` is Switch's own prefix and its names are
+ # spelled exactly as the dispatcher knows them, so rewriting there would
+ # silently turn a typo into a different command.
+ if text[0] == "/" and name not in COMMANDS_BY_NAME:
+ name = name.replace("_", "-")
+ return name, parts[1].strip() if len(parts) > 1 else ""
+
+ @staticmethod
+ def _root_id_of(message: Any) -> str | None:
+ """The thread this message belongs to, as an external ref.
+
+ A forum topic gives a stable `message_thread_id` for every message in
+ it. Outside forums Telegram has no thread object, only reply chains, so
+ the message being replied to stands in as the root — which is what an
+ outbound reply is anchored to anyway.
+ """
+ thread_id = getattr(message, "message_thread_id", None)
+ if thread_id:
+ return str(thread_id)
+ replied = getattr(message, "reply_to_message", None)
+ if replied is not None:
+ return str(replied.message_id)
+ return None
+
+ @staticmethod
+ def _display_name(user: Any) -> str:
+ """The handle Switch addresses this person by.
+
+ Telegram usernames are optional, so a person without one is identified
+ by their display name with spaces removed — it still has to survive being
+ written as `@name` in a room.
+ """
+ username = getattr(user, "username", None)
+ if username:
+ return str(username)
+ parts = [
+ str(getattr(user, "first_name", "") or ""),
+ str(getattr(user, "last_name", "") or ""),
+ ]
+ joined = "".join(part for part in parts if part).strip().replace(" ", "")
+ # The numeric id is appended, not used only as a fallback: display names
+ # are not unique and stripping the spaces makes collisions likelier
+ # still ("Ann Marie" and "AnnMarie" both give AnnMarie). Two people
+ # sharing a handle would share a room identity, and a mention meant for
+ # one would reach whichever spoke last.
+ user_id = getattr(user, "id", "")
+ return f"{joined}_{user_id}" if joined else f"user{user_id}"
+
+ # ── Attachments ──────────────────────────────────────────────────────────
+
+ async def _fetch_attachments(
+ self, message: Any
+ ) -> tuple[list[Attachment], list[AttachmentFailure]]:
+ """Download every file on a Telegram message, whatever the type.
+
+ Returns the downloaded attachments and, separately, the ones that could
+ not be relayed (oversize, download failure) so the bridge can disclose
+ them in the room rather than dropping them silently.
+ """
+ attachments: list[Attachment] = []
+ failures: list[AttachmentFailure] = []
+ cap = min(self._max_attachment_bytes, _MAX_DOWNLOAD_BYTES)
+
+ for file_id, filename, mimetype, size in self._describe_files(message):
+ if isinstance(size, int) and size > cap:
+ logger.warning(
+ "Telegram attachment %s is %d bytes, over the %d cap",
+ filename,
+ size,
+ cap,
+ )
+ failures.append(
+ AttachmentFailure(
+ filename=filename,
+ reason=f"{size} bytes exceeds the {cap} byte limit",
+ )
+ )
+ continue
+ try:
+ bot = self._require_bot()
+ handle = await bot.get_file(file_id)
+ data = bytes(await handle.download_as_bytearray())
+ except Exception as exc:
+ logger.exception("Failed to download Telegram attachment %s", filename)
+ failures.append(
+ AttachmentFailure(
+ filename=filename, reason=f"download failed: {exc}"
+ )
+ )
+ continue
+ if len(data) > cap:
+ failures.append(
+ AttachmentFailure(
+ filename=filename,
+ reason=f"{len(data)} bytes exceeds the {cap} byte limit",
+ )
+ )
+ continue
+ attachments.append(
+ Attachment(filename=filename, mimetype=mimetype, data=data)
+ )
+ return attachments, failures
+
+ @staticmethod
+ def _describe_files(message: Any) -> list[tuple[str, str, str, int | None]]:
+ """Every downloadable file on a message as
+ `(file_id, filename, mimetype, size)`.
+
+ Telegram models each media kind as its own field rather than one
+ attachments list, and a photo arrives as a ladder of resized versions of
+ which only the last is worth relaying."""
+ found: list[tuple[str, str, str, int | None]] = []
+
+ photos = getattr(message, "photo", None) or []
+ if photos:
+ largest = photos[-1]
+ found.append(
+ (
+ largest.file_id,
+ f"photo_{largest.file_unique_id}.jpg",
+ "image/jpeg",
+ getattr(largest, "file_size", None),
+ )
+ )
+
+ document = getattr(message, "document", None)
+ if document is not None:
+ found.append(
+ (
+ document.file_id,
+ str(getattr(document, "file_name", None) or "file"),
+ str(
+ getattr(document, "mime_type", None)
+ or "application/octet-stream"
+ ),
+ getattr(document, "file_size", None),
+ )
+ )
+
+ for field, fallback_name, fallback_type in (
+ ("video", "video.mp4", "video/mp4"),
+ ("animation", "animation.mp4", "video/mp4"),
+ ("audio", "audio.mp3", "audio/mpeg"),
+ ("voice", "voice.ogg", "audio/ogg"),
+ ("video_note", "video_note.mp4", "video/mp4"),
+ ):
+ media = getattr(message, field, None)
+ if media is None:
+ continue
+ found.append(
+ (
+ media.file_id,
+ str(getattr(media, "file_name", None) or fallback_name),
+ str(getattr(media, "mime_type", None) or fallback_type),
+ getattr(media, "file_size", None),
+ )
+ )
+
+ return found
+
+ # ── Helpers ──────────────────────────────────────────────────────────────
+
+ @staticmethod
+ def _chat_id(channel_id: str) -> int | str:
+ """Telegram wants a numeric chat id, but accepts an `@name` handle."""
+ try:
+ return int(channel_id)
+ except ValueError:
+ return channel_id
+
+ @staticmethod
+ def _ref(message: Any) -> str:
+ return f"{message.chat.id}:{message.message_id}"
+
+ @staticmethod
+ def _parse_message_ref(message_ref: str) -> tuple[str, str]:
+ parts = message_ref.split(":", 1)
+ if len(parts) != 2:
+ logger.error("Invalid Telegram message ref format: %s", message_ref)
+ return "", ""
+ return parts[0], parts[1]
+
+ @staticmethod
+ def _agent_marker(sender_name: str) -> str:
+ """A stable coloured mark for one agent.
+
+ Telegram gives a bot no per-message name or avatar, so every agent
+ arrives under the same app identity and a bold name was the only thing
+ telling them apart — which reads as one speaker once a few of them are
+ talking. A mark that is always the same for the same agent gives a
+ reader something to recognise at a glance, the way an avatar would.
+
+ Derived from the name rather than configured, so it needs no state and
+ no migration and cannot disagree between two bridges. `blake2b` and not
+ `hash()`: the built-in is salted per process, so it would hand the same
+ agent a different colour after every restart.
+
+ Deliberately not a provider logo. The server only distinguishes
+ `claude-code` from `codex`, and Switch Console registers every other
+ provider — Gemini, Cursor, the rest — as `claude-code`; a logo drawn
+ from that would confidently label most agents wrongly.
+ """
+ digest = hashlib.blake2b(sender_name.encode("utf-8"), digest_size=8).digest()
+ return _AGENT_MARKERS[digest[0] % len(_AGENT_MARKERS)]
+
+ @classmethod
+ def _attribute(cls, sender_name: str, content: str) -> str:
+ """Put the agent's mark and name at the head of the body.
+
+ This is the whole of Telegram's per-message identity: one bot posts for
+ every agent, so without the name a reader cannot tell them apart."""
+ name = (
+ f"{cls._agent_marker(sender_name)} "
+ f"<b>{html.escape(sender_name, quote=False)}</b>"
+ )
+ if not content:
+ return name
+ return f"{name}\n{content}" if "\n" in content else f"{name}: {content}"
+
+ @staticmethod
+ def _reply_kwargs(thread_root_id: str | None) -> dict[str, Any]:
+ """Anchor a post to its thread root.
+
+ `allow_sending_without_reply` matters: a root that has since been
+ deleted would otherwise fail the whole send, and a reply landing at the
+ chat root is much better than no message at all."""
+ if not thread_root_id:
+ return {}
+ try:
+ root = int(thread_root_id)
+ except ValueError:
+ logger.error("Ignoring unparseable Telegram thread root %s", thread_root_id)
+ return {}
+ return {
+ "reply_parameters": ReplyParameters(
+ message_id=root, allow_sending_without_reply=True
+ )
+ }
+
+ @staticmethod
+ def _is_photo(mimetype: str, size: int) -> bool:
+ """Whether Telegram will accept this as an inline photo.
+
+ sendPhoto previews in the timeline but re-encodes and caps at 10MB, and
+ rejects formats it cannot resize; anything else keeps its bytes intact
+ as a document."""
+ return mimetype in ("image/jpeg", "image/png", "image/webp") and size <= (
+ 10 * 1024 * 1024
+ )
+
+ @staticmethod
+ def _clamp(text: str) -> str:
+ """The largest valid prefix of an edit that Telegram will accept.
+
+ An edit cannot be split across messages the way a send can, so an
+ over-long one is cut — but cutting the rendered HTML by character count
+ lands mid-tag or mid-attribute, which Telegram rejects outright, and an
+ edit has nowhere to fall back to. Reusing the chunker's first piece
+ keeps the markup balanced."""
+ if len(text) <= MAX_MESSAGE:
+ return text
+ head = chunk_message(text)[0]
+ logger.warning(
+ "A Telegram edit of %d characters was cut to %d to fit the limit",
+ len(text),
+ len(head),
+ )
+ return head
+
+ async def _split_caption(
+ self, channel_id: str, caption: str, thread_root_id: str | None
+ ) -> tuple[str, str | None]:
+ """Fit a caption to Telegram's caption limit.
+
+ A caption longer than the limit is posted as its own message ahead of
+ the file and the file goes out bare, rather than the text being cut off.
+ Returns the caption to attach and the ref of any message posted first."""
+ if len(caption) <= _MAX_CAPTION_CHARS:
+ return caption, None
+ ref = await self._send_text(channel_id, caption, thread_root_id)
+ return "", ref
+
+ async def _send_text(
+ self, channel_id: str, body: str, thread_root_id: str | None
+ ) -> str | None:
+ """Post one body, split across messages if Telegram's cap demands it.
+
+ Returns the ref of the first message so an edit or delete targets the
+ head of the run."""
+ bot = self._require_bot()
+ first_ref: str | None = None
+ for index, chunk in enumerate(chunk_message(body)):
+ kwargs = self._reply_kwargs(thread_root_id) if index == 0 else {}
+ sent = await self._send_chunk(bot, channel_id, chunk, kwargs)
+ if sent is None:
+ return first_ref
+ if first_ref is None:
+ first_ref = sent
+ return first_ref
+
+ async def _send_chunk(
+ self, bot: Any, channel_id: str, chunk: str, kwargs: dict[str, Any]
+ ) -> str | None:
+ try:
+ sent = await bot.send_message(
+ chat_id=self._chat_id(channel_id),
+ text=chunk,
+ parse_mode=ParseMode.HTML,
+ link_preview_options=_NO_PREVIEW,
+ **kwargs,
+ )
+ return self._ref(sent)
+ except BadRequest as e:
+ # Any rejection gets the plain-text retry, not only the ones whose
+ # text says "parse". Telegram refuses markup under several different
+ # messages — an unsupported URL protocol in an anchor is one, and it
+ # says nothing about parsing — and matching on the wording meant
+ # those lost the whole message to a single log line. Retrying
+ # stripped costs one call in the cases that were failing anyway, and
+ # a message that arrives unformatted beats one that never arrives.
+ logger.warning(
+ "Telegram rejected a message to chat %s (%s) — resending it "
+ "unformatted",
+ channel_id,
+ e,
+ )
+ try:
+ sent = await bot.send_message(
+ chat_id=self._chat_id(channel_id),
+ text=html.unescape(re.sub(r"<[^>]+>", "", chunk)),
+ link_preview_options=_NO_PREVIEW,
+ **kwargs,
+ )
+ return self._ref(sent)
+ except TelegramError as retry_error:
+ logger.error(
+ "Failed to send message to Telegram chat %s: %s",
+ channel_id,
+ retry_error,
+ )
+ return None
+ except TelegramError as e:
+ logger.error(
+ "Failed to send message to Telegram chat %s: %s", channel_id, e
+ )
+ return None
diff --git a/core/switch_core/bridges/collaboration/telegram/chunking.py b/core/switch_core/bridges/collaboration/telegram/chunking.py
new file mode 100644
index 000000000..fcf6ba18d
--- /dev/null
+++ b/core/switch_core/bridges/collaboration/telegram/chunking.py
@@ -0,0 +1,143 @@
+"""Split outbound text to fit Telegram's per-message character limit, without
+breaking the markup it carries.
+
+Telegram caps a message at 4,096 characters and rejects anything longer
+outright — well under what an agent writes when it answers a real question, and
+tighter than Slack or Mattermost. Splitting on line boundaries alone is not
+enough here: the body has already been rendered to Telegram's HTML subset, and a
+cut through an open tag makes Telegram refuse *both* halves, so a long code
+block arrives as unformatted text. Tags open at a cut are therefore closed at
+the end of one piece and reopened at the start of the next.
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+
+logger = logging.getLogger(__name__)
+
+MAX_MESSAGE = 4096
+
+_TAG_RE = re.compile(r"<(/?)([a-z]+)[^>]*>")
+
+
+def open_tags(text: str) -> list[tuple[str, str]]:
+ """The tags still open at the end of `text`, outermost first.
+
+ Returned as `(name, opening tag)` so each can be both closed here and
+ reopened verbatim — an `<a href="…">` has to carry its target across."""
+ stack: list[tuple[str, str]] = []
+ for match in _TAG_RE.finditer(text):
+ closing, name = match.group(1), match.group(2)
+ if not closing:
+ stack.append((name, match.group(0)))
+ continue
+ for index in range(len(stack) - 1, -1, -1):
+ if stack[index][0] == name:
+ del stack[index]
+ break
+ return stack
+
+
+def safe_split(text: str, limit: int) -> int:
+ """The best place to cut `text` at or before `limit`.
+
+ Never inside a tag — half an `<a href="…">` is unparseable — and on a
+ line break when there is one late enough to be worth using."""
+ cut = min(limit, len(text))
+ last_open = text.rfind("<", 0, cut)
+ if last_open > text.rfind(">", 0, cut):
+ cut = last_open
+ newline = text.rfind("\n", 0, cut)
+ if newline > cut // 2:
+ cut = newline
+ return max(cut, 1)
+
+
+def chunk_message(body: str) -> list[str]:
+ """Break a body into Telegram-sized pieces, keeping the markup valid.
+
+ Agent output routinely runs past the 4096-character cap, and Telegram
+ rejects an oversize message outright rather than truncating it. A naive
+ split lands inside the formatting — a long code block is the usual
+ casualty — and Telegram then refuses each half, so the whole thing
+ arrives unformatted. Tags left open at a cut are therefore closed at the
+ end of one piece and reopened at the start of the next.
+ """
+ if len(body) <= MAX_MESSAGE:
+ return [body]
+
+ chunks: list[str] = []
+ rest = body
+ reopen = ""
+ while True:
+ candidate = reopen + rest
+ if len(candidate) <= MAX_MESSAGE:
+ chunks.append(candidate)
+ return chunks
+
+ cut = safe_split(candidate, MAX_MESSAGE)
+ closers = closing_tags(candidate[:cut])
+ if cut + len(closers) > MAX_MESSAGE:
+ # Closing the open tags would overflow; cut earlier to fit them.
+ cut = safe_split(candidate, MAX_MESSAGE - len(closers))
+ closers = closing_tags(candidate[:cut])
+ # A cut this early means the markup itself is the problem — a single
+ # tag longer than a whole message, or more nesting than one can carry.
+ # Either way no split preserves it, and forcing one yields a piece with
+ # a byte or two of text in it.
+ if cut <= len(reopen) or cut < MAX_MESSAGE // 4:
+ # Cutting hard here would sever a tag mid-character and put a bare
+ # `<` on the wire, which Telegram rejects — and the plain-text retry
+ # cannot recognise the fragment as a tag either, so the text is
+ # mangled too. Drop the markup for the remainder instead:
+ # unformatted and whole beats formatted and broken.
+ logger.warning(
+ "A Telegram message's markup cannot be split to fit (%d chars "
+ "of open tags, best cut at %d); sending the rest unformatted",
+ len(reopen),
+ cut,
+ )
+ return chunks + _plain_chunks(strip_tags(rest))
+
+ head = candidate[:cut]
+ chunks.append(head.removesuffix("\n") + closers)
+ reopen = "".join(tag for _, tag in open_tags(head)) if closers else ""
+ # Only the single newline the cut was made on is consumed — it is the
+ # separator between the two messages. Stripping the whole run would
+ # swallow blank lines that are part of the body.
+ rest = candidate[cut:].removeprefix("\n")
+ if not rest:
+ return chunks
+
+
+_ANCHOR_RE = re.compile(r'<a href="([^"]*)">(.*?)</a>', re.DOTALL)
+
+
+def strip_tags(text: str) -> str:
+ """The text with the markup removed, for a body whose markup cannot be kept.
+
+ A link becomes `label (target)` rather than just `label`: the target is the
+ part a reader cannot recover, and dropping it silently would lose the very
+ thing that made the message too long to format. Entities stay escaped —
+ these pieces are still sent with HTML parse mode, they simply have no tags.
+ """
+ return _TAG_RE.sub("", _ANCHOR_RE.sub(r"\2 (\1)", text))
+
+
+def _plain_chunks(text: str) -> list[str]:
+ """Split unmarked text on the cleanest line break under the cap."""
+ chunks: list[str] = []
+ rest = text
+ while len(rest) > MAX_MESSAGE:
+ cut = safe_split(rest, MAX_MESSAGE)
+ chunks.append(rest[:cut].removesuffix("\n"))
+ rest = rest[cut:].removeprefix("\n")
+ if rest:
+ chunks.append(rest)
+ return chunks
+
+
+def closing_tags(text: str) -> str:
+ return "".join(f"</{name}>" for name, _ in reversed(open_tags(text)))
diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.py
index 5a9408ec4..14140ea58 100644
--- a/core/switch_core/db/models.py
+++ b/core/switch_core/db/models.py
@@ -498,6 +498,16 @@ class CollaborationBridge(Base):
agent_greetings_enabled: Mapped[bool] = mapped_column(
Boolean, server_default="true", nullable=False
)
+ # Whether an operator permits this connection to create channels on the
+ # platform. Only ever narrows what the platform allows: a bridge whose
+ # adapter reports `supports_channel_creation = False` cannot be granted it
+ # by setting this true, so the effective answer is the two ANDed together.
+ # Kept per connection rather than per type because withholding it is a
+ # deployment's decision — the bot may hold no such permission, or the
+ # organisation may not want rooms appearing from Switch.
+ channel_creation_enabled: Mapped[bool] = mapped_column(
+ Boolean, server_default="true", nullable=False
+ )
# The bridge new rooms land on when no bridge is named. At most one row may
# be true; the partial unique index below is what actually enforces that,
# so concurrent writers cannot produce two defaults.
diff --git a/core/switch_core/db/stores/collaboration_bridge_store.py b/core/switch_core/db/stores/collaboration_bridge_store.py
index 1fd8d0732..0999f31b5 100644
--- a/core/switch_core/db/stores/collaboration_bridge_store.py
+++ b/core/switch_core/db/stores/collaboration_bridge_store.py
@@ -76,6 +76,16 @@ class CollaborationBridgeStore:
await session.flush()
return bridge
+ async def set_channel_creation_enabled(
+ self, session: AsyncSession, bridge_id: str, enabled: bool
+ ) -> CollaborationBridge:
+ bridge = await session.get(CollaborationBridge, bridge_id)
+ if bridge is None:
+ raise ValueError(f"Bridge not found: {bridge_id}")
+ bridge.channel_creation_enabled = enabled
+ await session.flush()
+ return bridge
+
async def set_service_url(
self, session: AsyncSession, bridge_id: str, service_url: str
) -> None:
diff --git a/core/switch_core/db/stores/room_store.py b/core/switch_core/db/stores/room_store.py
index 00288f8e8..fb38aa274 100644
--- a/core/switch_core/db/stores/room_store.py
+++ b/core/switch_core/db/stores/room_store.py
@@ -290,6 +290,18 @@ class RoomStore:
)
return result.scalar_one_or_none()
+ async def update_external_channel(
+ self, session: AsyncSession, room_id: str, external_channel_id: str
+ ) -> None:
+ """Re-point a bridged room at a new external channel id, keeping its
+ bridge and channel type. For a platform that reissues a channel's id
+ under the room (Telegram, when a group becomes a supergroup)."""
+ room = await session.get(Room, room_id)
+ if room is None:
+ raise ValueError(f"Room not found: {room_id}")
+ room.external_channel_id = external_channel_id
+ await session.flush()
+
async def update_protection_config(
self, session: AsyncSession, room_id: str, config: dict[str, object]
) -> None:
diff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.py
index f03b1b5e7..1eb36ad6a 100644
--- a/core/switch_core/gateway/collaborations.py
+++ b/core/switch_core/gateway/collaborations.py
@@ -10,6 +10,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from switch_core.bridges.collaboration.lifecycle_service import (
CollaborationBridgeLifecycleService,
)
+from switch_core.bridges.collaboration.models import BridgeInstallLink
from switch_core.db.models import CollaborationBridge, User
from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
from switch_core.db.stores.external_user_store import ExternalUserStore
@@ -56,6 +57,41 @@ async def _home_url(
return None
+async def _install_links(
+ bridge_id: str, collab_lifecycle: CollaborationBridgeLifecycleService
+) -> list[BridgeInstallLink]:
+ """One-click "add the app to a chat" links, built by the live adapter.
+ Empty when the bridge is not running or its platform has none — the same
+ "offer it only when it works" rule as the home link."""
+ adapter = collab_lifecycle.get_adapter(bridge_id)
+ if adapter is None:
+ return []
+ try:
+ return await adapter.install_links()
+ except Exception:
+ logger.warning(
+ "Failed to build install links for bridge %s", bridge_id, exc_info=True
+ )
+ return []
+
+
+async def _install_note(
+ bridge_id: str, collab_lifecycle: CollaborationBridgeLifecycleService
+) -> str | None:
+ """What the install links do not cover, in the platform's own terms. None
+ when the bridge is not running or the platform has nothing to add."""
+ adapter = collab_lifecycle.get_adapter(bridge_id)
+ if adapter is None:
+ return None
+ try:
+ return await adapter.install_note()
+ except Exception:
+ logger.warning(
+ "Failed to build the install note for bridge %s", bridge_id, exc_info=True
+ )
+ return None
+
+
async def _detail(
bridge: CollaborationBridge,
*,
@@ -76,6 +112,12 @@ async def _detail(
room_count=room_count,
created_at=str(bridge.created_at),
home_url=await _home_url(bridge.id, collab_lifecycle),
+ install_links=await _install_links(bridge.id, collab_lifecycle),
+ install_note=await _install_note(bridge.id, collab_lifecycle),
+ channel_creation_supported=collab_lifecycle.supports_channel_creation(
+ bridge.type
+ ),
+ channel_creation_enabled=bridge.channel_creation_enabled,
)
@@ -90,6 +132,7 @@ async def list_bridge_types(
BridgeTypeInfo(
key=t,
config_schema=collab_lifecycle.get_config_schema(t),
+ channel_creation_supported=collab_lifecycle.supports_channel_creation(t),
)
for t in collab_lifecycle.get_registered_types()
]
@@ -113,6 +156,7 @@ async def create_bridge(
bridge_type=req.bridge_type,
display_name=req.display_name,
connection_config=dict(req.connection_config),
+ channel_creation_enabled=req.channel_creation_enabled,
)
except ValidationError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
@@ -196,9 +240,27 @@ async def update_bridge(
if bridge is None:
raise HTTPException(status_code=404, detail="Bridge not found")
- bridge = await bridge_store.set_agent_greetings_enabled(
- session, bridge_id, payload.agent_greetings_enabled
- )
+ if (
+ payload.channel_creation_enabled
+ and not collab_lifecycle.supports_channel_creation(bridge.type)
+ ):
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ f"{bridge.type} cannot create channels from Switch, so this "
+ "connection cannot be allowed to. Create the chat on the "
+ "platform and add the bot to it; Switch adopts it as a room."
+ ),
+ )
+
+ if payload.agent_greetings_enabled is not None:
+ bridge = await bridge_store.set_agent_greetings_enabled(
+ session, bridge_id, payload.agent_greetings_enabled
+ )
+ if payload.channel_creation_enabled is not None:
+ bridge = await bridge_store.set_channel_creation_enabled(
+ session, bridge_id, payload.channel_creation_enabled
+ )
await session.commit()
rooms = await room_store.get_by_bridge(session, bridge_id)
return await _detail(
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index 8b2cf63e2..628126ee0 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -2,9 +2,10 @@ from __future__ import annotations
from typing import Any
-from pydantic import BaseModel
+from pydantic import BaseModel, Field
from switch_core.addressing import AddressingPolicy
+from switch_core.bridges.collaboration.models import BridgeInstallLink
# ── Rooms ─────────────────────────────────────────────────────────────────────
@@ -421,15 +422,37 @@ class BridgeDetail(BaseModel):
# offers no such link. Never carries a credential — only ids that the
# platform already puts in its own URLs.
home_url: str | None = None
+ # One-click links that add this bridge's app to a chat, from the live
+ # adapter. Empty when the bridge is not running or the platform has no such
+ # link, in which case installation stays a documented manual flow.
+ install_links: list[BridgeInstallLink] = Field(default_factory=list)
+ # What those links do not cover, in the platform's own terms — the kinds of
+ # chat that have to be joined by hand. None when there is nothing to add.
+ install_note: str | None = None
+ # Whether the platform can create a channel from Switch at all, and whether
+ # an operator permits this connection to. The two are separate so a UI can
+ # tell "your organisation turned this off" (changeable here) from "Telegram
+ # has no such call" (not changeable anywhere) — the first is a disabled
+ # switch you can flip, the second a disabled switch with a reason.
+ channel_creation_supported: bool = True
+ channel_creation_enabled: bool = True
class BridgeUpdateRequest(BaseModel):
- agent_greetings_enabled: bool
+ # Both optional so a caller can change one without restating the other; a
+ # request that sets neither changes nothing rather than silently resetting
+ # a field it did not mention.
+ agent_greetings_enabled: bool | None = None
+ channel_creation_enabled: bool | None = None
class BridgeTypeInfo(BaseModel):
key: str
config_schema: dict[str, Any]
+ # Whether this platform can create channels at all. Read from the adapter
+ # class, so it is answerable before any connection of this type exists —
+ # which is exactly when the registration form needs it.
+ channel_creation_supported: bool = True
class BridgeCreateRequest(BaseModel):
@@ -440,6 +463,10 @@ class BridgeCreateRequest(BaseModel):
# Set by the headless standalone bootstrap so a fresh deployment bridges
# rooms out of the box.
set_as_default: bool = False
+ # Whether this connection may create channels on the platform. Defaults on
+ # to keep existing callers behaving as they did; registration rejects it
+ # for a platform that cannot, rather than storing a claim it cannot honour.
+ channel_creation_enabled: bool = True
class ExternalUserSummary(BaseModel):
diff --git a/core/switch_core/main.py b/core/switch_core/main.py
index a2542a5b3..93488daac 100644
--- a/core/switch_core/main.py
+++ b/core/switch_core/main.py
@@ -49,6 +49,10 @@ from switch_core.bridges.collaboration.teams.adapter import (
TeamsAdapter,
TeamsConnectionConfig,
)
+from switch_core.bridges.collaboration.telegram.adapter import (
+ TelegramAdapter,
+ TelegramConnectionConfig,
+)
from switch_core.bridges.resource.service import ResourceService
from switch_core.bridges.resource.tracker import ResourceRequestTracker
from switch_core.clients.admin_client import AdminClient
@@ -382,6 +386,9 @@ async def run() -> None:
collab_lifecycle.register_adapter(
"discord", DiscordAdapter, DiscordConnectionConfig
)
+ collab_lifecycle.register_adapter(
+ "telegram", TelegramAdapter, TelegramConnectionConfig
+ )
# Health check mounted on the agent bridge app
@agent_bridge_app.get("/health")
diff --git a/core/switch_core/migrations/versions/d1a7c3e58b40_add_channel_creation_enabled_to_bridges.py b/core/switch_core/migrations/versions/d1a7c3e58b40_add_channel_creation_enabled_to_bridges.py
new file mode 100644
index 000000000..45dacf33f
--- /dev/null
+++ b/core/switch_core/migrations/versions/d1a7c3e58b40_add_channel_creation_enabled_to_bridges.py
@@ -0,0 +1,40 @@
+"""add channel_creation_enabled to collaboration_bridges
+
+Revision ID: d1a7c3e58b40
+Revises: b3f36489c258
+Create Date: 2026-08-13 00:00:00.000000
+
+"""
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "d1a7c3e58b40"
+down_revision: str | None = "b3f36489c258"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "collaboration_bridges",
+ sa.Column(
+ "channel_creation_enabled",
+ sa.Boolean(),
+ server_default="true",
+ nullable=False,
+ ),
+ )
+ # Existing connections keep the behaviour they had, which was "whatever the
+ # platform allows" — so the operator switch defaults on and the adapter's
+ # own ceiling is what turns it off for a platform that never could.
+ op.execute(
+ "UPDATE collaboration_bridges SET channel_creation_enabled = false "
+ "WHERE type = 'telegram'"
+ )
+
+
+def downgrade() -> None:
+ op.drop_column("collaboration_bridges", "channel_creation_enabled")
diff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.py
index ba4a9f32a..b72edbf1d 100644
--- a/core/switch_core/room_service.py
+++ b/core/switch_core/room_service.py
@@ -8,7 +8,10 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.aliases import validate_alias_map
from switch_core.authz import Principal, can, validate_visibility_pair
-from switch_core.bridges.collaboration.models import ChannelType
+from switch_core.bridges.collaboration.models import (
+ ChannelCreationUnsupported,
+ ChannelType,
+)
from switch_core.bridges.resource.service import ResourceService
from switch_core.clients.client_lifecycle_service import ClientLifecycleService
from switch_core.db.models import Room, RoomGroup, RoomRole
@@ -321,6 +324,26 @@ class RoomService:
)
return default.id
+ async def _require_channel_creation(self, bridge_id: str) -> None:
+ """Refuse to make a channel on a connection an operator has withheld it
+ from, before anything is provisioned.
+
+ Only the operator's switch is checked here. A platform that cannot
+ create channels at all is caught by its own adapter raising, which says
+ so in the platform's terms — naming the bot, the link, the step to take
+ — and that is a better error than anything this layer could compose.
+ """
+ async with self._session_factory() as session:
+ bridge = await self._collab_bridge_store.get(session, bridge_id)
+ if bridge is None or bridge.channel_creation_enabled:
+ return
+ raise ChannelCreationUnsupported(
+ f"Creating channels is turned off for the '{bridge.display_name}' "
+ "connection. Create the channel on the platform and add the Switch "
+ "app to it — Switch adopts it as a room — or ask an administrator to "
+ "allow channel creation for this connection."
+ )
+
async def create_room(self, config: RoomCreateConfig) -> RoomCreateResult:
await self._validate_attachments(config)
# Validate the group up front so a bad id fails before we provision a
@@ -357,6 +380,7 @@ class RoomService:
self._validate_dm_room(config, agent_ids)
if bridge_core and external_channel_id is None:
+ await self._require_channel_creation(bridge_id) # type: ignore[arg-type]
if is_dm:
user_name = (config.user_names or [])[0]
agent_name = (await self._resolve_ids_to_names(agent_ids))[0]
@@ -776,14 +800,10 @@ class RoomService:
bridge_core = self._collab_lifecycle.get(bridge_id)
if external_channel_id is None and bridge_core is not None:
+ await self._require_channel_creation(bridge_id)
external_channel_id = await bridge_core.adapter.create_channel(
room.name, room.description
)
- if external_channel_id is None:
- raise RuntimeError(
- f"Failed to create external channel for room {room_id} "
- f"on bridge {bridge_id}"
- )
async with self._session_factory() as session:
await self._room_store.update_bridge(
@@ -880,6 +900,7 @@ class RoomService:
)
if external_channel_id is None:
+ await self._require_channel_creation(bridge_id)
external_channel_id = await new_bridge.adapter.create_channel(
room.name,
room.description,
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py
new file mode 100644
index 000000000..1e678062f
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py
@@ -0,0 +1,158 @@
+"""A room follows its channel when the platform reissues the channel's id.
+
+Telegram gives a group a brand new chat id the moment it becomes a supergroup,
+which promoting a bot or adding members is enough to trigger. Left alone, the
+room stays bound to an id nothing arrives from again while sends keep working —
+the platform forwards those — so the bridge looks alive and is deaf. These tests
+pin the re-point, and the two cases where it must refuse rather than guess.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+from typing import Any
+
+from switch_core.bridges.collaboration.bridge_core import BridgeCore
+
+OLD_ID = "-4912345678"
+NEW_ID = "-1009876543210"
+
+
+class _Adapter:
+ def __init__(self) -> None:
+ self.notices: list[tuple[str, str]] = []
+
+ async def admin_message(self, channel_id: str, content: str, *a: Any) -> str:
+ self.notices.append((channel_id, content))
+ return f"{channel_id}:1"
+
+
+class _RoomStore:
+ """Rooms keyed by external channel id, and the re-points asked for."""
+
+ def __init__(self, rooms: dict[str, SimpleNamespace]) -> None:
+ self._rooms = rooms
+ self.repoints: list[tuple[str, str]] = []
+
+ async def get_by_external_channel(
+ self, session: Any, bridge_id: str, external_channel_id: str
+ ) -> SimpleNamespace | None:
+ return self._rooms.get(external_channel_id)
+
+ async def update_external_channel(
+ self, session: Any, room_id: str, external_channel_id: str
+ ) -> None:
+ self.repoints.append((room_id, external_channel_id))
+
+
+class _Session:
+ async def commit(self) -> None:
+ return None
+
+ async def __aenter__(self) -> _Session:
+ return self
+
+ async def __aexit__(self, *exc: Any) -> None:
+ return None
+
+
+def _make_bridge(rooms: dict[str, SimpleNamespace]) -> BridgeCore:
+ bridge = BridgeCore.__new__(BridgeCore)
+ bridge._bridge_id = "bridge-1"
+ bridge._channel_locks = {}
+ bridge._channel_to_room = {}
+ bridge._room_to_channel = {}
+ bridge._adapter = _Adapter() # type: ignore[assignment]
+ bridge._room_store = _RoomStore(rooms) # type: ignore[assignment]
+ bridge._session_factory = _Session # type: ignore[assignment]
+ return bridge
+
+
+def _room(room_id: str = "room-uuid") -> SimpleNamespace:
+ return SimpleNamespace(id=room_id, matrix_room_id=f"!{room_id}:switch.local")
+
+
+def test_the_handler_is_installed_before_the_adapter_starts() -> None:
+ # Both halves are tested apart from each other, so without this the line
+ # that connects them could be deleted and every other test would pass —
+ # and the adapter would report a migration into a handler that is None.
+ installed: list[Any] = []
+ started: list[str] = []
+
+ class _Adapter:
+ def set_channel_migration_handler(self, handler: Any) -> None:
+ installed.append(handler)
+
+ async def start(self, **kwargs: Any) -> None:
+ started.append("started")
+ assert installed, "the handler must be installed before start()"
+
+ bridge = _make_bridge({})
+ bridge._adapter = _Adapter() # type: ignore[assignment]
+
+ async def _noop() -> None:
+ return None
+
+ bridge._load_channel_map = _noop # type: ignore[assignment,method-assign]
+ bridge._load_existing_puppets = _noop # type: ignore[assignment,method-assign]
+ bridge._ensure_channel_captures = _noop # type: ignore[assignment,method-assign]
+ bridge._create_agent_identities = _noop # type: ignore[assignment,method-assign]
+
+ asyncio.run(BridgeCore.start(bridge))
+
+ assert started == ["started"]
+ assert installed == [bridge._handle_channel_migrated]
+
+
+def test_the_room_moves_onto_the_new_channel_id() -> None:
+ room = _room()
+ bridge = _make_bridge({OLD_ID: room})
+ bridge._channel_to_room[OLD_ID] = (room.id, room.matrix_room_id)
+ bridge._room_to_channel[(room.id, room.matrix_room_id)] = OLD_ID
+
+ asyncio.run(BridgeCore._handle_channel_migrated(bridge, OLD_ID, NEW_ID))
+
+ store: Any = bridge._room_store
+ assert store.repoints == [(room.id, NEW_ID)]
+ # The in-memory routing table is what inbound traffic is matched against,
+ # so a committed row alone would not fix anything until the next restart.
+ assert bridge._channel_to_room == {NEW_ID: (room.id, room.matrix_room_id)}
+ assert bridge._room_to_channel == {(room.id, room.matrix_room_id): NEW_ID}
+
+
+def test_the_chat_is_told_its_room_followed_it() -> None:
+ room = _room()
+ bridge = _make_bridge({OLD_ID: room})
+
+ asyncio.run(BridgeCore._handle_channel_migrated(bridge, OLD_ID, NEW_ID))
+
+ adapter: Any = bridge._adapter
+ assert [channel for channel, _ in adapter.notices] == [NEW_ID]
+
+
+def test_a_migration_of_an_unbridged_channel_is_a_no_op() -> None:
+ bridge = _make_bridge({})
+
+ asyncio.run(BridgeCore._handle_channel_migrated(bridge, OLD_ID, NEW_ID))
+
+ store: Any = bridge._room_store
+ adapter: Any = bridge._adapter
+ assert store.repoints == []
+ assert adapter.notices == []
+
+
+def test_a_new_id_another_room_already_holds_is_refused() -> None:
+ # The unique index on (bridge, external channel) would reject the update
+ # anyway. Refusing loudly beats leaving two rooms that both look right when
+ # one of them is bound to a dead id.
+ old_room = _room("room-old")
+ occupant = _room("room-new")
+ bridge = _make_bridge({OLD_ID: old_room, NEW_ID: occupant})
+
+ asyncio.run(BridgeCore._handle_channel_migrated(bridge, OLD_ID, NEW_ID))
+
+ store: Any = bridge._room_store
+ adapter: Any = bridge._adapter
+ assert store.repoints == []
+ assert adapter.notices == []
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_no_agents_notice.py b/core/tests/switch_core/bridges/collaboration/test_bridge_no_agents_notice.py
index d7e9dbc38..019ba27f3 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_no_agents_notice.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_no_agents_notice.py
@@ -8,6 +8,10 @@ from switch_core.bridges.collaboration.discord.adapter import (
DiscordAdapter,
DiscordConnectionConfig,
)
+from switch_core.bridges.collaboration.telegram.adapter import (
+ TelegramAdapter,
+ TelegramConnectionConfig,
+)
# When the Switch app is invited to (or addressed in) a bridged channel that has
# no room yet, a room is auto-created even if no agent can be associated with it
@@ -142,6 +146,24 @@ def test_each_adapter_advertises_a_syntax_it_actually_accepts() -> None:
assert "Discord slash command" in hint
assert "@agent-name" not in hint
+ telegram_adapter = TelegramAdapter(
+ config=TelegramConnectionConfig(bot_token="t", bot_username="b")
+ )
+ telegram_hint = telegram_adapter.slash_invite_hint()
+ # Telegram passes a command's whole tail through as text, so the argument is
+ # spelled exactly as in the `!` form — no named fields.
+ assert telegram_hint is not None
+ assert "Telegram slash command" in telegram_hint
+ # The underscore spelling leads, because it is the only one Telegram will
+ # register and therefore the only one its menu offers. Advertising the
+ # hyphenated form first sent people to the one spelling the client will not
+ # autocomplete.
+ assert "`/invite_agent @agent-name`" in telegram_hint
+ assert telegram_hint.index("/invite_agent") < telegram_hint.index("/invite-agent")
+ # Both are still named, since the hyphenated form is what every other
+ # platform and the docs use, and Telegram does accept it when typed.
+ assert "`/invite-agent`" in telegram_hint
+
async def test_auto_create_with_agents_posts_no_notice() -> None:
bridge = _fake_bridge(agent_ids=["a1"])
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_admin_rendering.py b/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_admin_rendering.py
new file mode 100644
index 000000000..5ecacc150
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_admin_rendering.py
@@ -0,0 +1,139 @@
+"""Who renders an admin/system message on its way out of Matrix.
+
+`admin_message` takes Switch Markdown and renders it itself, because most of
+its callers are notices composed in `bridge_core` with no adapter in reach. The
+relay path here has to respect that and pass the body unrendered.
+
+It did not, and the two halves each did the conversion: a `!list-agents` reply
+reached Telegram reading `&lt;b&gt;Agents in this room:&lt;/b&gt;`, because the
+second pass escaped the markup the first one had produced. Nothing covered the
+relay path at the time, so nothing caught it.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+from switch_core.bridges.collaboration.bridge_core import ADMIN_MARKER, BridgeCore
+
+BODY = "**Agents in this room:**\n- **scout** — Claude Code"
+
+
+class _RecordingAdapter:
+ """Records what each send path was handed, and renders like a real adapter.
+
+ `translate_outbound` escapes first, exactly as the HTML-producing adapters
+ do, so a body run through it twice comes back with visible entities — which
+ is what makes the double conversion detectable here rather than merely
+ counted.
+ """
+
+ def __init__(self) -> None:
+ self.admin_calls: list[str] = []
+ self.message_calls: list[str] = []
+
+ def translate_outbound(self, content: str) -> str:
+ escaped = (
+ content.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
+ )
+ out, parts = "", escaped.split("**")
+ for index, part in enumerate(parts):
+ out += part if index % 2 == 0 else f"<b>{part}</b>"
+ return out
+
+ async def admin_message(
+ self,
+ channel_id: str,
+ content: str,
+ thread_root_id: str | None = None,
+ *,
+ message_type: str | None = None,
+ ) -> str | None:
+ self.admin_calls.append(content)
+ return "ref-admin"
+
+ async def send_message(
+ self,
+ channel_id: str,
+ sender_name: str,
+ content: str,
+ thread_root_id: str | None = None,
+ ) -> str | None:
+ self.message_calls.append(content)
+ return "ref-msg"
+
+
+def _bridge(adapter: _RecordingAdapter) -> BridgeCore:
+ core = object.__new__(BridgeCore)
+ core._adapter = adapter # type: ignore[assignment]
+ core._puppet_matrix_ids = set() # type: ignore[assignment]
+ core._bridge_client_matrix_user_id = "@bridge:switch.local" # type: ignore[assignment]
+ core._find_channel = lambda **_kwargs: "C1" # type: ignore[assignment]
+ core._record_message_map = _noop # type: ignore[assignment]
+ core._move_indicator_for_sender = _noop # type: ignore[assignment]
+ core._outbound_thread_root_ref = _none # type: ignore[assignment]
+ return core
+
+
+async def _noop(*_args: Any, **_kwargs: Any) -> None:
+ return None
+
+
+async def _none(*_args: Any, **_kwargs: Any) -> None:
+ return None
+
+
+def _event(*, admin: bool) -> Any:
+ content: dict[str, Any] = {}
+ if admin:
+ content[ADMIN_MARKER] = {"type": "command_result"}
+ else:
+ content["sender_name"] = "scout"
+ return SimpleNamespace(
+ sender="@someone:switch.local",
+ body=BODY,
+ event_id="$e1",
+ source={"content": content},
+ )
+
+
+async def test_an_admin_event_reaches_the_adapter_unrendered() -> None:
+ adapter = _RecordingAdapter()
+
+ await _bridge(adapter).handle_outbound_message(
+ SimpleNamespace(room_id="!r:switch.local"), _event(admin=True)
+ )
+
+ # Handed on as written, for admin_message to render once.
+ assert adapter.admin_calls == [BODY]
+ assert adapter.message_calls == []
+
+
+async def test_an_admin_event_is_not_rendered_twice() -> None:
+ # The failure this file exists for, stated as its symptom: whatever the
+ # adapter renders must not contain escaped tags.
+ adapter = _RecordingAdapter()
+
+ await _bridge(adapter).handle_outbound_message(
+ SimpleNamespace(room_id="!r:switch.local"), _event(admin=True)
+ )
+
+ rendered = adapter.translate_outbound(adapter.admin_calls[0])
+ assert "<b>Agents in this room:</b>" in rendered
+ assert "&lt;b&gt;" not in rendered
+
+
+async def test_an_agent_message_is_still_rendered_by_the_relay() -> None:
+ # The other half of the contract, and the reason this is not simply
+ # "never render in the relay": send_message takes rendered content.
+ adapter = _RecordingAdapter()
+
+ await _bridge(adapter).handle_outbound_message(
+ SimpleNamespace(room_id="!r:switch.local"), _event(admin=False)
+ )
+
+ assert adapter.admin_calls == []
+ assert adapter.message_calls == [
+ "<b>Agents in this room:</b>\n- <b>scout</b> — Claude Code"
+ ]
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py b/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py
index 38745266e..4c3d6308e 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py
@@ -21,6 +21,10 @@ from switch_core.bridges.collaboration.teams.adapter import (
TeamsAdapter,
TeamsConnectionConfig,
)
+from switch_core.bridges.collaboration.telegram.adapter import (
+ TelegramAdapter,
+ TelegramConnectionConfig,
+)
def _service() -> CollaborationBridgeLifecycleService:
@@ -65,6 +69,18 @@ def test_discord_adapter_registers_with_expected_required_fields() -> None:
assert set(schema["required"]) == {"bot_token", "guild_id"}
+def test_telegram_adapter_registers_with_expected_required_fields() -> None:
+ service = _service()
+ service.register_adapter("telegram", TelegramAdapter, TelegramConnectionConfig)
+
+ assert service.get_registered_types() == ["telegram"]
+ schema = service.get_config_schema("telegram")
+ # bot_username is required alongside the token because every t.me link the
+ # bridge hands out is built from it, with no API call to fall back on.
+ assert set(schema["properties"]) == {"bot_token", "bot_username"}
+ assert set(schema["required"]) == {"bot_token", "bot_username"}
+
+
def test_get_config_schema_exposes_required_fields() -> None:
service = _service()
service.register_adapter("slack", SlackAdapter, SlackConnectionConfig)
@@ -81,6 +97,49 @@ def test_get_config_schema_unknown_type_raises() -> None:
service.get_config_schema("does-not-exist")
+# ── Channel-creation capability ──────────────────────────────────────────────
+
+
+def test_only_telegram_cannot_create_channels() -> None:
+ # A platform fact, not a preference. Telegram's Bot API has no call to make
+ # a chat; every other platform Switch bridges to does.
+ assert TelegramAdapter.supports_channel_creation is False
+ for adapter in (SlackAdapter, MattermostAdapter, DiscordAdapter, TeamsAdapter):
+ assert adapter.supports_channel_creation is True
+
+
+def test_capability_is_answerable_without_a_running_bridge() -> None:
+ # Read from the registered class, not a live adapter, because the operator
+ # needs the answer while registering a connection and while one is stopped.
+ service = _service()
+ service.register_adapter("telegram", TelegramAdapter, TelegramConnectionConfig)
+ service.register_adapter("slack", SlackAdapter, SlackConnectionConfig)
+
+ assert service.supports_channel_creation("telegram") is False
+ assert service.supports_channel_creation("slack") is True
+
+
+def test_an_unregistered_type_is_not_reported_as_incapable() -> None:
+ # Registration rejects an unknown type by name, which is a better error than
+ # a capability claim about a platform Switch does not have.
+ assert _service().supports_channel_creation("does-not-exist") is True
+
+
+async def test_registering_telegram_cannot_grant_channel_creation() -> None:
+ # The operator switch only ever narrows the platform's ceiling. Storing
+ # "allowed" here would be a claim the connection could never honour.
+ service = _service()
+ service.register_adapter("telegram", TelegramAdapter, TelegramConnectionConfig)
+
+ with pytest.raises(ValueError, match="cannot create channels"):
+ await service.register(
+ bridge_type="telegram",
+ display_name="Acme Telegram",
+ connection_config={"bot_token": "t", "bot_username": "b"},
+ channel_creation_enabled=True,
+ )
+
+
def test_teams_adapter_registers_with_expected_required_fields() -> None:
service = _service()
service.register_adapter("teams", TeamsAdapter, TeamsConnectionConfig)
diff --git a/core/tests/switch_core/bridges/collaboration/test_home_deeplinks.py b/core/tests/switch_core/bridges/collaboration/test_home_deeplinks.py
index 94fe16901..ae9b9e9fb 100644
--- a/core/tests/switch_core/bridges/collaboration/test_home_deeplinks.py
+++ b/core/tests/switch_core/bridges/collaboration/test_home_deeplinks.py
@@ -32,6 +32,10 @@ from switch_core.bridges.collaboration.teams.adapter import (
TeamsAdapter,
TeamsConnectionConfig,
)
+from switch_core.bridges.collaboration.telegram.adapter import (
+ TelegramAdapter,
+ TelegramConnectionConfig,
+)
BOT_TOKEN = "xoxb-do-not-leak-this"
ADMIN_PASSWORD = "do-not-leak-this-either"
@@ -83,6 +87,12 @@ def _teams() -> TeamsAdapter:
)
+def _telegram() -> TelegramAdapter:
+ return TelegramAdapter(
+ config=TelegramConnectionConfig(bot_token=BOT_TOKEN, bot_username="@acme_bot")
+ )
+
+
def test_slack_home_opens_the_workspace() -> None:
assert _run(_slack().home_deeplink()) == "slack://open?team=T0ABCDEF"
@@ -100,6 +110,12 @@ def test_teams_home_opens_the_tenant() -> None:
)
+def test_telegram_home_opens_the_bot_chat() -> None:
+ # Telegram has no workspace; the bot's own chat is the nearest equivalent.
+ # The configured username is normalised, so a leading @ does not double up.
+ assert _run(_telegram().home_deeplink()) == "https://t.me/acme_bot"
+
+
def test_mattermost_home_opens_the_team() -> None:
assert _run(_mattermost().home_deeplink()) == "mattermost://mattermost:8065/switch"
@@ -119,9 +135,32 @@ def test_base_adapter_offers_no_home_link() -> None:
def test_no_home_link_carries_a_credential() -> None:
- for adapter in (_slack(), _discord(), _mattermost(), _teams()):
+ for adapter in (_slack(), _discord(), _mattermost(), _teams(), _telegram()):
link = _run(adapter.home_deeplink())
assert link is not None
assert BOT_TOKEN not in link
assert ADMIN_PASSWORD not in link
assert "xapp-" not in link
+
+
+def test_base_adapter_offers_no_install_link() -> None:
+ # Most platforms install their app through their own admin UI, and a link
+ # invented for them would be a link to nowhere.
+ assert _run(CollaborationAdapter.install_links(object())) == [] # type: ignore[arg-type]
+
+
+def test_no_install_link_carries_a_credential() -> None:
+ # Same exposure as a home link: built from a config that also holds bot
+ # tokens, and served by `GET /gateway/collaborations` — then handed to the
+ # operator's browser and on to the platform.
+ for adapter in (_slack(), _discord(), _mattermost(), _teams(), _telegram()):
+ for link in _run(adapter.install_links()):
+ assert BOT_TOKEN not in link.url
+ assert ADMIN_PASSWORD not in link.url
+ assert "xapp-" not in link.url
+
+
+def test_base_adapter_offers_no_install_note() -> None:
+ # Most platforms have nothing to add beyond their links, and an empty
+ # panel in the dialog would be worse than none.
+ assert _run(CollaborationAdapter.install_note(object())) is None # type: ignore[arg-type]
diff --git a/core/tests/switch_core/bridges/collaboration/test_telegram_adapter.py b/core/tests/switch_core/bridges/collaboration/test_telegram_adapter.py
new file mode 100644
index 000000000..4cfdccf29
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_telegram_adapter.py
@@ -0,0 +1,2494 @@
+from __future__ import annotations
+
+import asyncio
+import logging
+from typing import Any
+from unittest.mock import patch
+
+import pytest
+from telegram.error import BadRequest, Conflict, TelegramError
+
+from switch_core.bridges.collaboration.models import (
+ InboundCommand,
+ InboundMessage,
+ OutboundAttachment,
+)
+from switch_core.bridges.collaboration.telegram import adapter as adapter_module
+from switch_core.bridges.collaboration.telegram.adapter import (
+ _INSTALL_PAYLOAD,
+ TelegramAdapter,
+ TelegramConnectionConfig,
+)
+
+CHAT_ID = -1001234567890
+BOT_USER_ID = 42
+BOT_USERNAME = "acme_switch_bot"
+
+# The mark "scout" hashes to. Written out rather than computed, so a change to
+# the palette or the hash shows up here as a diff instead of passing silently —
+# an agent's mark changing is a visible change to everyone reading the chat.
+SCOUT_MARK = "🟡"
+
+
+def _run(coro: Any) -> Any:
+ loop = asyncio.new_event_loop()
+ try:
+ return loop.run_until_complete(coro)
+ finally:
+ loop.close()
+
+
+class _FakeChat:
+ def __init__(
+ self,
+ chat_id: int = CHAT_ID,
+ *,
+ chat_type: str = "supergroup",
+ title: str | None = "general",
+ username: str | None = None,
+ ) -> None:
+ self.id = chat_id
+ self.type = chat_type
+ self.title = title
+ self.username = username
+
+
+class _FakeUser:
+ def __init__(
+ self,
+ user_id: int = 7,
+ *,
+ username: str | None = "alice",
+ first_name: str = "Alice",
+ last_name: str = "",
+ ) -> None:
+ self.id = user_id
+ self.username = username
+ self.first_name = first_name
+ self.last_name = last_name
+
+
+class _FakeSentMessage:
+ def __init__(self, chat: _FakeChat, message_id: int) -> None:
+ self.chat = chat
+ self.message_id = message_id
+
+
+class _FakeFileHandle:
+ def __init__(self, data: bytes, *, fail: bool = False) -> None:
+ self._data = data
+ self._fail = fail
+
+ async def download_as_bytearray(self) -> bytearray:
+ if self._fail:
+ raise TelegramError("file is gone")
+ return bytearray(self._data)
+
+
+class _FakePhotoSize:
+ def __init__(self, file_id: str, unique: str, size: int) -> None:
+ self.file_id = file_id
+ self.file_unique_id = unique
+ self.file_size = size
+
+
+class _FakeDocument:
+ def __init__(
+ self, file_id: str, name: str, mime: str | None, size: int | None
+ ) -> None:
+ self.file_id = file_id
+ self.file_name = name
+ self.mime_type = mime
+ self.file_size = size
+
+
+class _FakeInbound:
+ """An inbound Telegram message. Only the fields the adapter reads."""
+
+ def __init__(
+ self,
+ *,
+ chat: _FakeChat | None = None,
+ message_id: int = 11,
+ text: str | None = "hello",
+ caption: str | None = None,
+ from_user: Any = "default",
+ reply_to_message: Any = None,
+ message_thread_id: int | None = None,
+ new_chat_members: list[Any] | None = None,
+ photo: list[Any] | None = None,
+ document: Any = None,
+ **service: Any,
+ ) -> None:
+ self.chat = chat if chat is not None else _FakeChat()
+ self.message_id = message_id
+ self.text = text
+ self.caption = caption
+ self.from_user = _FakeUser() if from_user == "default" else from_user
+ self.reply_to_message = reply_to_message
+ self.message_thread_id = message_thread_id
+ self.new_chat_members = new_chat_members
+ self.photo = photo
+ self.document = document
+ # Service-message and other-media fields, set only when a test needs one.
+ for field, value in service.items():
+ setattr(self, field, value)
+
+
+class _FakeMember:
+ def __init__(self, status: str) -> None:
+ self.status = status
+
+
+class _FakeBot:
+ def __init__(self) -> None:
+ self.messages: list[dict[str, Any]] = []
+ self.photos: list[dict[str, Any]] = []
+ self.documents: list[dict[str, Any]] = []
+ self.albums: list[dict[str, Any]] = []
+ self.edits: list[dict[str, Any]] = []
+ self.deletes: list[dict[str, Any]] = []
+ self.actions: list[dict[str, Any]] = []
+ self.files: dict[str, _FakeFileHandle] = {}
+ self.published_commands: list[Any] = []
+ self.chat: _FakeChat = _FakeChat()
+ # What getChatMember reports for the bot itself in `chat`.
+ self.member_status = "administrator"
+ self.get_chat_member_error: Exception | None = None
+ self._next_id = 500
+ # Set to an exception to make the next send_message raise it once.
+ self.send_message_error: Exception | None = None
+ self.send_photo_error: Exception | None = None
+ self.send_album_error: Exception | None = None
+
+ def _mint(self, chat_id: Any) -> _FakeSentMessage:
+ self._next_id += 1
+ return _FakeSentMessage(_FakeChat(int(chat_id)), self._next_id)
+
+ async def send_message(self, **kwargs: Any) -> _FakeSentMessage:
+ if self.send_message_error is not None:
+ error = self.send_message_error
+ self.send_message_error = None
+ raise error
+ self.messages.append(kwargs)
+ return self._mint(kwargs["chat_id"])
+
+ async def send_photo(self, **kwargs: Any) -> _FakeSentMessage:
+ if self.send_photo_error is not None:
+ error = self.send_photo_error
+ self.send_photo_error = None
+ raise error
+ self.photos.append(kwargs)
+ return self._mint(kwargs["chat_id"])
+
+ async def send_document(self, **kwargs: Any) -> _FakeSentMessage:
+ self.documents.append(kwargs)
+ return self._mint(kwargs["chat_id"])
+
+ async def send_media_group(self, **kwargs: Any) -> list[_FakeSentMessage]:
+ if self.send_album_error is not None:
+ error = self.send_album_error
+ self.send_album_error = None
+ raise error
+ self.albums.append(kwargs)
+ return [self._mint(kwargs["chat_id"]) for _ in kwargs["media"]]
+
+ async def edit_message_text(self, **kwargs: Any) -> None:
+ self.edits.append(kwargs)
+
+ async def delete_message(self, **kwargs: Any) -> None:
+ self.deletes.append(kwargs)
+
+ async def send_chat_action(self, **kwargs: Any) -> None:
+ self.actions.append(kwargs)
+
+ async def set_my_commands(self, commands: Any) -> None:
+ self.published_commands = list(commands)
+
+ async def get_chat(self, chat_id: Any) -> _FakeChat:
+ return self.chat
+
+ async def get_chat_member(self, **kwargs: Any) -> _FakeMember:
+ if self.get_chat_member_error is not None:
+ raise self.get_chat_member_error
+ return _FakeMember(self.member_status)
+
+ async def get_file(self, file_id: str) -> _FakeFileHandle:
+ handle = self.files.get(file_id)
+ if handle is None:
+ raise TelegramError(f"no such file {file_id}")
+ return handle
+
+
+def _adapter() -> TelegramAdapter:
+ adapter = TelegramAdapter(
+ config=TelegramConnectionConfig(bot_token="token", bot_username=BOT_USERNAME)
+ )
+ adapter._bot_user_id = BOT_USER_ID
+ adapter._bot = _FakeBot()
+ return adapter
+
+
+def _bot(adapter: TelegramAdapter) -> _FakeBot:
+ return adapter._bot # type: ignore[no-any-return]
+
+
+# ── Inbound bridging ─────────────────────────────────────────────────────────
+
+
+async def _collect(sink: list[Any], value: Any) -> None:
+ sink.append(value)
+
+
+def test_inbound_message_is_bridged_with_chat_and_sender() -> None:
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+
+ _run(adapter._handle_message(_FakeInbound(text="hello team")))
+
+ assert len(seen) == 1
+ assert seen[0].channel_id == str(CHAT_ID)
+ assert seen[0].channel_type == "channel_private"
+ assert seen[0].sender_name == "alice"
+ assert seen[0].content == "hello team"
+ assert seen[0].message_ref == f"{CHAT_ID}:11"
+ assert seen[0].channel_name == "general"
+
+
+def test_the_bots_own_messages_are_dropped() -> None:
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+
+ _run(
+ adapter._handle_message(
+ _FakeInbound(from_user=_FakeUser(user_id=BOT_USER_ID, username="the_bot"))
+ )
+ )
+
+ assert seen == []
+
+
+def test_a_repeated_message_id_is_only_bridged_once() -> None:
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+
+ _run(adapter._handle_message(_FakeInbound(message_id=11)))
+ _run(adapter._handle_message(_FakeInbound(message_id=11)))
+
+ assert len(seen) == 1
+
+
+def test_the_same_message_id_in_another_chat_is_not_a_duplicate() -> None:
+ # Telegram numbers messages per chat, so the id alone cannot dedupe.
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+
+ _run(adapter._handle_message(_FakeInbound(message_id=11)))
+ _run(
+ adapter._handle_message(
+ _FakeInbound(message_id=11, chat=_FakeChat(chat_id=-100999))
+ )
+ )
+
+ assert len(seen) == 2
+
+
+def test_a_caption_stands_in_for_text_on_a_media_message() -> None:
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+ photo = _FakePhotoSize("small", "u1", 10)
+ _bot(adapter).files["small"] = _FakeFileHandle(b"img")
+
+ _run(
+ adapter._handle_message(
+ _FakeInbound(text=None, caption="look at this", photo=[photo])
+ )
+ )
+
+ assert seen[0].content == "look at this"
+
+
+def test_a_bang_prefixed_message_routes_as_a_command() -> None:
+ adapter = _adapter()
+ commands: list[InboundCommand] = []
+ messages: list[InboundMessage] = []
+ adapter._on_command = lambda c: _collect(commands, c)
+ adapter._on_message = lambda m: _collect(messages, m)
+
+ _run(adapter._handle_message(_FakeInbound(text="!invite-agent @scout")))
+
+ assert messages == []
+ assert commands[0].command == "invite-agent"
+ assert commands[0].args == "@scout"
+ assert commands[0].message_ref == f"{CHAT_ID}:11"
+
+
+def test_a_slash_prefixed_message_routes_as_a_command() -> None:
+ # `/name` is Telegram's native command convention — the client renders it
+ # as a tappable link — and with privacy mode left on it is the only text a
+ # bot reliably receives in a group. It has to reach the same dispatcher as
+ # `!name` or the documented commands simply do nothing (CHOO-1686).
+ adapter = _adapter()
+ commands: list[InboundCommand] = []
+ messages: list[InboundMessage] = []
+ adapter._on_command = lambda c: _collect(commands, c)
+ adapter._on_message = lambda m: _collect(messages, m)
+
+ _run(adapter._handle_message(_FakeInbound(text="/invite-agent @scout")))
+
+ assert messages == []
+ assert commands[0].command == "invite-agent"
+ assert commands[0].args == "@scout"
+
+
+def test_a_command_addressed_to_the_bot_drops_the_bot_name() -> None:
+ # Telegram appends @botname when the command is picked from autocomplete
+ # in a group; the dispatcher must still see the bare command.
+ adapter = _adapter()
+ commands: list[InboundCommand] = []
+ adapter._on_command = lambda c: _collect(commands, c)
+
+ _run(
+ adapter._handle_message(
+ _FakeInbound(text=f"/invite-agent@{BOT_USERNAME} @scout")
+ )
+ )
+
+ assert commands[0].command == "invite-agent"
+ assert commands[0].args == "@scout"
+
+
+def test_a_bare_command_has_no_arguments() -> None:
+ adapter = _adapter()
+ commands: list[InboundCommand] = []
+ adapter._on_command = lambda c: _collect(commands, c)
+
+ _run(adapter._handle_message(_FakeInbound(text="/list-agents")))
+
+ assert commands[0].command == "list-agents"
+ assert commands[0].args == ""
+
+
[email protected]("text", ["/", "!", "/ spaced", "hello /not-a-command"])
+def test_text_that_only_looks_like_a_command_is_bridged_as_a_message(text: str) -> None:
+ adapter = _adapter()
+ commands: list[InboundCommand] = []
+ messages: list[InboundMessage] = []
+ adapter._on_command = lambda c: _collect(commands, c)
+ adapter._on_message = lambda m: _collect(messages, m)
+
+ _run(adapter._handle_message(_FakeInbound(text=text)))
+
+ assert commands == []
+ assert len(messages) == 1
+
+
+def test_tagging_the_bot_itself_is_reported() -> None:
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+
+ _run(adapter._handle_message(_FakeInbound(text=f"hey @{BOT_USERNAME} help")))
+
+ assert seen[0].self_mention_token == BOT_USERNAME
+
+
+def test_a_message_naming_no_one_has_no_self_mention() -> None:
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+
+ _run(adapter._handle_message(_FakeInbound(text="hey @someone_else")))
+
+ assert seen[0].self_mention_token is None
+
+
+def test_a_channel_post_with_no_author_is_skipped() -> None:
+ # Broadcast channel posts are authored by the channel, so there is no
+ # sender to attribute them to.
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+
+ _run(adapter._handle_message(_FakeInbound(from_user=None)))
+
+ assert seen == []
+
+
+# ── Threading ────────────────────────────────────────────────────────────────
+
+
+def test_a_forum_topic_id_is_the_thread_root() -> None:
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+
+ _run(adapter._handle_message(_FakeInbound(message_thread_id=88)))
+
+ assert seen[0].root_id == "88"
+
+
+def test_outside_a_forum_the_replied_to_message_is_the_root() -> None:
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+
+ _run(
+ adapter._handle_message(
+ _FakeInbound(reply_to_message=_FakeInbound(message_id=5))
+ )
+ )
+
+ assert seen[0].root_id == "5"
+
+
+def test_a_top_level_message_has_no_root() -> None:
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+
+ _run(adapter._handle_message(_FakeInbound()))
+
+ assert seen[0].root_id is None
+
+
+# ── Joins ────────────────────────────────────────────────────────────────────
+
+
+def test_a_group_becoming_a_supergroup_re_points_the_room() -> None:
+ # Telegram reissues the chat id on upgrade. Left alone, the room stays bound
+ # to the old one and inbound silently stops matching while outbound keeps
+ # working — Telegram forwards sends to the old id. So the room follows.
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+ moves: list[tuple[str, str]] = []
+ adapter.set_channel_migration_handler(lambda old, new: _collect(moves, (old, new)))
+ notice = _FakeInbound(text=None)
+ notice.migrate_to_chat_id = -1009876543210 # type: ignore[attr-defined]
+
+ _run(adapter._handle_message(notice))
+
+ assert moves == [(str(CHAT_ID), "-1009876543210")]
+ # The notice itself is not conversation.
+ assert seen == []
+
+
+def test_the_replacement_supergroup_re_points_the_room_it_replaced() -> None:
+ # The same change announced from the other side: Telegram puts
+ # migrate_from_chat_id on the first message of the new chat. Either is
+ # enough, and whichever arrives first does the work.
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+ moves: list[tuple[str, str]] = []
+ adapter.set_channel_migration_handler(lambda old, new: _collect(moves, (old, new)))
+ notice = _FakeInbound(text=None)
+ notice.migrate_from_chat_id = -4912345678 # type: ignore[attr-defined]
+
+ _run(adapter._handle_message(notice))
+
+ assert moves == [("-4912345678", str(CHAT_ID))]
+ assert seen == []
+
+
+def test_a_migration_with_nothing_installed_to_follow_it_is_reported(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ # Degraded, not silent: without a handler the room cannot be moved, so the
+ # log has to carry the id to re-point it at by hand.
+ adapter = _adapter()
+ notice = _FakeInbound(text=None)
+ notice.migrate_to_chat_id = -1009876543210 # type: ignore[attr-defined]
+
+ with caplog.at_level(logging.ERROR):
+ _run(adapter._handle_message(notice))
+
+ assert "-1009876543210" in caplog.text
+ assert "re-point" in caplog.text.lower()
+
+
+def test_an_ordinary_message_is_not_mistaken_for_a_migration() -> None:
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+
+ _run(adapter._handle_message(_FakeInbound(text="just talking")))
+
+ assert len(seen) == 1
+
+
+def test_a_person_joining_is_reported_as_a_user_join() -> None:
+ adapter = _adapter()
+ joins: list[Any] = []
+ adapter._on_user_joined = lambda j: _collect(joins, j)
+
+ _run(
+ adapter._handle_message(
+ _FakeInbound(new_chat_members=[_FakeUser(user_id=9, username="bob")])
+ )
+ )
+
+ assert joins[0].external_user_id == "9"
+ assert joins[0].external_username == "bob"
+ assert joins[0].channel_id == str(CHAT_ID)
+
+
+def test_the_bot_being_added_provisions_the_room() -> None:
+ # Telegram gives the "app added to channel" signal Discord lacks, so the
+ # room can be created on join rather than waiting for a message.
+ adapter = _adapter()
+ app_joins: list[Any] = []
+ adapter._on_app_joined = lambda j: _collect(app_joins, j)
+
+ _run(
+ adapter._handle_message(
+ _FakeInbound(new_chat_members=[_FakeUser(user_id=BOT_USER_ID)])
+ )
+ )
+
+ assert app_joins[0].channel_id == str(CHAT_ID)
+ assert app_joins[0].channel_name == "general"
+
+
+def test_a_membership_update_for_the_bot_provisions_the_room() -> None:
+ adapter = _adapter()
+ app_joins: list[Any] = []
+ adapter._on_app_joined = lambda j: _collect(app_joins, j)
+
+ _run(
+ adapter._handle_update(
+ _FakeUpdate(
+ my_chat_member=_FakeChatMemberUpdate(
+ _FakeChat(), status="administrator"
+ )
+ )
+ )
+ )
+
+ assert app_joins[0].channel_id == str(CHAT_ID)
+
+
+def test_the_bot_being_removed_provisions_nothing() -> None:
+ adapter = _adapter()
+ app_joins: list[Any] = []
+ adapter._on_app_joined = lambda j: _collect(app_joins, j)
+
+ _run(
+ adapter._handle_update(
+ _FakeUpdate(
+ my_chat_member=_FakeChatMemberUpdate(_FakeChat(), status="left")
+ )
+ )
+ )
+
+ assert app_joins == []
+
+
+def test_a_one_to_one_chat_does_not_provision_a_room_on_join() -> None:
+ adapter = _adapter()
+ app_joins: list[Any] = []
+ adapter._on_app_joined = lambda j: _collect(app_joins, j)
+
+ _run(
+ adapter._handle_update(
+ _FakeUpdate(
+ my_chat_member=_FakeChatMemberUpdate(
+ _FakeChat(chat_type="private"), status="member"
+ )
+ )
+ )
+ )
+
+ assert app_joins == []
+
+
+class _FakeChatMemberUpdate:
+ def __init__(self, chat: _FakeChat, *, status: str) -> None:
+ self.chat = chat
+ self.new_chat_member = type("_M", (), {"status": status})()
+
+
+class _FakeUpdate:
+ def __init__(self, *, message: Any = None, my_chat_member: Any = None) -> None:
+ self.message = message
+ self.channel_post = None
+ self.my_chat_member = my_chat_member
+
+
+# ── Sender names ─────────────────────────────────────────────────────────────
+
+
+def test_a_person_without_a_username_is_named_from_their_display_name() -> None:
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+
+ _run(
+ adapter._handle_message(
+ _FakeInbound(
+ from_user=_FakeUser(
+ user_id=9, username=None, first_name="Ada", last_name="Lovelace"
+ )
+ )
+ )
+ )
+
+ # It has to survive being written as @name in a room, so no spaces — and it
+ # carries the numeric id, because display names are not unique and two
+ # people sharing a handle would share a room identity.
+ assert seen[0].sender_name == "AdaLovelace_9"
+
+
+def test_a_person_with_no_name_at_all_falls_back_to_their_id() -> None:
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+
+ _run(
+ adapter._handle_message(
+ _FakeInbound(
+ from_user=_FakeUser(
+ user_id=9, username=None, first_name="", last_name=""
+ )
+ )
+ )
+ )
+
+ assert seen[0].sender_name == "user9"
+
+
+# ── Inbound attachments ──────────────────────────────────────────────────────
+
+
+def test_the_largest_size_of_a_photo_is_the_one_relayed() -> None:
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+ bot = _bot(adapter)
+ bot.files["big"] = _FakeFileHandle(b"full-size")
+
+ _run(
+ adapter._handle_message(
+ _FakeInbound(
+ text=None,
+ photo=[
+ _FakePhotoSize("small", "u1", 10),
+ _FakePhotoSize("big", "u2", 900),
+ ],
+ )
+ )
+ )
+
+ assert [a.filename for a in seen[0].attachments] == ["photo_u2.jpg"]
+ assert seen[0].attachments[0].mimetype == "image/jpeg"
+ assert seen[0].attachments[0].data == b"full-size"
+
+
+def test_a_document_keeps_its_name_and_type() -> None:
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+ _bot(adapter).files["d1"] = _FakeFileHandle(b"col1,col2")
+
+ _run(
+ adapter._handle_message(
+ _FakeInbound(
+ text=None, document=_FakeDocument("d1", "report.csv", "text/csv", 9)
+ )
+ )
+ )
+
+ assert seen[0].attachments[0].filename == "report.csv"
+ assert seen[0].attachments[0].mimetype == "text/csv"
+
+
+def test_an_oversize_attachment_is_disclosed_not_dropped() -> None:
+ adapter = _adapter()
+ adapter.set_max_attachment_bytes(100)
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+
+ _run(
+ adapter._handle_message(
+ _FakeInbound(
+ text=None,
+ document=_FakeDocument(
+ "d1", "huge.bin", "application/octet-stream", 5000
+ ),
+ )
+ )
+ )
+
+ assert seen[0].attachments == []
+ assert seen[0].attachment_failures[0].filename == "huge.bin"
+ assert "exceeds" in seen[0].attachment_failures[0].reason
+
+
+def test_the_bot_api_download_ceiling_applies_even_when_the_bridge_allows_more() -> (
+ None
+):
+ adapter = _adapter()
+ adapter.set_max_attachment_bytes(200 * 1024 * 1024)
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+
+ _run(
+ adapter._handle_message(
+ _FakeInbound(
+ text=None,
+ document=_FakeDocument("d1", "huge.bin", None, 50 * 1024 * 1024),
+ )
+ )
+ )
+
+ assert seen[0].attachments == []
+ assert seen[0].attachment_failures[0].filename == "huge.bin"
+
+
+def test_a_failed_download_is_disclosed_not_dropped() -> None:
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+ _bot(adapter).files["d1"] = _FakeFileHandle(b"", fail=True)
+
+ _run(
+ adapter._handle_message(
+ _FakeInbound(text=None, document=_FakeDocument("d1", "x.bin", None, 4))
+ )
+ )
+
+ assert seen[0].attachments == []
+ assert "download failed" in seen[0].attachment_failures[0].reason
+
+
+# ── Outbound messaging ───────────────────────────────────────────────────────
+
+
+def test_an_agents_name_leads_a_single_line_message() -> None:
+ adapter = _adapter()
+
+ ref = _run(adapter.send_message(str(CHAT_ID), "scout", "on it"))
+
+ sent = _bot(adapter).messages[0]
+ assert sent["text"] == f"{SCOUT_MARK} <b>scout</b>: on it"
+ assert sent["chat_id"] == CHAT_ID
+ assert ref == f"{CHAT_ID}:501"
+
+
+def test_an_agents_name_sits_above_a_multi_line_message() -> None:
+ adapter = _adapter()
+
+ _run(adapter.send_message(str(CHAT_ID), "scout", "line one\nline two"))
+
+ assert (
+ _bot(adapter).messages[0]["text"]
+ == f"{SCOUT_MARK} <b>scout</b>\nline one\nline two"
+ )
+
+
+def test_a_threaded_reply_is_anchored_to_its_root() -> None:
+ adapter = _adapter()
+
+ _run(adapter.send_message(str(CHAT_ID), "scout", "in thread", "88"))
+
+ params = _bot(adapter).messages[0]["reply_parameters"]
+ assert params.message_id == 88
+ # A root that has since been deleted must not take the message down with it.
+ assert params.allow_sending_without_reply is True
+
+
+def test_a_body_over_the_cap_is_split_rather_than_rejected() -> None:
+ adapter = _adapter()
+ body = "\n".join(["x" * 200] * 60)
+
+ ref = _run(adapter.send_message(str(CHAT_ID), "scout", body))
+
+ sent = _bot(adapter).messages
+ assert len(sent) > 1
+ assert all(len(m["text"]) <= 4096 for m in sent)
+ # The ref names the head of the run, so an edit or delete finds it.
+ assert ref == f"{CHAT_ID}:501"
+
+
+def test_only_the_first_chunk_replies_into_the_thread() -> None:
+ # Every chunk carrying reply_parameters would make Telegram render the
+ # quoted root once per message.
+ adapter = _adapter()
+ body = "\n".join(["x" * 200] * 60)
+
+ _run(adapter.send_message(str(CHAT_ID), "scout", body, "88"))
+
+ sent = _bot(adapter).messages
+ assert "reply_parameters" in sent[0]
+ assert all("reply_parameters" not in m for m in sent[1:])
+
+
+def test_markup_telegram_rejects_is_resent_as_plain_text() -> None:
+ # Losing the message is the one outcome that is not acceptable.
+ adapter = _adapter()
+ _bot(adapter).send_message_error = BadRequest("Can't parse entities: bad tag")
+
+ ref = _run(adapter.send_message(str(CHAT_ID), "scout", "<b>oops</unclosed>"))
+
+ sent = _bot(adapter).messages
+ assert len(sent) == 1
+ assert "parse_mode" not in sent[0]
+ assert "<" not in sent[0]["text"]
+ assert ref is not None
+
+
+def test_any_rejection_is_retried_unformatted_rather_than_dropped() -> None:
+ # The retry used to be conditioned on the word "parse" appearing in
+ # Telegram's error. It refuses markup under other wordings too — an
+ # unsupported URL protocol in a link is one, and says nothing about parsing
+ # — and those lost the entire message to a single log line. One extra call
+ # in the cases that were failing anyway is the cheaper mistake.
+ adapter = _adapter()
+ _bot(adapter).send_message_error = BadRequest("unsupported URL protocol")
+
+ ref = _run(adapter.send_message(str(CHAT_ID), "scout", "hello"))
+
+ sent = _bot(adapter).messages
+ assert len(sent) == 1
+ assert "parse_mode" not in sent[0]
+ assert ref is not None
+
+
+def test_a_rejection_that_survives_the_retry_gives_up_and_says_so(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ adapter = _adapter()
+ bot = _bot(adapter)
+
+ async def always_refuse(**_kwargs: Any) -> Any:
+ raise BadRequest("chat not found")
+
+ bot.send_message = always_refuse # type: ignore[method-assign]
+
+ with caplog.at_level(logging.ERROR):
+ ref = _run(adapter.send_message(str(CHAT_ID), "scout", "hello"))
+
+ assert ref is None
+ # A message that could not be delivered at all is an error in the log, not
+ # a silent return.
+ assert any("chat not found" in r.getMessage() for r in caplog.records)
+
+
+def test_an_admin_notice_carries_no_agent_name() -> None:
+ adapter = _adapter()
+
+ _run(adapter.admin_message(str(CHAT_ID), "scout is not in this room"))
+
+ assert _bot(adapter).messages[0]["text"] == "scout is not in this room"
+
+
+def test_an_admin_notice_is_converted_from_markdown_like_any_other_body() -> None:
+ # These notices are written in Switch Markdown, same as an agent's message,
+ # and go out with parse_mode HTML. Skipping the conversion put the raw `**`
+ # and backticks in front of whoever had just added the bot.
+ adapter = _adapter()
+
+ _run(
+ adapter.admin_message(
+ str(CHAT_ID), "**To add an agent**, type `!invite-agent @name`"
+ )
+ )
+
+ text = _bot(adapter).messages[0]["text"]
+ assert text == ("<b>To add an agent</b>, type <code>!invite-agent @name</code>")
+ assert "**" not in text
+ assert "`" not in text
+
+
+def test_two_agents_get_different_marks_and_keep_them() -> None:
+ # Telegram gives a bot no per-message avatar, so a stable mark is the only
+ # thing a reader can learn to recognise. It must not move between restarts,
+ # which rules out the salted built-in hash.
+ first = TelegramAdapter._attribute("scout", "hello")
+ second = TelegramAdapter._attribute("ranger", "hello")
+
+ assert first.split()[0] != second.split()[0]
+ assert TelegramAdapter._attribute("scout", "again").startswith(first.split()[0])
+
+
+def test_editing_a_message_targets_its_chat_and_id() -> None:
+ adapter = _adapter()
+
+ _run(adapter.update_message(str(CHAT_ID), f"{CHAT_ID}:501", "new text"))
+
+ edit = _bot(adapter).edits[0]
+ assert edit["chat_id"] == CHAT_ID
+ assert edit["message_id"] == 501
+ assert edit["text"] == "new text"
+
+
+def test_an_edit_that_changes_nothing_is_not_an_error() -> None:
+ adapter = _adapter()
+
+ async def _raise(**_kwargs: Any) -> None:
+ raise BadRequest("Message is not modified")
+
+ _bot(adapter).edit_message_text = _raise # type: ignore[method-assign]
+
+ # Must not raise.
+ _run(adapter.update_message(str(CHAT_ID), f"{CHAT_ID}:501", "same"))
+
+
+def test_deleting_a_message_targets_its_chat_and_id() -> None:
+ adapter = _adapter()
+
+ _run(adapter.delete_message(str(CHAT_ID), f"{CHAT_ID}:501"))
+
+ assert _bot(adapter).deletes[0] == {"chat_id": CHAT_ID, "message_id": 501}
+
+
+def test_a_malformed_message_ref_is_refused_rather_than_guessed() -> None:
+ adapter = _adapter()
+
+ _run(adapter.delete_message(str(CHAT_ID), "nonsense"))
+
+ assert _bot(adapter).deletes == []
+
+
+# ── Typing ───────────────────────────────────────────────────────────────────
+
+
+def test_typing_on_sends_a_chat_action() -> None:
+ adapter = _adapter()
+
+ _run(adapter.send_typing(str(CHAT_ID), "scout", True))
+
+ assert _bot(adapter).actions[0]["chat_id"] == CHAT_ID
+
+
+def test_typing_off_sends_nothing() -> None:
+ # Telegram's chat action expires on its own; there is no cancel call.
+ adapter = _adapter()
+
+ _run(adapter.send_typing(str(CHAT_ID), "scout", False))
+
+ assert _bot(adapter).actions == []
+
+
+# ── Outbound attachments ─────────────────────────────────────────────────────
+
+
+def test_an_image_is_sent_as_a_photo_so_it_previews() -> None:
+ adapter = _adapter()
+
+ _run(
+ adapter.send_attachment(
+ str(CHAT_ID), "scout", "chart.png", "image/png", b"bytes", "the chart"
+ )
+ )
+
+ assert _bot(adapter).documents == []
+ assert _bot(adapter).photos[0]["caption"] == f"{SCOUT_MARK} <b>scout</b>: the chart"
+
+
+def test_a_non_image_is_sent_as_a_document_so_its_bytes_survive() -> None:
+ adapter = _adapter()
+
+ _run(
+ adapter.send_attachment(
+ str(CHAT_ID), "scout", "report.csv", "text/csv", b"a,b", None
+ )
+ )
+
+ doc = _bot(adapter).documents[0]
+ assert doc["filename"] == "report.csv"
+ assert doc["caption"] == f"{SCOUT_MARK} <b>scout</b>"
+
+
+def test_an_image_too_big_to_preview_is_sent_as_a_document() -> None:
+ adapter = _adapter()
+
+ _run(
+ adapter.send_attachment(
+ str(CHAT_ID), "scout", "huge.png", "image/png", b"x" * (11 * 1024 * 1024)
+ )
+ )
+
+ assert _bot(adapter).photos == []
+ assert _bot(adapter).documents[0]["filename"] == "huge.png"
+
+
+def test_a_caption_too_long_for_a_file_posts_ahead_of_it() -> None:
+ adapter = _adapter()
+
+ _run(
+ adapter.send_attachment(
+ str(CHAT_ID), "scout", "x.bin", "application/octet-stream", b"x", "c" * 2000
+ )
+ )
+
+ assert len(_bot(adapter).messages) == 1
+ assert _bot(adapter).documents[0]["caption"] is None
+
+
+def test_a_failed_upload_falls_back_to_a_disclosed_notice() -> None:
+ adapter = _adapter()
+ _bot(adapter).send_photo_error = TelegramError("upload rejected")
+
+ _run(adapter.send_attachment(str(CHAT_ID), "scout", "c.png", "image/png", b"bytes"))
+
+ assert "couldn't be relayed" in _bot(adapter).messages[0]["text"]
+ assert "c.png" in _bot(adapter).messages[0]["text"]
+
+
+def test_an_overflowing_caption_is_not_posted_twice_when_the_upload_fails() -> None:
+ # The caption has already gone out on its own; handing it to the fallback
+ # notice as well would say the same thing twice.
+ adapter = _adapter()
+ _bot(adapter).send_photo_error = TelegramError("upload rejected")
+
+ _run(
+ adapter.send_attachment(
+ str(CHAT_ID), "scout", "c.png", "image/png", b"bytes", "c" * 2000
+ )
+ )
+
+ posted = _bot(adapter).messages
+ assert len(posted) == 2
+ assert "c" * 2000 in posted[0]["text"]
+ assert "c" * 100 not in posted[1]["text"]
+ assert "couldn't be relayed" in posted[1]["text"]
+
+
+def test_several_images_arrive_as_one_album() -> None:
+ adapter = _adapter()
+ files = [
+ OutboundAttachment(filename="a.png", mimetype="image/png", data=b"a"),
+ OutboundAttachment(filename="b.png", mimetype="image/png", data=b"b"),
+ ]
+
+ _run(adapter.send_attachments(str(CHAT_ID), "scout", files, "two charts"))
+
+ album = _bot(adapter).albums[0]
+ assert len(album["media"]) == 2
+ # Only the first item's caption shows for the album as a whole.
+ assert album["media"][0].caption == f"{SCOUT_MARK} <b>scout</b>: two charts"
+ assert album["media"][1].caption is None
+ assert _bot(adapter).photos == []
+
+
+def test_a_mixed_batch_falls_back_to_one_message_per_file() -> None:
+ # sendMediaGroup will not mix photos with documents.
+ adapter = _adapter()
+ files = [
+ OutboundAttachment(filename="a.png", mimetype="image/png", data=b"a"),
+ OutboundAttachment(filename="b.csv", mimetype="text/csv", data=b"b"),
+ ]
+
+ _run(adapter.send_attachments(str(CHAT_ID), "scout", files))
+
+ assert _bot(adapter).albums == []
+ assert len(_bot(adapter).photos) == 1
+ assert len(_bot(adapter).documents) == 1
+
+
+def test_a_batch_over_the_album_limit_falls_back_to_one_message_per_file() -> None:
+ adapter = _adapter()
+ files = [
+ OutboundAttachment(filename=f"{i}.png", mimetype="image/png", data=b"x")
+ for i in range(11)
+ ]
+
+ _run(adapter.send_attachments(str(CHAT_ID), "scout", files))
+
+ assert _bot(adapter).albums == []
+ assert len(_bot(adapter).photos) == 11
+
+
+def test_a_single_file_batch_is_just_an_attachment() -> None:
+ adapter = _adapter()
+ files = [OutboundAttachment(filename="a.png", mimetype="image/png", data=b"a")]
+
+ _run(adapter.send_attachments(str(CHAT_ID), "scout", files, "one"))
+
+ assert _bot(adapter).albums == []
+ assert _bot(adapter).photos[0]["caption"] == f"{SCOUT_MARK} <b>scout</b>: one"
+
+
+def test_a_rejected_album_still_delivers_the_files() -> None:
+ adapter = _adapter()
+ _bot(adapter).send_album_error = TelegramError("album rejected")
+ files = [
+ OutboundAttachment(filename="a.png", mimetype="image/png", data=b"a"),
+ OutboundAttachment(filename="b.png", mimetype="image/png", data=b"b"),
+ ]
+
+ _run(adapter.send_attachments(str(CHAT_ID), "scout", files))
+
+ assert len(_bot(adapter).photos) == 2
+
+
+# ── Runtime state ────────────────────────────────────────────────────────────
+
+
+def test_working_posts_a_status_message() -> None:
+ adapter = _adapter()
+
+ _run(
+ adapter.apply_runtime_state(
+ str(CHAT_ID), "scout", "working", notify_user=None, thread_root_id=None
+ )
+ )
+
+ assert "Working on it" in _bot(adapter).messages[0]["text"]
+ assert (str(CHAT_ID), "scout") in adapter._working_msg
+
+
+def test_working_again_edits_the_status_rather_than_reposting() -> None:
+ adapter = _adapter()
+ _run(
+ adapter.apply_runtime_state(
+ str(CHAT_ID), "scout", "working", notify_user=None, thread_root_id=None
+ )
+ )
+
+ _run(
+ adapter.apply_runtime_state(
+ str(CHAT_ID),
+ "scout",
+ "working",
+ notify_user=None,
+ thread_root_id=None,
+ detail="Editing adapter.py",
+ )
+ )
+
+ assert len(_bot(adapter).messages) == 1
+ assert "Editing adapter.py" in _bot(adapter).edits[0]["text"]
+
+
+def test_awaiting_input_pings_the_operator() -> None:
+ adapter = _adapter()
+
+ _run(
+ adapter.apply_runtime_state(
+ str(CHAT_ID),
+ "scout",
+ "awaiting-input",
+ notify_user="alice",
+ thread_root_id=None,
+ )
+ )
+
+ assert "needs your input" in _bot(adapter).messages[0]["text"]
+ assert adapter._input_pings[(str(CHAT_ID), "scout")]
+
+
+def test_going_idle_removes_the_status_and_the_pings() -> None:
+ adapter = _adapter()
+ _run(
+ adapter.apply_runtime_state(
+ str(CHAT_ID), "scout", "working", notify_user=None, thread_root_id=None
+ )
+ )
+ _run(
+ adapter.apply_runtime_state(
+ str(CHAT_ID),
+ "scout",
+ "awaiting-input",
+ notify_user="alice",
+ thread_root_id=None,
+ )
+ )
+
+ _run(
+ adapter.apply_runtime_state(
+ str(CHAT_ID), "scout", "idle", notify_user=None, thread_root_id=None
+ )
+ )
+
+ assert adapter._working_msg == {}
+ assert adapter._input_pings == {}
+ assert len(_bot(adapter).deletes) == 2
+
+
+def test_the_status_message_follows_the_conversation() -> None:
+ # Repositioning comes from the base class, but only for adapters that track
+ # the indicator — this asserts Telegram does.
+ adapter = _adapter()
+ _run(
+ adapter.apply_runtime_state(
+ str(CHAT_ID), "scout", "working", notify_user=None, thread_root_id=None
+ )
+ )
+ original = adapter._working_msg[(str(CHAT_ID), "scout")].message_ref
+
+ _run(adapter.reposition_runtime_state(str(CHAT_ID), "scout", "88"))
+
+ moved = adapter._working_msg[(str(CHAT_ID), "scout")]
+ assert moved.message_ref != original
+ assert moved.thread_root_id == "88"
+ # The replacement goes up before the original comes down.
+ assert _bot(adapter).deletes[0]["message_id"] == int(original.split(":")[1])
+
+
+# ── Translation ──────────────────────────────────────────────────────────────
+
+
+ ("markdown", "expected"),
+ [
+ ("**bold**", "<b>bold</b>"),
+ ("*italic*", "<i>italic</i>"),
+ ("_italic_", "<i>italic</i>"),
+ ("~~gone~~", "<s>gone</s>"),
+ ("`code`", "<code>code</code>"),
+ ("## Heading", "<b>Heading</b>"),
+ ("- item", "• item"),
+ ("[label](https://e.com)", '<a href="https://e.com">label</a>'),
+ ],
+)
+def test_markdown_becomes_telegram_html(markdown: str, expected: str) -> None:
+ assert _adapter().translate_outbound(markdown) == expected
+
+
+def test_html_characters_in_the_body_are_escaped() -> None:
+ # Otherwise Telegram reads them as markup and rejects the whole message.
+ assert _adapter().translate_outbound("a < b & c") == "a &lt; b &amp; c"
+
+
+def test_code_contents_are_never_treated_as_markup() -> None:
+ adapter = _adapter()
+
+ rendered = adapter.translate_outbound("```py\nif a < b and *x*:\n```")
+
+ assert rendered == "<pre>if a &lt; b and *x*:</pre>"
+
+
+def test_a_url_is_escaped_once_not_twice() -> None:
+ adapter = _adapter()
+
+ rendered = adapter.translate_outbound("[x](https://e.com?a=1&b=2)")
+
+ assert rendered == '<a href="https://e.com?a=1&amp;b=2">x</a>'
+
+
+def test_a_deeplink_telegram_cannot_render_becomes_copyable_text() -> None:
+ # "Open in Switch Console" is a `switchdash://` URL. Telegram linkifies only
+ # http(s)/tg, and an anchor carrying anything else is either rejected — which
+ # cost the whole message — or stripped by the client, leaving a label with no
+ # address behind it. Neither is acceptable, so the address stays visible.
+ adapter = _adapter()
+
+ rendered = adapter.translate_outbound(
+ "([Open in Switch Console](switchdash://session?server=https%3A%2F%2Fs&agent=a))"
+ )
+
+ assert "<a href" not in rendered
+ assert (
+ rendered == "(Open in Switch Console: <code>switchdash://session"
+ "?server=https%3A%2F%2Fs&amp;agent=a</code>)"
+ )
+
+
+def test_an_https_deeplink_is_still_a_real_link() -> None:
+ # With GATEWAY_PUBLIC_URL set, the deeplink is rewritten to the https
+ # redirect before it reaches the adapter — and that one must stay clickable.
+ adapter = _adapter()
+
+ rendered = adapter.translate_outbound(
+ "([Open in Switch Console](https://api.acme.test/deeplink/session?agent=a))"
+ )
+
+ assert rendered == (
+ '(<a href="https://api.acme.test/deeplink/session?agent=a">'
+ "Open in Switch Console</a>)"
+ )
+
+
+ "url",
+ [
+ "tg://resolve?domain=acme",
+ "mailto:[email protected]",
+ "http://acme.test",
+ ],
+)
+def test_a_scheme_telegram_renders_is_left_clickable(url: str) -> None:
+ # Only a scheme Telegram will not render gets downgraded. Narrowing this
+ # further would turn working links into code spans.
+ adapter = _adapter()
+
+ rendered = adapter.translate_outbound(f"[go]({url})")
+
+ assert rendered == f'<a href="{url}">go</a>'
+
+
+def test_a_table_is_left_as_written() -> None:
+ # Telegram cannot render tables; mangling one helps nobody.
+ adapter = _adapter()
+ table = "| a | b |\n| - | - |"
+
+ assert adapter.translate_outbound(table) == table
+
+
+def test_a_known_person_is_mentioned_by_id() -> None:
+ adapter = _adapter()
+ adapter.prime_mention_targets({"alice": "12345"})
+
+ rendered = adapter.translate_outbound("ping @alice")
+
+ assert rendered == 'ping <a href="tg://user?id=12345">@alice</a>'
+
+
+def test_an_unknown_name_stays_plain_so_the_client_can_link_it() -> None:
+ adapter = _adapter()
+
+ assert adapter.translate_outbound("ping @bob") == "ping @bob"
+
+
+def test_an_agent_name_is_not_turned_into_a_mention() -> None:
+ # Agents are not Telegram users; linking them would go nowhere.
+ adapter = _adapter()
+ adapter.prime_mention_targets({"alice": "12345"})
+
+ assert adapter.translate_outbound("@switch.cmcdermott") == "@switch.cmcdermott"
+
+
+def test_priming_ignores_entries_that_are_not_numeric_ids() -> None:
+ adapter = _adapter()
+
+ adapter.prime_mention_targets({"alice": "not-an-id", "": "5"})
+
+ assert adapter.translate_outbound("@alice") == "@alice"
+
+
+def test_inbound_text_needs_no_rewriting() -> None:
+ # Telegram already delivers @handle the way Switch expects.
+ adapter = _adapter()
+
+ assert adapter.translate_inbound("hi @alice") == "hi @alice"
+
+
+# ── Lifecycle ────────────────────────────────────────────────────────────────
+
+
+class _FakeUpdater:
+ def __init__(self) -> None:
+ self.polling_kwargs: dict[str, Any] | None = None
+ self.stopped = False
+
+ async def start_polling(self, **kwargs: Any) -> None:
+ self.polling_kwargs = kwargs
+
+ async def stop(self) -> None:
+ self.stopped = True
+
+
+class _FakeApplication:
+ def __init__(
+ self,
+ *,
+ can_read_all_group_messages: bool = True,
+ can_join_groups: bool | None = None,
+ ) -> None:
+ self.bot = _FakeBot()
+ self.updater = _FakeUpdater()
+ self.handlers: list[Any] = []
+ self.started = False
+ self.shut_down = False
+ self._can_read_all = can_read_all_group_messages
+ # None leaves the field off getMe entirely, as an older Bot API would.
+ self._can_join_groups = can_join_groups
+ self.bot.get_me = self._get_me # type: ignore[attr-defined]
+
+ async def _get_me(self) -> Any:
+ fields: dict[str, Any] = {
+ "id": BOT_USER_ID,
+ "username": BOT_USERNAME,
+ "can_read_all_group_messages": self._can_read_all,
+ }
+ if self._can_join_groups is not None:
+ fields["can_join_groups"] = self._can_join_groups
+ return type("_Me", (), fields)()
+
+ def add_handler(self, handler: Any) -> None:
+ self.handlers.append(handler)
+
+ async def initialize(self) -> None:
+ self.initialized = True
+
+ async def start(self) -> None:
+ self.started = True
+
+ async def stop(self) -> None:
+ self.started = False
+
+ async def shutdown(self) -> None:
+ self.shut_down = True
+
+
+class _FakeBuilder:
+ def __init__(self, app: _FakeApplication) -> None:
+ self._app = app
+
+ def token(self, _token: str) -> _FakeBuilder:
+ return self
+
+ def build(self) -> _FakeApplication:
+ return self._app
+
+
+async def _noop(_value: Any) -> None:
+ return None
+
+
+def test_starting_begins_polling_and_learns_the_bot_id() -> None:
+ adapter = TelegramAdapter(
+ config=TelegramConnectionConfig(bot_token="token", bot_username=BOT_USERNAME)
+ )
+ app = _FakeApplication()
+
+ with patch.object(adapter_module, "ApplicationBuilder", lambda: _FakeBuilder(app)):
+ _run(adapter.start(_noop, _noop, _noop, _noop, _noop))
+
+ assert app.started is True
+ assert adapter._bot_user_id == BOT_USER_ID
+ assert app.updater.polling_kwargs is not None
+ assert app.updater.polling_kwargs["allowed_updates"] == [
+ "message",
+ "channel_post",
+ "my_chat_member",
+ ]
+
+
+def test_a_second_poller_on_the_same_token_is_named(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ # Telegram hands each update to one getUpdates caller, so a leftover
+ # deployment or a second replica quietly takes a share of the traffic:
+ # outbound still works, inbound goes dead, and nothing says why unless the
+ # Conflict is surfaced (CHOO-1686).
+ with caplog.at_level(logging.ERROR):
+ TelegramAdapter._on_polling_error(Conflict("terminated by other getUpdates"))
+
+ assert "Another process is polling Telegram with this bot token" in caplog.text
+ assert "missing inbound messages" in caplog.text
+
+
+def test_other_polling_errors_are_reported_but_not_misdiagnosed(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ with caplog.at_level(logging.WARNING):
+ TelegramAdapter._on_polling_error(TelegramError("temporary network blip"))
+
+ assert "temporary network blip" in caplog.text
+ assert "Another process" not in caplog.text
+
+
+def test_polling_installs_the_error_callback() -> None:
+ # Without it the Conflict never reaches the log at all.
+ adapter = TelegramAdapter(
+ config=TelegramConnectionConfig(bot_token="token", bot_username=BOT_USERNAME)
+ )
+ app = _FakeApplication()
+
+ with patch.object(adapter_module, "ApplicationBuilder", lambda: _FakeBuilder(app)):
+ _run(adapter.start(_noop, _noop, _noop, _noop, _noop))
+
+ assert app.updater.polling_kwargs is not None
+ assert "error_callback" in app.updater.polling_kwargs
+
+
+def test_privacy_mode_on_is_not_reported_as_a_fault(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ # BotFather enables it by default and it used to be logged as a warning,
+ # but on its own it is not a fault: Telegram exempts a bot that is an
+ # administrator of a chat, which is what the dashboard's install link
+ # grants. Whether any one chat is readable is a per-chat question.
+ adapter = TelegramAdapter(
+ config=TelegramConnectionConfig(bot_token="token", bot_username=BOT_USERNAME)
+ )
+ app = _FakeApplication(can_read_all_group_messages=False)
+
+ with patch.object(adapter_module, "ApplicationBuilder", lambda: _FakeBuilder(app)):
+ with caplog.at_level(logging.INFO):
+ _run(adapter.start(_noop, _noop, _noop, _noop, _noop))
+
+ assert "administrator" in caplog.text
+ assert [r for r in caplog.records if r.levelno >= logging.WARNING] == []
+ # Still starts, and knows what it read.
+ assert adapter._privacy_mode_disabled is False
+ assert app.updater.polling_kwargs is not None
+
+
+def test_privacy_mode_off_is_recorded_as_seeing_everything(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ adapter = TelegramAdapter(
+ config=TelegramConnectionConfig(bot_token="token", bot_username=BOT_USERNAME)
+ )
+ app = _FakeApplication(can_read_all_group_messages=True)
+
+ with patch.object(adapter_module, "ApplicationBuilder", lambda: _FakeBuilder(app)):
+ with caplog.at_level(logging.INFO):
+ _run(adapter.start(_noop, _noop, _noop, _noop, _noop))
+
+ assert adapter._privacy_mode_disabled is True
+ assert "sees all messages" in caplog.text
+
+
+def test_stopping_shuts_the_application_down() -> None:
+ adapter = TelegramAdapter(
+ config=TelegramConnectionConfig(bot_token="token", bot_username=BOT_USERNAME)
+ )
+ app = _FakeApplication()
+
+ with patch.object(adapter_module, "ApplicationBuilder", lambda: _FakeBuilder(app)):
+ _run(adapter.start(_noop, _noop, _noop, _noop, _noop))
+ _run(adapter.stop())
+
+ assert app.updater.stopped is True
+ assert app.shut_down is True
+ assert adapter._bot is None
+
+
+def test_sending_before_the_bridge_is_connected_fails_loudly() -> None:
+ adapter = TelegramAdapter(
+ config=TelegramConnectionConfig(bot_token="token", bot_username=BOT_USERNAME)
+ )
+
+ with pytest.raises(RuntimeError, match="not connected"):
+ _run(adapter.send_message(str(CHAT_ID), "scout", "hello"))
+
+
+class _FakeMedia:
+ def __init__(
+ self, file_id: str, *, name: str | None = None, mime: str | None = None
+ ) -> None:
+ self.file_id = file_id
+ self.file_name = name
+ self.mime_type = mime
+ self.file_size = 4
+
+
+ ("field", "filename", "mimetype"),
+ [
+ ("video", "video.mp4", "video/mp4"),
+ ("animation", "animation.mp4", "video/mp4"),
+ ("audio", "audio.mp3", "audio/mpeg"),
+ ("voice", "voice.ogg", "audio/ogg"),
+ ("video_note", "video_note.mp4", "video/mp4"),
+ ],
+)
+def test_every_media_kind_is_relayed(field: str, filename: str, mimetype: str) -> None:
+ # Telegram models each kind as its own field rather than one attachments
+ # list, so a kind missing from the loop is simply never relayed.
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+ _bot(adapter).files["m1"] = _FakeFileHandle(b"media")
+
+ _run(
+ adapter._handle_message(
+ _FakeInbound(text=None, caption="look", **{field: _FakeMedia("m1")})
+ )
+ )
+
+ assert [a.filename for a in seen[0].attachments] == [filename]
+ assert seen[0].attachments[0].mimetype == mimetype
+
+
+def test_media_keeps_its_own_name_and_type_when_telegram_supplies_them() -> None:
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+ _bot(adapter).files["m1"] = _FakeFileHandle(b"media")
+
+ _run(
+ adapter._handle_message(
+ _FakeInbound(
+ text=None,
+ caption="clip",
+ video=_FakeMedia("m1", name="demo.mov", mime="video/quicktime"),
+ )
+ )
+ )
+
+ assert seen[0].attachments[0].filename == "demo.mov"
+ assert seen[0].attachments[0].mimetype == "video/quicktime"
+
+
+ "field",
+ ["left_chat_member", "new_chat_title", "pinned_message", "group_chat_created"],
+)
+def test_service_messages_are_not_bridged_as_empty_messages(field: str) -> None:
+ # A service message has a real sender and no body. Telegram has no empty
+ # user message, so relaying one puts a blank line in the room (CHOO-1686).
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+
+ _run(adapter._handle_message(_FakeInbound(text=None, **{field: object()})))
+
+ assert seen == []
+
+
+def test_a_photo_with_no_caption_is_still_bridged() -> None:
+ # The service-message guard keys on there being nothing at all to relay, so
+ # it must not swallow a wordless image.
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+ _bot(adapter).files["p1"] = _FakeFileHandle(b"img")
+
+ _run(
+ adapter._handle_message(
+ _FakeInbound(text=None, photo=[_FakePhotoSize("p1", "u1", 4)])
+ )
+ )
+
+ assert len(seen) == 1
+ assert seen[0].content == ""
+ assert len(seen[0].attachments) == 1
+
+
+def test_an_undownloadable_attachment_is_still_bridged_as_a_failure() -> None:
+ # Disclosure beats silence: the guard must not treat "only failures" as a
+ # service message and drop the disclosure with it.
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+ _bot(adapter).files["d1"] = _FakeFileHandle(b"", fail=True)
+
+ _run(
+ adapter._handle_message(
+ _FakeInbound(text=None, document=_FakeDocument("d1", "x.bin", None, 4))
+ )
+ )
+
+ assert len(seen) == 1
+ assert seen[0].attachment_failures[0].filename == "x.bin"
+
+
+def test_a_forum_topic_message_belongs_to_the_chat_not_the_topic() -> None:
+ # The topic id is the thread root; the room is still keyed on the chat.
+ adapter = _adapter()
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+
+ _run(adapter._handle_message(_FakeInbound(message_thread_id=88)))
+
+ assert seen[0].channel_id == str(CHAT_ID)
+ assert seen[0].root_id == "88"
+
+
+def test_the_dedupe_cache_evicts_oldest_first() -> None:
+ # Unbounded growth would be a slow leak on a busy bridge; eviction is what
+ # bounds it, and an evicted id must be able to bridge again.
+ adapter = _adapter()
+ adapter._seen_ids_max = 3
+ seen: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(seen, m)
+
+ for message_id in (1, 2, 3, 4):
+ _run(adapter._handle_message(_FakeInbound(message_id=message_id)))
+
+ assert len(adapter._seen_ids) == 3
+ assert (str(CHAT_ID), 1) not in adapter._seen_ids
+
+ _run(adapter._handle_message(_FakeInbound(message_id=1)))
+
+ assert len(seen) == 5
+
+
+def test_a_command_published_under_its_underscore_name_still_resolves() -> None:
+ # Telegram will not register a hyphen, so the menu offers `/invite_agent`.
+ adapter = _adapter()
+ commands: list[InboundCommand] = []
+ adapter._on_command = lambda c: _collect(commands, c)
+
+ _run(adapter._handle_message(_FakeInbound(text="/invite_agent @scout")))
+
+ assert commands[0].command == "invite-agent"
+ assert commands[0].args == "@scout"
+
+
+def test_the_bots_own_username_wins_over_a_configured_one(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ # Every t.me link is built from this name, and a name that is not the
+ # bot's resolves to whatever account does own it — so the link opens a
+ # chat with a stranger and reads as a link that did nothing. The token
+ # says which bot this is; the configured name is a label someone typed.
+ adapter = TelegramAdapter(
+ config=TelegramConnectionConfig(bot_token="token", bot_username="wrong_name")
+ )
+ app = _FakeApplication()
+
+ with patch.object(adapter_module, "ApplicationBuilder", lambda: _FakeBuilder(app)):
+ with caplog.at_level(logging.WARNING):
+ _run(adapter.start(_noop, _noop, _noop, _noop, _noop))
+
+ assert "wrong_name" in caplog.text
+ assert BOT_USERNAME in caplog.text
+ # Corrected everywhere a link is built from it, not just complained about.
+ assert adapter._bot_username == BOT_USERNAME
+ for link in _run(adapter.install_links()):
+ assert f"t.me/{BOT_USERNAME}" in link.url
+ assert _run(adapter.home_deeplink()) == f"https://t.me/{BOT_USERNAME}"
+
+
+def test_groups_disabled_in_botfather_withholds_the_group_link(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ # Telegram answers an add-to-group link for such a bot by opening a chat
+ # with it, which is indistinguishable from a broken link. Better to not
+ # offer it and say why.
+ adapter = TelegramAdapter(
+ config=TelegramConnectionConfig(bot_token="token", bot_username=BOT_USERNAME)
+ )
+ app = _FakeApplication(can_join_groups=False)
+
+ with patch.object(adapter_module, "ApplicationBuilder", lambda: _FakeBuilder(app)):
+ with caplog.at_level(logging.WARNING):
+ _run(adapter.start(_noop, _noop, _noop, _noop, _noop))
+
+ assert _run(adapter.install_links()) == []
+ assert "Allow Groups" in caplog.text
+
+
+def test_groups_are_assumed_allowed_when_the_bot_does_not_say() -> None:
+ # BotFather's default, and an older Bot API that omits the field must not
+ # be read as a refusal.
+ adapter = TelegramAdapter(
+ config=TelegramConnectionConfig(bot_token="token", bot_username=BOT_USERNAME)
+ )
+ app = _FakeApplication()
+
+ with patch.object(adapter_module, "ApplicationBuilder", lambda: _FakeBuilder(app)):
+ _run(adapter.start(_noop, _noop, _noop, _noop, _noop))
+
+ assert [link.key for link in _run(adapter.install_links())] == ["group"]
+
+
+def test_a_bad_token_fails_the_start_rather_than_running_deaf() -> None:
+ adapter = TelegramAdapter(
+ config=TelegramConnectionConfig(bot_token="bad", bot_username=BOT_USERNAME)
+ )
+ app = _FakeApplication()
+
+ async def _unauthorised() -> Any:
+ raise TelegramError("Unauthorized")
+
+ app.bot.get_me = _unauthorised # type: ignore[attr-defined]
+
+ with patch.object(adapter_module, "ApplicationBuilder", lambda: _FakeBuilder(app)):
+ with pytest.raises(TelegramError, match="Unauthorized"):
+ _run(adapter.start(_noop, _noop, _noop, _noop, _noop))
+
+ assert app.updater.polling_kwargs is None
+
+
+def test_an_application_without_an_updater_fails_loudly() -> None:
+ # Polling is the only inbound path; an application that cannot poll would
+ # otherwise send happily and receive nothing.
+ adapter = TelegramAdapter(
+ config=TelegramConnectionConfig(bot_token="token", bot_username=BOT_USERNAME)
+ )
+ app = _FakeApplication()
+ app.updater = None # type: ignore[assignment]
+
+ with patch.object(adapter_module, "ApplicationBuilder", lambda: _FakeBuilder(app)):
+ with pytest.raises(RuntimeError, match="without an updater"):
+ _run(adapter.start(_noop, _noop, _noop, _noop, _noop))
+
+
+def test_the_command_menu_is_published_in_telegrams_spelling() -> None:
+ adapter = TelegramAdapter(
+ config=TelegramConnectionConfig(bot_token="token", bot_username=BOT_USERNAME)
+ )
+ app = _FakeApplication()
+
+ with patch.object(adapter_module, "ApplicationBuilder", lambda: _FakeBuilder(app)):
+ _run(adapter.start(_noop, _noop, _noop, _noop, _noop))
+
+ published = {c.command for c in app.bot.published_commands}
+ assert "invite_agent" in published
+ assert not any("-" in name for name in published)
+
+
+def test_a_menu_telegram_rejects_does_not_stop_the_bridge(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ # The bridge is fully usable without the menu; refusing to start over it
+ # would be a far worse outcome.
+ adapter = TelegramAdapter(
+ config=TelegramConnectionConfig(bot_token="token", bot_username=BOT_USERNAME)
+ )
+ app = _FakeApplication()
+
+ async def _reject(_commands: Any) -> None:
+ raise TelegramError("bad menu")
+
+ app.bot.set_my_commands = _reject # type: ignore[attr-defined]
+
+ with patch.object(adapter_module, "ApplicationBuilder", lambda: _FakeBuilder(app)):
+ with caplog.at_level(logging.ERROR):
+ _run(adapter.start(_noop, _noop, _noop, _noop, _noop))
+
+ assert "Could not publish the Telegram command menu" in caplog.text
+ assert app.updater.polling_kwargs is not None
+
+
+def test_a_mention_inside_a_link_does_not_nest_anchors() -> None:
+ # Rewriting an `@name` that sits in a link's label or target produced an
+ # anchor inside an anchor, which Telegram rejects — and a caption or an edit
+ # has no plain-text retry to save it (CHOO-1686).
+ adapter = _adapter()
+ adapter.prime_mention_targets({"alice": "555"})
+
+ assert (
+ adapter.translate_outbound("[profile](https://x.com/@alice)")
+ == '<a href="https://x.com/@alice">profile</a>'
+ )
+ assert (
+ adapter.translate_outbound("[ping @alice](https://x.com)")
+ == '<a href="https://x.com">ping @alice</a>'
+ )
+
+
+def test_formatting_inside_a_link_label_still_renders() -> None:
+ adapter = _adapter()
+
+ assert (
+ adapter.translate_outbound("[**bold** link](https://e.com)")
+ == '<a href="https://e.com"><b>bold</b> link</a>'
+ )
+
+
+def test_a_mention_outside_a_link_is_still_rendered() -> None:
+ adapter = _adapter()
+ adapter.prime_mention_targets({"alice": "555"})
+
+ assert (
+ adapter.translate_outbound("hi @alice")
+ == 'hi <a href="tg://user?id=555">@alice</a>'
+ )
+
+
+def test_unmatched_brackets_do_not_stall_the_bridge() -> None:
+ # `[` inside the link label's character class made the matcher retry the
+ # whole tail from every position: 200k characters of unmatched brackets —
+ # a pasted log, a changelog of `[FIX]` lines — blocked the event loop for
+ # about thirteen seconds, and served as a denial of service.
+ import time
+
+ adapter = _adapter()
+ body = "[unclosed " * 20_000
+
+ started = time.monotonic()
+ adapter.translate_outbound(body)
+
+ assert time.monotonic() - started < 1.0
+
+
+def test_an_over_long_edit_is_cut_to_valid_markup() -> None:
+ # An edit cannot be split across messages the way a send can, and cutting
+ # the rendered HTML by character count left it ending mid-attribute — which
+ # Telegram rejects, losing the edit entirely.
+ adapter = _adapter()
+ rendered = adapter.translate_outbound("**" + "word " * 1500 + "**")
+
+ clamped = adapter._clamp(rendered)
+
+ assert len(clamped) <= 4096
+ assert clamped.count("<b>") == clamped.count("</b>")
+
+
+def test_an_edit_telegram_will_not_parse_is_resent_unformatted() -> None:
+ # Without this the status message silently stays stale for good.
+ adapter = _adapter()
+ calls: list[dict[str, Any]] = []
+
+ async def _edit(**kwargs: Any) -> None:
+ calls.append(kwargs)
+ if len(calls) == 1:
+ raise BadRequest("Can't parse entities: bad tag")
+
+ _bot(adapter).edit_message_text = _edit # type: ignore[method-assign]
+
+ _run(adapter.update_message(str(CHAT_ID), f"{CHAT_ID}:501", "<b>oops</unclosed>"))
+
+ assert len(calls) == 2
+ assert "parse_mode" not in calls[1]
+ assert "<" not in calls[1]["text"]
+
+
+def test_two_people_with_the_same_display_name_stay_distinct() -> None:
+ # Stripping spaces makes collisions likelier ("Ann Marie" and "AnnMarie"),
+ # and two people sharing a handle would share a room identity — a mention
+ # meant for one reaching whichever spoke last.
+ adapter = _adapter()
+
+ class _U:
+ def __init__(self, user_id: int, first: str, last: str) -> None:
+ self.id = user_id
+ self.username = None
+ self.first_name = first
+ self.last_name = last
+
+ assert adapter._display_name(_U(1, "Ann", "Marie")) != adapter._display_name(
+ _U(2, "AnnMarie", "")
+ )
+
+
+def test_a_public_username_is_used_as_is() -> None:
+ adapter = _adapter()
+
+ assert adapter._display_name(_FakeUser(user_id=7, username="alice")) == "alice"
+
+
+def test_the_underscore_spelling_is_only_translated_for_slash_commands() -> None:
+ # `!` is Switch's own prefix and its names are spelled as the dispatcher
+ # knows them, so rewriting there would turn a typo into another command.
+ adapter = _adapter()
+
+ assert adapter._parse_command("/list_agents") == ("list-agents", "")
+ assert adapter._parse_command("!list_agents") == ("list_agents", "")
+ assert adapter._parse_command("!list-agents") == ("list-agents", "")
+
+
+# ── Install links ────────────────────────────────────────────────────────────
+
+
+def test_the_group_install_link_asks_for_no_permissions() -> None:
+ # The bridge needs none in a group: a bot posts and deletes its own
+ # messages as an ordinary member. Asking to be an administrator bought
+ # only an exemption from privacy mode, which turning Group Privacy off in
+ # BotFather gives once per bot rather than once per group — and its chat
+ # picker leaves out basic groups entirely (CHOO-1686).
+ adapter = _adapter()
+
+ links = {link.key: link for link in _run(adapter.install_links())}
+
+ group = links["group"]
+ assert group.url == (f"https://t.me/{BOT_USERNAME}?startgroup={_INSTALL_PAYLOAD}")
+ assert "admin=" not in group.url
+
+
+def test_no_group_link_asks_to_be_an_administrator() -> None:
+ # A permission prompt is only as trustworthy as its contents, and the
+ # honest count for a group is zero.
+ adapter = _adapter()
+
+ for link in _run(adapter.install_links()):
+ if link.key.startswith("group"):
+ assert "admin=" not in link.url
+
+
+def test_an_install_link_carries_no_credential() -> None:
+ # It is handed to the operator's browser and then to Telegram.
+ adapter = _adapter()
+
+ for link in _run(adapter.install_links()):
+ assert "token" not in link.url
+
+
+# ── What the bridge can see in a chat ────────────────────────────────────────
+
+
+def test_an_administrator_bot_sees_everything_despite_privacy_mode() -> None:
+ # Telegram's own rule: "bot admins always receive all messages". This is
+ # what makes the one-click install enough on its own.
+ adapter = _adapter()
+ adapter._privacy_mode_disabled = False
+ _bot(adapter).member_status = "administrator"
+
+ assert _run(adapter._chat_visibility(str(CHAT_ID))).status == "full"
+
+
+def test_a_plain_member_bot_with_privacy_mode_on_is_mention_only() -> None:
+ adapter = _adapter()
+ adapter._privacy_mode_disabled = False
+ _bot(adapter).member_status = "member"
+
+ assert _run(adapter._chat_visibility(str(CHAT_ID))).status == "mention_only"
+
+
+def test_a_plain_member_bot_with_privacy_mode_off_sees_everything() -> None:
+ adapter = _adapter()
+ adapter._privacy_mode_disabled = True
+ _bot(adapter).member_status = "member"
+
+ assert _run(adapter._chat_visibility(str(CHAT_ID))).status == "full"
+
+
+def test_a_one_to_one_chat_is_always_fully_visible() -> None:
+ # Privacy mode has never applied to private chats.
+ adapter = _adapter()
+ adapter._privacy_mode_disabled = False
+ _bot(adapter).chat = _FakeChat(chat_type="private")
+
+ assert _run(adapter._chat_visibility("7")).status == "full"
+
+
+def test_visibility_is_unknown_rather_than_guessed_when_the_lookup_fails() -> None:
+ adapter = _adapter()
+ _bot(adapter).get_chat_member_error = TelegramError("no")
+
+ assert _run(adapter._chat_visibility(str(CHAT_ID))).status == "unknown"
+
+
+def test_a_mention_only_chat_is_told_so_in_the_chat() -> None:
+ # Otherwise it is indistinguishable from agents ignoring people.
+ adapter = _adapter()
+ adapter._privacy_mode_disabled = False
+ _bot(adapter).member_status = "member"
+
+ _run(adapter.announce_visibility(str(CHAT_ID)))
+
+ posted = _bot(adapter).messages[-1]["text"]
+ assert "only see messages that tag me" in posted
+ assert "administrator" in posted
+
+
+def test_a_fully_visible_chat_is_not_told_anything() -> None:
+ adapter = _adapter()
+ _bot(adapter).member_status = "administrator"
+
+ _run(adapter.announce_visibility(str(CHAT_ID)))
+
+ assert _bot(adapter).messages == []
+
+
+def test_the_visibility_notice_is_posted_once() -> None:
+ adapter = _adapter()
+ adapter._privacy_mode_disabled = False
+ _bot(adapter).member_status = "member"
+
+ _run(adapter.announce_visibility(str(CHAT_ID)))
+ _run(adapter.announce_visibility(str(CHAT_ID)))
+
+ assert len(_bot(adapter).messages) == 1
+
+
+def test_an_undetermined_visibility_says_nothing_and_stays_undetermined() -> None:
+ # Claiming either way from a failed lookup would be worse than silence, and
+ # the chat must not be marked as told — the next check should try again.
+ adapter = _adapter()
+ _bot(adapter).get_chat_member_error = TelegramError("no")
+
+ _run(adapter.announce_visibility(str(CHAT_ID)))
+
+ assert _bot(adapter).messages == []
+ assert str(CHAT_ID) not in adapter._visibility_announced
+
+
+def test_startup_audit_warns_for_each_mention_only_chat(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ # Logged, not posted: a restart must not repost a notice in every chat.
+ adapter = _adapter()
+ adapter._privacy_mode_disabled = False
+ _bot(adapter).member_status = "member"
+
+ with caplog.at_level(logging.WARNING):
+ _run(
+ adapter.ensure_channel_subscriptions(
+ [(str(CHAT_ID), "channel_private"), ("7", "lobby")]
+ )
+ )
+
+ assert str(CHAT_ID) in caplog.text
+ assert _bot(adapter).messages == []
+
+
+def test_startup_audit_is_quiet_when_every_chat_is_visible(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ adapter = _adapter()
+ _bot(adapter).member_status = "administrator"
+
+ with caplog.at_level(logging.WARNING):
+ _run(adapter.ensure_channel_subscriptions([(str(CHAT_ID), "channel_private")]))
+
+ assert caplog.text == ""
+
+
+# ── Telegram's own /start handshake ──────────────────────────────────────────
+
+
+def test_the_install_handshake_is_absorbed_rather_than_bridged() -> None:
+ # Adding the bot via ?startgroup=<payload> makes Telegram send the bot
+ # `/start@bot <payload>`. That is the platform greeting the bot, not
+ # somebody running a Switch command.
+ adapter = _adapter()
+ commands: list[InboundCommand] = []
+ messages: list[InboundMessage] = []
+ adapter._on_command = lambda c: _collect(commands, c)
+ adapter._on_message = lambda m: _collect(messages, m)
+ _bot(adapter).member_status = "administrator"
+
+ _run(adapter._handle_message(_FakeInbound(text=f"/start@{BOT_USERNAME} switch")))
+
+ assert commands == []
+ assert messages == []
+
+
+def test_the_install_handshake_reports_where_the_chat_came_from(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ adapter = _adapter()
+ _bot(adapter).member_status = "administrator"
+
+ with caplog.at_level(logging.INFO):
+ _run(adapter._handle_message(_FakeInbound(text="/start switch")))
+
+ assert "install link" in caplog.text
+
+
+def test_the_install_handshake_reports_a_chat_it_cannot_read() -> None:
+ # The one moment the operator is looking at the chat, so a mention-only
+ # install says so there and then.
+ adapter = _adapter()
+ adapter._privacy_mode_disabled = False
+ _bot(adapter).member_status = "member"
+
+ _run(adapter._handle_message(_FakeInbound(text="/start switch")))
+
+ assert "only see messages that tag me" in _bot(adapter).messages[-1]["text"]
+
+
+def test_a_bare_start_in_a_group_is_absorbed_too() -> None:
+ # A bot added by hand gets one as well, and it is no more a Switch command
+ # there than it is after an install link.
+ adapter = _adapter()
+ commands: list[InboundCommand] = []
+ adapter._on_command = lambda c: _collect(commands, c)
+ _bot(adapter).member_status = "administrator"
+
+ _run(adapter._handle_message(_FakeInbound(text="/start")))
+
+ assert commands == []
+
+
+def test_a_bare_start_in_a_one_to_one_chat_is_left_alone() -> None:
+ # It is how a person opens a conversation with the bot; swallowing it would
+ # leave the DM unbridged until they typed again.
+ adapter = _adapter()
+ commands: list[InboundCommand] = []
+ adapter._on_command = lambda c: _collect(commands, c)
+ private = _FakeChat(chat_id=7, chat_type="private", title=None)
+
+ _run(adapter._handle_message(_FakeInbound(chat=private, text="/start")))
+
+ assert [c.command for c in commands] == ["start"]
+
+
+def test_an_ordinary_command_is_still_dispatched() -> None:
+ adapter = _adapter()
+ commands: list[InboundCommand] = []
+ adapter._on_command = lambda c: _collect(commands, c)
+
+ _run(adapter._handle_message(_FakeInbound(text="/list-agents")))
+
+ assert [c.command for c in commands] == ["list-agents"]
+
+
+def test_administrator_status_is_reported_as_the_conclusive_answer() -> None:
+ # The global privacy flag is not conclusive — Telegram only reads it when
+ # the bot joins — so callers that can act on the difference need to know
+ # which of the two settled it.
+ adapter = _adapter()
+ adapter._privacy_mode_disabled = True
+ _bot(adapter).member_status = "administrator"
+
+ assert _run(adapter._chat_visibility(str(CHAT_ID))).via_admin is True
+
+
+def test_the_chat_creator_counts_as_an_administrator() -> None:
+ adapter = _adapter()
+ adapter._privacy_mode_disabled = False
+ _bot(adapter).member_status = "creator"
+
+ visibility = _run(adapter._chat_visibility(str(CHAT_ID)))
+ assert visibility.status == "full"
+ assert visibility.via_admin is True
+
+
+def test_full_visibility_from_the_global_setting_alone_is_not_conclusive() -> None:
+ adapter = _adapter()
+ adapter._privacy_mode_disabled = True
+ _bot(adapter).member_status = "member"
+
+ assert _run(adapter._chat_visibility(str(CHAT_ID))).via_admin is False
+
+
+def test_promoting_the_bot_retracts_the_mention_only_warning() -> None:
+ # The documented way to upgrade a chat. Without this the warning stands
+ # forever and nothing confirms the promotion worked.
+ adapter = _adapter()
+ adapter._privacy_mode_disabled = False
+ _bot(adapter).member_status = "member"
+ _run(adapter.announce_visibility(str(CHAT_ID)))
+
+ _bot(adapter).member_status = "administrator"
+ _run(adapter.announce_visibility(str(CHAT_ID)))
+
+ assert "whole conversation here now" in _bot(adapter).messages[-1]["text"]
+
+
+def test_demoting_the_bot_says_what_was_lost() -> None:
+ adapter = _adapter()
+ adapter._privacy_mode_disabled = False
+ _bot(adapter).member_status = "administrator"
+ _run(adapter.announce_visibility(str(CHAT_ID)))
+ assert _bot(adapter).messages == []
+
+ _bot(adapter).member_status = "member"
+ _run(adapter.announce_visibility(str(CHAT_ID)))
+
+ assert "only see messages that tag me" in _bot(adapter).messages[-1]["text"]
+
+
+def test_a_chat_that_was_already_visible_is_not_congratulated() -> None:
+ # Only a change is worth saying. A first look that finds everything in
+ # order stays quiet.
+ adapter = _adapter()
+ _bot(adapter).member_status = "administrator"
+
+ _run(adapter.announce_visibility(str(CHAT_ID)))
+ _run(adapter.announce_visibility(str(CHAT_ID)))
+
+ assert _bot(adapter).messages == []
+
+
+def test_startup_audit_names_a_chat_it_is_taking_on_trust(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ # Privacy mode off, but the bot is not an admin here: Telegram reads that
+ # setting at join time and no API call says which value this chat got. If
+ # the bot predates the change it is still being filtered, and this is the
+ # only line anywhere that says so.
+ adapter = _adapter()
+ adapter._privacy_mode_disabled = True
+ _bot(adapter).member_status = "member"
+
+ with caplog.at_level(logging.INFO):
+ _run(adapter.ensure_channel_subscriptions([(str(CHAT_ID), "channel_private")]))
+
+ assert "add it back" in caplog.text
+ assert [r for r in caplog.records if r.levelno >= logging.WARNING] == []
+
+
+def test_an_administrator_chat_is_audited_without_caveat(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ adapter = _adapter()
+ adapter._privacy_mode_disabled = False
+ _bot(adapter).member_status = "administrator"
+
+ with caplog.at_level(logging.INFO):
+ _run(adapter.ensure_channel_subscriptions([(str(CHAT_ID), "channel_private")]))
+
+ assert caplog.text == ""
+
+
+def test_being_added_by_hand_still_discloses_a_mention_only_chat() -> None:
+ # The route with no install link behind it, and the one most likely to be
+ # mention-only. The notice must not depend on the /start handshake.
+ adapter = _adapter()
+ adapter._privacy_mode_disabled = False
+ _bot(adapter).member_status = "member"
+ joins: list[Any] = []
+ adapter._on_app_joined = lambda j: _collect(joins, j)
+
+ _run(
+ adapter._handle_my_chat_member(
+ _FakeChatMemberUpdate(_FakeChat(), status="member")
+ )
+ )
+
+ assert [j.channel_id for j in joins] == [str(CHAT_ID)]
+ # After provisioning: a notice about a room that does not exist yet would
+ # point at nothing.
+ assert "only see messages that tag me" in _bot(adapter).messages[-1]["text"]
+
+
+def test_a_chat_reissued_a_new_id_is_re_assessed() -> None:
+ # The new id is a different chat as far as Telegram is concerned, so
+ # anything said about the old one no longer holds.
+ adapter = _adapter()
+ adapter._visibility_announced[str(CHAT_ID)] = "mention_only"
+ adapter.set_channel_migration_handler(lambda old, new: _noop_migration())
+
+ _run(adapter._repoint(str(CHAT_ID), "-1009876543210"))
+
+ assert str(CHAT_ID) not in adapter._visibility_announced
+
+
+async def _noop_migration() -> None:
+ return None
+
+
+def test_a_bridge_with_no_bot_username_offers_no_install_link() -> None:
+ # The links are built from it; without one there is nothing to point at.
+ adapter = _adapter()
+ adapter._bot_username = ""
+
+ assert _run(adapter.install_links()) == []
+
+
+def test_the_group_link_lists_every_group() -> None:
+ # The `admin=` form's picker lists only groups the person already
+ # administers, which excludes a basic group — so it could offer nothing to
+ # pick, and Telegram then opens a chat with the bot, reading as a broken
+ # link. The plain form lists every group the person can add a member to.
+ adapter = _adapter()
+
+ links = {link.key: link for link in _run(adapter.install_links())}
+
+ assert "group" in links
+ assert links["group"].url.endswith(f"?startgroup={_INSTALL_PAYLOAD}")
+
+
+def test_the_group_link_says_no_permissions_are_needed() -> None:
+ # The operator is about to confirm a dialog; what it will and will not ask
+ # for is the useful thing to know beforehand.
+ adapter = _adapter()
+
+ group = next(link for link in _run(adapter.install_links()) if link.key == "group")
+
+ assert "no permissions" in group.description
+
+
+def test_no_link_is_offered_when_groups_are_barred() -> None:
+ # The group link is the only one there is, so a bot BotFather has kept out
+ # of groups has nothing to offer rather than something that cannot work.
+ adapter = _adapter()
+ adapter._can_join_groups = False
+
+ assert _run(adapter.install_links()) == []
+
+
+def test_the_install_note_gives_the_route_a_channel_has_to_take() -> None:
+ # No link can add a bot to a channel on every client, so the dialog that
+ # offers the group link has to say where to go instead — otherwise a
+ # missing button is all the operator sees.
+ adapter = _adapter()
+
+ note = _run(adapter.install_note())
+
+ assert note is not None
+ assert "Administrators" in note
+ assert "Post Messages" in note
+
+
+# ── Commands tapped from Telegram's menu ─────────────────────────────────────
+#
+# Telegram sends a command the instant it is tapped in the `/` list, with no
+# chance to type an argument and no way for a bot to say one is needed. So
+# `/invite_agent` from the menu arrives bare, and answering with its usage line
+# leaves the one route out being to retype the whole thing by hand.
+
+
+def test_a_bare_command_that_needs_an_argument_asks_for_it() -> None:
+ adapter = _adapter()
+ commands: list[InboundCommand] = []
+ adapter._on_command = lambda c: _collect(commands, c)
+
+ _run(adapter._handle_message(_FakeInbound(text="/invite_agent")))
+
+ # Not dispatched: running it bare only produces the usage line.
+ assert commands == []
+ sent = _bot(adapter).messages[0]
+ assert "needs one more thing" in sent["text"]
+ # ForceReply is what makes answering a tap rather than a retyped command,
+ # and `selective` keeps it aimed at whoever ran it in a busy group.
+ assert sent["reply_markup"].force_reply is True
+ assert sent["reply_markup"].selective is True
+ # Anchored to their message, which is what `selective` targets.
+ assert sent["reply_parameters"].message_id == 11
+
+
+def test_the_reply_to_that_prompt_runs_the_command() -> None:
+ adapter = _adapter()
+ commands: list[InboundCommand] = []
+ adapter._on_command = lambda c: _collect(commands, c)
+ messages: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(messages, m)
+
+ _run(adapter._handle_message(_FakeInbound(text="/invite_agent")))
+ prompt_id = _bot(adapter).messages[0]["chat_id"], 501
+
+ _run(
+ adapter._handle_message(
+ _FakeInbound(
+ message_id=12,
+ text="@scout",
+ reply_to_message=_FakeInbound(message_id=prompt_id[1]),
+ )
+ )
+ )
+
+ assert [(c.command, c.args) for c in commands] == [("invite-agent", "@scout")]
+ # The answer is the argument, not something to relay into the room.
+ assert messages == []
+
+
+def test_a_second_reply_to_the_same_prompt_is_an_ordinary_message() -> None:
+ # One shot, so a conversation that carries on under the prompt is not
+ # swallowed as repeated invocations.
+ adapter = _adapter()
+ adapter._on_command = lambda c: _collect([], c)
+ messages: list[InboundMessage] = []
+ adapter._on_message = lambda m: _collect(messages, m)
+
+ _run(adapter._handle_message(_FakeInbound(text="/invite_agent")))
+ _run(
+ adapter._handle_message(
+ _FakeInbound(
+ message_id=12,
+ text="@scout",
+ reply_to_message=_FakeInbound(message_id=501),
+ )
+ )
+ )
+ _run(
+ adapter._handle_message(
+ _FakeInbound(
+ message_id=13,
+ text="thanks",
+ reply_to_message=_FakeInbound(message_id=501),
+ )
+ )
+ )
+
+ assert [m.content for m in messages] == ["thanks"]
+
+
+def test_a_bare_command_that_needs_nothing_still_runs() -> None:
+ adapter = _adapter()
+ commands: list[InboundCommand] = []
+ adapter._on_command = lambda c: _collect(commands, c)
+
+ _run(adapter._handle_message(_FakeInbound(text="/list_agents")))
+
+ assert [c.command for c in commands] == ["list-agents"]
+ assert _bot(adapter).messages == []
+
+
+def test_a_command_given_its_argument_is_not_interrupted() -> None:
+ adapter = _adapter()
+ commands: list[InboundCommand] = []
+ adapter._on_command = lambda c: _collect(commands, c)
+
+ _run(adapter._handle_message(_FakeInbound(text="/invite_agent @scout")))
+
+ assert [(c.command, c.args) for c in commands] == [("invite-agent", "@scout")]
+ assert _bot(adapter).messages == []
diff --git a/core/tests/switch_core/bridges/collaboration/test_telegram_chunking.py b/core/tests/switch_core/bridges/collaboration/test_telegram_chunking.py
new file mode 100644
index 000000000..2e4559b78
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_telegram_chunking.py
@@ -0,0 +1,138 @@
+"""Splitting a rendered Telegram body across messages.
+
+The rule is separated from the adapter (as Discord's is) because it is pure and
+the interesting cases are all about markup surviving a cut, which needs no bot,
+no network and no event loop.
+"""
+
+from __future__ import annotations
+
+import re
+
+import pytest
+
+from switch_core.bridges.collaboration.telegram.adapter import (
+ TelegramAdapter,
+ TelegramConnectionConfig,
+)
+from switch_core.bridges.collaboration.telegram.chunking import (
+ MAX_MESSAGE,
+ chunk_message,
+)
+
+
+def _render(markdown: str) -> str:
+ """Markdown through the adapter's translation, which is what gets split."""
+ adapter = TelegramAdapter(
+ config=TelegramConnectionConfig(bot_token="t", bot_username="b")
+ )
+ return adapter.translate_outbound(markdown)
+
+
+def _tags_balanced(text: str) -> bool:
+ stack: list[str] = []
+ for match in re.finditer(r"<(/?)([a-z]+)[^>]*>", text):
+ if match.group(1):
+ if not stack or stack[-1] != match.group(2):
+ return False
+ stack.pop()
+ else:
+ stack.append(match.group(2))
+ return not stack
+
+
+def _visible(text: str) -> str:
+ return re.sub(r"<[^>]+>", "", text).replace("\n", "")
+
+
+ ("name", "markdown"),
+ [
+ ("code block", "```\n" + "x" * 9000 + "\n```"),
+ ("bold run", "**" + "word " * 1200 + "**"),
+ ("bulleted list", "\n".join(f"- **item {i}** padding" for i in range(300))),
+ ("link text", "[" + "L" * 5000 + "](https://e.com)"),
+ ("unformatted", "y" * 10000),
+ ],
+)
+def test_a_split_never_leaves_broken_markup(name: str, markdown: str) -> None:
+ # A cut landing inside the formatting makes Telegram reject *both* halves,
+ # so a long code block — the most common thing an agent posts — arrives
+ # completely unformatted. Tags open at a cut are closed and reopened.
+ chunks = chunk_message(_render(markdown))
+
+ assert all(len(c) <= 4096 for c in chunks), name
+ assert all(_tags_balanced(c) for c in chunks), name
+
+
+def test_a_split_code_block_resumes_as_a_code_block() -> None:
+ chunks = chunk_message(_render("```\n" + "x" * 9000 + "\n```"))
+
+ assert len(chunks) > 1
+ assert chunks[0].endswith("</pre>")
+ assert chunks[1].startswith("<pre>")
+
+
+def test_splitting_loses_no_text() -> None:
+ body = _render("**Report**\n\n" + "\n".join(f"- line {i}" for i in range(700)))
+
+ chunks = chunk_message(body)
+
+ # `_visible` drops newlines, so this is about characters surviving; the
+ # newline accounting is asserted separately below.
+ assert _visible("".join(chunks)) == _visible(body)
+
+
+def test_a_body_at_exactly_the_cap_is_left_whole() -> None:
+ assert chunk_message("a" * 4096) == ["a" * 4096]
+
+
+def test_markup_too_deep_to_split_degrades_to_plain_text() -> None:
+ # Forcing a cut here severed a tag mid-character and put a bare `<` on the
+ # wire, which Telegram rejects — and the plain-text retry could not
+ # recognise the fragment as a tag either, so the text was mangled too.
+ body = "".join(f"<b>text{i} " for i in range(2000))
+
+ chunks = chunk_message(body)
+
+ assert all(len(c) <= MAX_MESSAGE for c in chunks)
+ assert all(_tags_balanced(c) for c in chunks)
+ assert not any(re.search(r"<[a-z]*$", c) for c in chunks)
+ assert _visible("".join(chunks)).replace("\n", "") == _visible(body).replace(
+ "\n", ""
+ )
+
+
+def test_a_tag_longer_than_a_whole_message_still_carries_its_text() -> None:
+ # No split keeps this markup, so it goes as text — but the link target is
+ # the part a reader cannot recover, so it is spelled out rather than lost.
+ body = _render("[click](https://example.com/" + "a" * 4090 + ")")
+
+ chunks = chunk_message(body)
+
+ assert all(len(c) <= MAX_MESSAGE for c in chunks)
+ assert "click" in chunks[0]
+ assert "example.com" in "".join(chunks)
+
+
+def test_a_blank_line_at_a_boundary_is_not_swallowed() -> None:
+ # Only the single newline the cut is made on is the separator; stripping the
+ # run would merge two paragraphs into one.
+ body = _render("para one\n\n" + "x" * 4200 + "\n\npara two")
+
+ chunks = chunk_message(body)
+
+ assert any("\n\n" in c for c in chunks)
+
+
+def test_splitting_a_list_loses_only_the_separator_newlines() -> None:
+ body = _render("\n".join(f"- **Item {i}**: text" for i in range(2000)))
+
+ chunks = chunk_message(body)
+
+ plain = re.sub(r"<[^>]+>", "", body)
+ lost = plain.count("\n") - sum(
+ re.sub(r"<[^>]+>", "", c).count("\n") for c in chunks
+ )
+ # Exactly one per boundary — each piece is its own message.
+ assert lost == len(chunks) - 1
diff --git a/core/tests/switch_core/bridges/collaboration/test_telegram_provisioning.py b/core/tests/switch_core/bridges/collaboration/test_telegram_provisioning.py
new file mode 100644
index 000000000..b9f0cb69f
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_telegram_provisioning.py
@@ -0,0 +1,216 @@
+"""Channel provisioning, membership and links for the Telegram bridge.
+
+Telegram is the one platform where Switch cannot create the channel: the Bot API
+has no call for it, and none for adding a member either. Most of what follows
+therefore asserts that the adapter refuses clearly rather than appearing to
+succeed — a room that silently never got created is the failure mode worth
+guarding against.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from typing import Any
+
+import pytest
+
+from switch_core.bridges.collaboration.models import ChannelCreationUnsupported
+from switch_core.bridges.collaboration.telegram.adapter import (
+ TelegramAdapter,
+ TelegramConnectionConfig,
+)
+
+SUPERGROUP_ID = "-1001234567890"
+BOT_USERNAME = "acme_switch_bot"
+
+
+def _run(coro: Any) -> Any:
+ loop = asyncio.new_event_loop()
+ try:
+ return loop.run_until_complete(coro)
+ finally:
+ loop.close()
+
+
+class _FakeChat:
+ def __init__(self, chat_type: str, *, username: str | None = None) -> None:
+ self.type = chat_type
+ self.username = username
+ self.title = "somewhere"
+
+
+class _FakeBot:
+ def __init__(self, chat: _FakeChat) -> None:
+ self._chat = chat
+
+ async def get_chat(self, chat_id: Any) -> _FakeChat:
+ return self._chat
+
+
+def _adapter(chat: _FakeChat | None = None) -> TelegramAdapter:
+ adapter = TelegramAdapter(
+ config=TelegramConnectionConfig(bot_token="token", bot_username=BOT_USERNAME)
+ )
+ adapter._bot = _FakeBot(chat if chat is not None else _FakeChat("supergroup"))
+ return adapter
+
+
+# ── Creating chats ───────────────────────────────────────────────────────────
+
+
+ "channel_type", ["channel_public", "channel_private", "group", "direct"]
+)
+def test_creating_a_chat_is_refused_for_every_type(channel_type: Any) -> None:
+ # ChannelCreationUnsupported is a ValueError, which is what turns this into
+ # a 400 carrying the message rather than an opaque 500.
+ with pytest.raises(ChannelCreationUnsupported) as excinfo:
+ _run(_adapter().create_channel("Team room", "topic", channel_type=channel_type))
+
+ # The error is read by an operator, so it has to say what to do instead.
+ message = str(excinfo.value)
+ assert "cannot create chats" in message
+ assert BOT_USERNAME in message
+ assert "Team room" in message
+
+
+def test_creating_a_dm_is_refused_because_the_user_starts_it() -> None:
+ with pytest.raises(ChannelCreationUnsupported, match="initiated by the user"):
+ _run(
+ _adapter().create_dm_channel(
+ agent_name="scout", user_name="alice", user_external_id="7"
+ )
+ )
+
+
+# ── Chat types ───────────────────────────────────────────────────────────────
+
+
+ ("chat_type", "username", "expected"),
+ [
+ ("private", None, "lobby"),
+ ("group", None, "channel_private"),
+ ("supergroup", None, "channel_private"),
+ ("supergroup", "acme_public", "channel_public"),
+ ("channel", None, "channel_private"),
+ ("channel", "acme_news", "channel_public"),
+ ],
+)
+def test_chat_type_maps_to_the_bridges_channel_type(
+ chat_type: str, username: str | None, expected: str
+) -> None:
+ adapter = _adapter(_FakeChat(chat_type, username=username))
+
+ assert _run(adapter.get_channel_type(SUPERGROUP_ID)) == expected
+
+
+def test_a_basic_group_is_private_even_though_it_cannot_hold_a_username() -> None:
+ # A basic group has no username field to consult, so the mapping must not
+ # depend on one.
+ adapter = _adapter(_FakeChat("group", username="ignored"))
+
+ assert _run(adapter.get_channel_type(SUPERGROUP_ID)) == "channel_private"
+
+
+# ── Membership ───────────────────────────────────────────────────────────────
+
+
+def test_adding_users_says_so_rather_than_reporting_a_change_it_cannot_make(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ adapter = _adapter()
+
+ with caplog.at_level(logging.WARNING):
+ _run(adapter.add_users_to_channel(SUPERGROUP_ID, ["alice", "bob"], ["7", "8"]))
+
+ assert "Cannot add alice, bob" in caplog.text
+ assert "invite link" in caplog.text
+
+
+def test_adding_nobody_is_silent(caplog: pytest.LogCaptureFixture) -> None:
+ adapter = _adapter()
+
+ with caplog.at_level(logging.WARNING):
+ _run(adapter.add_users_to_channel(SUPERGROUP_ID, [], []))
+
+ assert caplog.text == ""
+
+
+def test_adding_agents_is_a_no_op_under_the_single_bot_model() -> None:
+ # Every agent posts through the one bot, so there is nothing to add.
+ _run(_adapter().add_agents_to_channel(SUPERGROUP_ID, ["scout", "scribe"]))
+
+
+def test_agent_identities_are_a_no_op_under_the_single_bot_model() -> None:
+ adapter = _adapter()
+
+ _run(adapter.create_agent_identity("scout", "a scout"))
+ _run(adapter.remove_agent_identity("scout"))
+
+ assert _run(adapter.get_channel_agent_names(SUPERGROUP_ID)) == []
+
+
+# ── Links ────────────────────────────────────────────────────────────────────
+
+
+def test_a_private_supergroup_link_carries_a_message_id() -> None:
+ # Bare `t.me/c/<id>` does not reliably resolve — the canonical private form
+ # includes a message id, and opens for members of the chat.
+ assert (
+ _run(_adapter().channel_deeplink(SUPERGROUP_ID))
+ == "https://t.me/c/1234567890/1"
+ )
+
+
+def test_a_public_chat_uses_its_real_address() -> None:
+ # A username gives a link that works in a browser as well as the app, so it
+ # beats the internal form whenever the chat has one.
+ adapter = _adapter(_FakeChat("supergroup", username="acme_public"))
+
+ assert _run(adapter.channel_deeplink(SUPERGROUP_ID)) == "https://t.me/acme_public"
+
+
+def test_a_failed_lookup_still_yields_the_internal_link() -> None:
+ # Losing the button because one API call failed is worse than the link the
+ # chat id alone can produce.
+ adapter = _adapter()
+
+ async def _fail(_chat_id: Any) -> _FakeChat:
+ raise RuntimeError("telegram unreachable")
+
+ adapter._bot.get_chat = _fail # type: ignore[union-attr]
+
+ assert (
+ _run(adapter.channel_deeplink(SUPERGROUP_ID)) == "https://t.me/c/1234567890/1"
+ )
+
+
+def test_a_basic_group_has_no_channel_link() -> None:
+ # A group that has never been upgraded to a supergroup is not addressable
+ # by URL at all, so the caller hides the button rather than showing a dud.
+ adapter = _adapter(_FakeChat("group"))
+
+ assert _run(adapter.channel_deeplink("-987654321")) is None
+
+
+def test_a_one_to_one_chat_has_no_channel_link() -> None:
+ # Better none than a link that opens the wrong place.
+ assert _run(_adapter().channel_deeplink("7")) is None
+
+
+def test_a_malformed_chat_id_has_no_channel_link() -> None:
+ assert _run(_adapter().channel_deeplink("-100not-a-number")) is None
+
+
+def test_an_empty_chat_id_has_no_channel_link() -> None:
+ assert _run(_adapter().channel_deeplink("")) is None
+
+
+def test_the_home_link_normalises_a_configured_at_sign() -> None:
+ adapter = TelegramAdapter(
+ config=TelegramConnectionConfig(bot_token="token", bot_username="@acme_bot")
+ )
+
+ assert _run(adapter.home_deeplink()) == "https://t.me/acme_bot"
diff --git a/core/tests/switch_core/db/stores/test_room_external_channel.py b/core/tests/switch_core/db/stores/test_room_external_channel.py
new file mode 100644
index 000000000..94d8663a7
--- /dev/null
+++ b/core/tests/switch_core/db/stores/test_room_external_channel.py
@@ -0,0 +1,118 @@
+"""Re-pointing a bridged room at a new external channel id.
+
+Telegram reissues a chat's id when a group becomes a supergroup, and the room
+has to follow it or nothing from that chat matches a room again. Against real
+Postgres, because the unique index on (bridge, external channel) is the whole
+reason a re-point can fail.
+"""
+
+from __future__ import annotations
+
+import uuid
+
+import pytest
+from sqlalchemy.exc import IntegrityError
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import Client, CollaborationBridge, Room
+from switch_core.db.stores.room_store import RoomStore
+
+OLD_ID = "-4912345678"
+NEW_ID = "-1009876543210"
+
+
+async def _make_bridge(session: AsyncSession, name: str) -> CollaborationBridge:
+ client = Client(
+ matrix_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",
+ display_name=f"{name} client",
+ type="bridge",
+ password="x",
+ )
+ session.add(client)
+ await session.flush()
+ bridge = CollaborationBridge(
+ type="telegram",
+ display_name=name,
+ connection_config={},
+ client_id=client.id,
+ status="active",
+ )
+ session.add(bridge)
+ await session.flush()
+ return bridge
+
+
+async def _make_room(
+ store: RoomStore,
+ session: AsyncSession,
+ name: str,
+ *,
+ bridge_id: str,
+ external_channel_id: str,
+) -> Room:
+ return await store.create(
+ session,
+ Room(
+ matrix_room_id=f"!{name}:test",
+ name=name,
+ description=f"{name} desc",
+ bridge_id=bridge_id,
+ channel_type="channel_private",
+ external_channel_id=external_channel_id,
+ ),
+ )
+
+
+class TestUpdateExternalChannel:
+ async def test_the_room_is_found_under_its_new_id(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = RoomStore()
+ async with session_factory() as session:
+ bridge = await _make_bridge(session, "telegram-1")
+ room = await _make_room(
+ store, session, "alpha", bridge_id=bridge.id, external_channel_id=OLD_ID
+ )
+ await session.commit()
+
+ await store.update_external_channel(session, room.id, NEW_ID)
+ await session.commit()
+
+ assert (
+ await store.get_by_external_channel(session, bridge.id, OLD_ID)
+ ) is None
+ moved = await store.get_by_external_channel(session, bridge.id, NEW_ID)
+ assert moved is not None
+ assert moved.id == room.id
+ # Only the id moves: it is the same conversation on the same bridge.
+ assert moved.bridge_id == bridge.id
+ assert moved.channel_type == "channel_private"
+
+ async def test_an_id_another_room_holds_is_rejected(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # The caller checks for this first; the index is the backstop, and a
+ # backstop nobody has seen fire is a guess.
+ store = RoomStore()
+ async with session_factory() as session:
+ bridge = await _make_bridge(session, "telegram-2")
+ room = await _make_room(
+ store, session, "beta", bridge_id=bridge.id, external_channel_id=OLD_ID
+ )
+ await _make_room(
+ store, session, "gamma", bridge_id=bridge.id, external_channel_id=NEW_ID
+ )
+ await session.commit()
+
+ # The store flushes, so the index rejects it there rather than at
+ # commit — the caller sees the failure at the call that caused it.
+ with pytest.raises(IntegrityError):
+ await store.update_external_channel(session, room.id, NEW_ID)
+
+ async def test_an_unknown_room_raises_rather_than_passing_quietly(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = RoomStore()
+ async with session_factory() as session:
+ with pytest.raises(ValueError, match="Room not found"):
+ await store.update_external_channel(session, "no-such-room", NEW_ID)
diff --git a/core/tests/switch_core/gateway/test_bridge_install_links.py b/core/tests/switch_core/gateway/test_bridge_install_links.py
new file mode 100644
index 000000000..151a42c09
--- /dev/null
+++ b/core/tests/switch_core/gateway/test_bridge_install_links.py
@@ -0,0 +1,112 @@
+"""Install links reaching the operator dashboard, and failing visibly.
+
+`GET /gateway/collaborations` builds each bridge's "add the app to a chat"
+links from the *live* adapter, the same way it builds the home link. Both ways
+that can come up empty are deliberate — a bridge that is not running has no
+adapter to ask, and an adapter that raises must not take the bridge list down
+with it — so both are pinned here rather than left to be discovered as a blank
+dialog with nothing in the logs.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+import pytest
+
+from switch_core.bridges.collaboration.models import BridgeInstallLink
+from switch_core.gateway.collaborations import _install_links, _install_note
+
+LINK = BridgeInstallLink(
+ key="group",
+ label="Add to a Telegram group",
+ description="Pick a group and confirm.",
+ url="https://t.me/acme_switch_bot?startgroup=switch",
+)
+
+
+class _Lifecycle:
+ """Only the one method the helper reaches for."""
+
+ def __init__(self, adapter: Any) -> None:
+ self._adapter = adapter
+
+ def get_adapter(self, bridge_id: str) -> Any:
+ return self._adapter
+
+
+class _Adapter:
+ def __init__(
+ self,
+ links: list[BridgeInstallLink] | Exception,
+ note: str | Exception | None = None,
+ ) -> None:
+ self._links = links
+ self._note = note
+
+ async def install_links(self) -> list[BridgeInstallLink]:
+ if isinstance(self._links, Exception):
+ raise self._links
+ return self._links
+
+ async def install_note(self) -> str | None:
+ if isinstance(self._note, Exception):
+ raise self._note
+ return self._note
+
+
+async def test_a_running_adapters_links_are_served() -> None:
+ lifecycle = _Lifecycle(_Adapter([LINK]))
+
+ links = await _install_links("bridge-1", lifecycle) # type: ignore[arg-type]
+
+ assert [link.url for link in links] == [LINK.url]
+
+
+async def test_a_bridge_that_is_not_running_offers_none() -> None:
+ # There is no adapter to ask, and a link built from stale config could
+ # point at a bot the bridge no longer uses.
+ lifecycle = _Lifecycle(None)
+
+ assert await _install_links("bridge-1", lifecycle) == [] # type: ignore[arg-type]
+
+
+async def test_an_adapter_that_raises_is_logged_not_swallowed(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ # The dashboard still lists its bridges; the reason the button is missing
+ # is in the log rather than nowhere.
+ lifecycle = _Lifecycle(_Adapter(RuntimeError("telegram is down")))
+
+ with caplog.at_level(logging.WARNING):
+ links = await _install_links("bridge-1", lifecycle) # type: ignore[arg-type]
+
+ assert links == []
+ assert "bridge-1" in caplog.text
+
+
+async def test_the_note_for_what_no_link_covers_is_served() -> None:
+ lifecycle = _Lifecycle(_Adapter([LINK], "Channels are added by hand."))
+
+ assert await _install_note("bridge-1", lifecycle) == ( # type: ignore[arg-type]
+ "Channels are added by hand."
+ )
+
+
+async def test_a_bridge_that_is_not_running_has_no_note() -> None:
+ lifecycle = _Lifecycle(None)
+
+ assert await _install_note("bridge-1", lifecycle) is None # type: ignore[arg-type]
+
+
+async def test_a_note_that_raises_is_logged_not_swallowed(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ lifecycle = _Lifecycle(_Adapter([LINK], RuntimeError("telegram is down")))
+
+ with caplog.at_level(logging.WARNING):
+ note = await _install_note("bridge-1", lifecycle) # type: ignore[arg-type]
+
+ assert note is None
+ assert "bridge-1" in caplog.text
diff --git a/core/tests/switch_core/gateway/test_collaborations_authz.py b/core/tests/switch_core/gateway/test_collaborations_authz.py
index 005bdda78..6f9d48204 100644
--- a/core/tests/switch_core/gateway/test_collaborations_authz.py
+++ b/core/tests/switch_core/gateway/test_collaborations_authz.py
@@ -145,6 +145,12 @@ class _NoRunningBridges:
def get_adapter(self, bridge_id: str) -> None:
return None
+ def supports_channel_creation(self, bridge_type: str) -> bool:
+ """Answered from the registered adapter class in production, so it holds
+ for a stopped bridge — which is the whole point of it not coming from a
+ live adapter."""
+ return True
+
async def test_set_default_promotes_and_demotes(
session_factory: async_sessionmaker[AsyncSession],
diff --git a/core/tests/switch_core/test_dm_rooms.py b/core/tests/switch_core/test_dm_rooms.py
index 0f831871d..a41e5cdd4 100644
--- a/core/tests/switch_core/test_dm_rooms.py
+++ b/core/tests/switch_core/test_dm_rooms.py
@@ -6,6 +6,7 @@ from typing import Any
import pytest
from switch_core.bridges.collaboration.adapter import CollaborationAdapter
+from switch_core.bridges.collaboration.models import ChannelCreationUnsupported
from switch_core.room_service import RoomCreateConfig, RoomService
# A DM room is a 1:1 "direct" room provisioned outbound onto a bridge (on Slack,
@@ -107,12 +108,32 @@ class _FakeLifecycle:
return self._bridges.get(bridge_id)
-def _dm_service(*, known_users: dict[str, str]) -> tuple[RoomService, _FakeBridge]:
+class _FakeBridgeStore:
+ """Reports a connection an operator has left able to create channels, so
+ these tests exercise the DM path rather than the capability guard."""
+
+ def __init__(self, *, channel_creation_enabled: bool) -> None:
+ self._enabled = channel_creation_enabled
+
+ async def get(self, session: Any, bridge_id: str) -> Any:
+ return SimpleNamespace(
+ id=bridge_id,
+ display_name=bridge_id,
+ channel_creation_enabled=self._enabled,
+ )
+
+
+def _dm_service(
+ *, known_users: dict[str, str], channel_creation_enabled: bool = True
+) -> tuple[RoomService, _FakeBridge]:
bridge = _FakeBridge(known_users)
svc = object.__new__(RoomService)
svc._session_factory = lambda: _FakeSessionCM() # type: ignore[assignment]
svc._agent_store = _FakeAgentStore({"a1": "agent.bot"}) # type: ignore[assignment]
svc._collab_lifecycle = _FakeLifecycle({"bridge-1": bridge}) # type: ignore[assignment]
+ svc._collab_bridge_store = _FakeBridgeStore( # type: ignore[assignment]
+ channel_creation_enabled=channel_creation_enabled
+ )
return svc, bridge
@@ -126,13 +147,26 @@ async def test_create_dm_room_fails_when_user_unknown_to_bridge() -> None:
assert bridge.dm_calls == []
+async def test_create_dm_room_refused_when_operator_withheld_channel_creation() -> None:
+ # Opening a DM makes a conversation on the platform just as a channel does,
+ # so the operator's switch governs it too.
+ svc, bridge = _dm_service(
+ known_users={"alice": "U1"}, channel_creation_enabled=False
+ )
+
+ with pytest.raises(ChannelCreationUnsupported, match="turned off"):
+ await svc.create_room(_dm_config(agent_ids=["a1"], user_names=["alice"]))
+
+ assert bridge.dm_calls == []
+
+
# ── Base adapter (non-Slack platforms) ───────────────────────────────────────
async def test_base_adapter_rejects_dm_channel_creation() -> None:
# The default raises so platforms whose DMs are user-initiated (Mattermost)
# fail loud rather than silently no-op.
- with pytest.raises(NotImplementedError, match="cannot create DM channels"):
+ with pytest.raises(ChannelCreationUnsupported, match="cannot create DM channels"):
await CollaborationAdapter.create_dm_channel(
SimpleNamespace(),
agent_name="a",
diff --git a/core/tests/switch_core/test_room_service_change_bridge.py b/core/tests/switch_core/test_room_service_change_bridge.py
index de1d1c3eb..86e1eb79e 100644
--- a/core/tests/switch_core/test_room_service_change_bridge.py
+++ b/core/tests/switch_core/test_room_service_change_bridge.py
@@ -5,6 +5,7 @@ from typing import Any
import pytest
+from switch_core.bridges.collaboration.models import ChannelCreationUnsupported
from switch_core.room_service import RoomService
@@ -127,6 +128,23 @@ class _FakeMatrix:
self._events.append(("kick", matrix_user_id))
+class _FakeBridgeStore:
+ """Whether an operator has left this connection able to create channels.
+
+ Moving a room to a bridge provisions a channel on it, so the same switch
+ that governs creating a room governs this."""
+
+ def __init__(self, *, channel_creation_enabled: bool) -> None:
+ self._enabled = channel_creation_enabled
+
+ async def get(self, session: Any, bridge_id: str) -> Any:
+ return SimpleNamespace(
+ id=bridge_id,
+ display_name=bridge_id,
+ channel_creation_enabled=self._enabled,
+ )
+
+
def _build_service(
*,
room: Any,
@@ -134,6 +152,7 @@ def _build_service(
agent_names: dict[str, str],
bridges: dict[str, Any],
events: list[Any],
+ channel_creation_enabled: bool = True,
) -> tuple[RoomService, _FakeRoomStore]:
room_store = _FakeRoomStore(room, agent_ids)
svc = object.__new__(RoomService)
@@ -142,6 +161,9 @@ def _build_service(
svc._agent_store = _FakeAgentStore(agent_names) # type: ignore[assignment]
svc._collab_lifecycle = _FakeLifecycle(bridges) # type: ignore[assignment]
svc._matrix_admin = _FakeMatrix(events) # type: ignore[assignment]
+ svc._collab_bridge_store = _FakeBridgeStore( # type: ignore[assignment]
+ channel_creation_enabled=channel_creation_enabled
+ )
return svc, room_store
@@ -338,3 +360,38 @@ class TestChangeBridge:
with pytest.raises(ValueError, match="already bound"):
await svc.change_bridge("room-1", bridge_id="bridge-x")
+
+ async def test_move_refused_when_the_target_may_not_create_channels(self) -> None:
+ # Moving a room to a bridge provisions a channel on it, so a connection
+ # an operator has withheld channel creation from must refuse here too —
+ # before the old binding is touched, so a refused move changes nothing.
+ events: list[Any] = []
+ room = SimpleNamespace(
+ id="room-1",
+ name="Work",
+ description="d",
+ matrix_room_id="!mx:switch.local",
+ bridge_id="bridge-old",
+ channel_type="channel_public",
+ external_channel_id="chan-old",
+ )
+ new_bridge = _FakeBridgeCore(
+ events, matrix_user_id="@bot-new:switch.local", new_channel_id="chan-new"
+ )
+ svc, room_store = _build_service(
+ room=room,
+ agent_ids=[],
+ agent_names={},
+ bridges={
+ "bridge-new": new_bridge,
+ "bridge-old": _FakeBridgeCore(events, matrix_user_id="@bot-old:s"),
+ },
+ events=events,
+ channel_creation_enabled=False,
+ )
+
+ with pytest.raises(ChannelCreationUnsupported, match="turned off"):
+ await svc.change_bridge("room-1", bridge_id="bridge-new")
+
+ assert room_store.update_bridge_calls == []
+ assert events == []
diff --git a/core/uv.lock b/core/uv.lock
index 81ec3ff16..936e084bb 100644
--- a/core/uv.lock
+++ b/core/uv.lock
@@ -2100,6 +2100,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/15/fe/9a58cb6eec633ff6afae150ca53c16f8cc8b65862ccb3d088051efdfceb7/python_socks-2.8.1-py3-none-any.whl", hash = "sha256:28232739c4988064e725cdbcd15be194743dd23f1c910f784163365b9d7be035", size = 55087, upload-time = "2026-02-16T05:23:59.147Z" },
]
+[[package]]
+name = "python-telegram-bot"
+version = "21.11.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "httpx" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/4c/74/3ebdc3ee2c323b4577fcc57542f71aa064ac9dac154af0c2f5805e1b9fbd/python_telegram_bot-21.11.1.tar.gz", hash = "sha256:2abda5202f27a838f35e8140e5292af0f4f8fad6c2e5123b2defadd5f4e8ca02", size = 442624, upload-time = "2025-03-01T11:46:54.735Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/27/3b/8f6372e580ba4514335873f64924eb80b80c3d3f8359c2bb2e07bb6d01b9/python_telegram_bot-21.11.1-py3-none-any.whl", hash = "sha256:17f933a7a0569f519d9b672e06d71c29ab3688f1ec575ba59a3ca37922481113", size = 676058, upload-time = "2025-03-01T11:46:52.001Z" },
+]
+
[[package]]
name = "pywin32"
version = "311"
@@ -2453,6 +2465,7 @@ dependencies = [
{ name = "pydantic" },
{ name = "pydantic-settings" },
{ name = "pyjwt" },
+ { name = "python-telegram-bot" },
{ name = "pyyaml" },
{ name = "slack-sdk" },
{ name = "sqlalchemy", extra = ["asyncio"] },
@@ -2488,6 +2501,7 @@ requires-dist = [
{ name = "pydantic", specifier = ">=2,<3" },
{ name = "pydantic-settings", specifier = ">=2.14.2,<3.0" },
{ name = "pyjwt", specifier = ">=2.9,<3" },
+ { name = "python-telegram-bot", specifier = ">=21,<22" },
{ name = "pyyaml", specifier = ">=6,<7" },
{ name = "slack-sdk", specifier = ">=3.41.0" },
{ name = "sqlalchemy", extras = ["asyncio"], specifier = ">=2,<3" },
diff --git a/deploy/remote/helm/switch/values.yaml b/deploy/remote/helm/switch/values.yaml
index 3f75b65bc..8082cfb9f 100644
--- a/deploy/remote/helm/switch/values.yaml
+++ b/deploy/remote/helm/switch/values.yaml
@@ -87,8 +87,9 @@ switchCore:
# Public base URL the gateway is served on (used for links / OIDC redirects).
frontendBaseUrl: ""
# Public origin (scheme + host, no path) of the gateway HTTP API itself, used
- # to build the switchdash:// deeplink HTTP redirect so the "Open in SwitchDash"
- # link is clickable on Discord and other http-only platforms. Leave empty to
+ # to build the switchdash:// deeplink HTTP redirect so the "Open in Switch
+ # Console" link is clickable on Discord, Telegram and other http-only
+ # platforms. Leave empty to
# post the raw switchdash:// deeplink.
gatewayPublicUrl: ""
# Set the Secure flag on the switch_auth session cookie. True here because the
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index df8ed2ab4..9c7760223 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -17,7 +17,7 @@ AI agents and humans collaborate in shared **rooms**, using a Matrix homeserver
([Tuwunel](https://github.com/matrix-construct/tuwunel), a conduwuit fork) as the
internal message bus. Agents connect through an **Agent Bridge** (an HTTP API and
an MCP server); humans participate from the chat tools they already use
-(Slack, Mattermost, Discord, Teams) through **collaboration bridges** that relay
+(Slack, Mattermost, Discord, Teams, Telegram) through **collaboration bridges** that relay
messages both ways. Operators manage the platform through a **gateway** API and
its dashboard.
@@ -52,6 +52,7 @@ flowchart LR
MM[Mattermost]
DC[Discord]
TE[Teams]
+ TG[Telegram]
end
subgraph agents["AI agents (connect via MCP or HTTP)"]
@@ -188,8 +189,9 @@ sequenceDiagram
Inbound messages do **not** arrive through the `/gateway/collaborations` admin
API (that only does bridge CRUD). Each adapter owns its transport:
-Slack (Socket Mode WebSocket), Mattermost (WebSocket), and Discord (Gateway
-WebSocket) hold **authenticated outbound connections**; Teams is the exception —
+Slack (Socket Mode WebSocket), Mattermost (WebSocket), Discord (Gateway
+WebSocket) and Telegram (Bot API long polling) hold **authenticated outbound
+connections**; Teams is the exception —
it self-hosts an HTTP listener (default port 3978) for Bot Framework activities
and Graph notifications.
[`bridges/collaboration/bridge_core.py`](../core/switch_core/bridges/collaboration/bridge_core.py)
@@ -266,7 +268,10 @@ themselves.
On Discord the same registry is also published as native slash commands
([`bridges/collaboration/discord/slash.py`](../core/switch_core/bridges/collaboration/discord/slash.py)):
a slash invocation is reassembled into the positional form the `!` handlers
-already parse, so both entry points reach one implementation.
+already parse, so both entry points reach one implementation. Telegram
+publishes the same registry to its command menu, where `/` is the platform's
+own convention and a `/`-prefixed message is one of the few things a bot is
+delivered without being an administrator of the chat.
### 4.5 Room provisioning & lifecycle
@@ -297,7 +302,7 @@ Everything ingress-facing, and where to find it:
| Session deeplink | `/deeplink/session` | public | `bridges/agent/deeplink.py` |
| Collaboration admin | `/gateway/collaborations` | cookie JWT (reads) / + admin (writes) | `gateway/collaborations.py` |
| Gateway API | `/gateway/*` | cookie JWT (`switch_auth`) | `gateway/app.py`, `gateway/auth.py` |
-| Platform ingress | adapter transports (Slack/MM/Discord WebSocket; Teams HTTP :3978) | platform token / Teams JWT+HMAC | `bridges/collaboration/*/adapter.py` |
+| Platform ingress | adapter transports (Slack/MM/Discord WebSocket; Telegram long polling; Teams HTTP :3978) | platform token / Teams JWT+HMAC | `bridges/collaboration/*/adapter.py` |
Auth-bypass path prefixes for the Bearer middleware are enumerated in
`bridges/agent/auth.py` (`PUBLIC_PATH_PREFIXES`): `/health`, `/.well-known`,
diff --git a/docs/bridges/DISCORD_SETUP.md b/docs/bridges/DISCORD_SETUP.md
index a346ccb3e..8dea26e05 100644
--- a/docs/bridges/DISCORD_SETUP.md
+++ b/docs/bridges/DISCORD_SETUP.md
@@ -63,7 +63,7 @@ the server icon → **Copy Server ID**. This is the `guild_id`.
## 5. Onboard the bridge in Switch
As a gateway admin, onboard the bridge from the **operator dashboard**:
-**Messaging Apps → Add bridge → Discord**, give it a display name (e.g. "Acme
+**Messaging Apps → Register messaging app → Discord**, give it a display name (e.g. "Acme
Discord"), and fill in the fields below.
Fields (`DiscordConnectionConfig`):
@@ -112,7 +112,8 @@ bridge fixes it.
## Clickable "Open in Switch Console" links (`GATEWAY_PUBLIC_URL`)
Discord only linkifies `http(s)`, so a raw `switchdash://session?…` deeplink
-renders as plain text. Set **`GATEWAY_PUBLIC_URL`** on switch-core to the Switch
+renders as plain text; the bridge logs a warning at startup when it is running
+without this set. Set **`GATEWAY_PUBLIC_URL`** on switch-core to the Switch
API's public origin — scheme + host only, **no path** — the same host Switch Console
reports as its `server` (distinct from the operator UI):
diff --git a/docs/bridges/MATTERMOST_SETUP.md b/docs/bridges/MATTERMOST_SETUP.md
index 365a2480c..1d69ce2f0 100644
--- a/docs/bridges/MATTERMOST_SETUP.md
+++ b/docs/bridges/MATTERMOST_SETUP.md
@@ -25,7 +25,7 @@ required**.
## 2. Onboard the bridge in Switch
As a gateway admin, onboard the bridge from the **operator dashboard**:
-**Messaging Apps → Add bridge → Mattermost**, give it a display name (e.g. "Acme
+**Messaging Apps → Register messaging app → Mattermost**, give it a display name (e.g. "Acme
Mattermost"), and fill in the fields below.
Fields (`MattermostConnectionConfig`):
diff --git a/docs/bridges/README.md b/docs/bridges/README.md
index e895d9c57..c000c9670 100644
--- a/docs/bridges/README.md
+++ b/docs/bridges/README.md
@@ -1,7 +1,7 @@
# Collaboration bridge setup
A **collaboration bridge** is a two-way relay between an external chat platform
-(Slack, Mattermost, Microsoft Teams, Discord) and Switch's internal Matrix
+(Slack, Mattermost, Microsoft Teams, Discord, Telegram) and Switch's internal Matrix
rooms. Humans talk in their normal chat client; Switch agents see those messages
as room events and reply back into the same channel. Each external channel maps
to a Switch room, and each Switch agent is presented in the channel under its own
@@ -16,6 +16,7 @@ shared onboarding model, then the per-platform guide:
| Mattermost | [`MATTERMOST_SETUP.md`](MATTERMOST_SETUP.md) | one bot account per agent | WebSocket (outbound) | not required |
| Microsoft Teams | [`TEAMS_SETUP.md`](TEAMS_SETUP.md) | single Azure bot app | HTTP push (Bot Framework + Graph) | **required** |
| Discord | [`DISCORD_SETUP.md`](DISCORD_SETUP.md) | single bot app | Gateway WebSocket (outbound) | not required |
+| Telegram | [`TELEGRAM_SETUP.md`](TELEGRAM_SETUP.md) | single bot, name in the message body | long polling (outbound) | not required |
## The onboarding model (same for every bridge)
@@ -25,37 +26,74 @@ credentials live per-bridge in the bridge's stored `connection_config` (a JSONB
column) — **never** in global environment/config. Onboarding one platform never
touches another.
-Onboard a bridge from the **operator dashboard**: **Messaging Apps → Add
-bridge**, pick the platform, and fill in the form. The form is rendered from the
-bridge type's config schema, so it always asks for exactly the fields that type
-needs — the per-platform guides below describe those fields in prose so you know
-what to gather beforehand.
+Onboard a bridge from the **operator dashboard**: **Messaging Apps → Register
+messaging app**, pick the platform, and fill in the form. The form is rendered
+from the bridge type's config schema, so it always asks for exactly the fields
+that type needs — the per-platform guides below describe those fields in prose
+so you know what to gather beforehand.
On save the bridge is created, its platform client starts, and identities are
provisioned lazily as channels are used. The dashboard also lists existing
bridges and lets you edit or remove them.
+**Adding the app to a chat.** Where the platform can express that as a single
+URL that works everywhere, the bridge's row offers an **Add to a chat** link:
+pick the chat, confirm, done. Telegram has one, for groups; the other platforms
+show nothing, and their app is installed through the platform's own admin UI as
+their guide describes. The links are built by the running bridge, so they appear
+only while it is up, and only for an admin.
+
### Registered bridge types
-`slack`, `mattermost`, `teams`, `discord`. The dashboard's Add-bridge form lists
-the live set and the fields each one requires.
+`slack`, `mattermost`, `teams`, `discord`, `telegram`. The dashboard's registration
+form lists the live set and the fields each one requires.
## Once a bridge is live
- **Rooms.** Depending on the platform, a Switch room is created for a channel
- either when the bot is added to it (Slack, Mattermost, Teams) or lazily on the
- first bridged message (Discord — it has no "app added to channel" signal).
- Existing Switch rooms can also be bound to a channel at room-creation time.
+ either when the bot is added to it (Slack, Mattermost, Teams, Telegram) or
+ lazily on the first bridged message (Discord — it has no "app added to channel"
+ signal). Existing Switch rooms can also be bound to a channel at room-creation
+ time. See **Channel creation** below for the other direction — Switch making
+ the channel — which not every connection can or may do.
- **Addressing agents.** Users `@mention` an agent by name in the channel to
address it; unaddressed chatter is bridged as context. In-room commands (e.g.
- `!invite-agent`) work on every platform. Slack and Discord additionally expose
- them as **native slash commands** (`/invite-agent`) routed into the same
- handler — declared in the app manifest on Slack, registered automatically per
- guild on Discord.
+ `!invite-agent`) work on every platform. Slack, Discord and Telegram
+ additionally expose them as **native slash commands** (`/invite-agent`) routed
+ into the same handler — declared in the app manifest on Slack, registered
+ automatically per guild on Discord, and accepted alongside `!` on Telegram,
+ where `/` is the platform's own convention.
- **"Open in Switch Console" links.** Agents surface a `switchdash://…` deeplink with
- their runtime status. Platforms that only linkify `http(s)` (notably Discord)
- need `GATEWAY_PUBLIC_URL` set so Switch can rewrite it to a clickable
- `https://<switch-api-host>/deeplink/session?…` redirect. See the Discord guide.
+ their runtime status. Platforms that only render `http(s)` links (Discord and
+ Telegram) need `GATEWAY_PUBLIC_URL` set so Switch can rewrite it to a clickable
+ `https://<switch-api-host>/deeplink/session?…` redirect; the bridge logs a
+ warning at startup when one of those platforms is running without it. Unset,
+ the address is posted as tap-to-copy text rather than as a link the platform
+ would silently discard. See the Discord or Telegram guide.
+
+### Channel creation
+
+Creating a Switch room normally creates the channel to go with it. Whether a
+connection will do that has two halves, and both must be true:
+
+- **Can the platform?** A fixed fact about the platform, not a setting.
+ Telegram is the one that cannot: the Bot API has no call to create a chat, so
+ a Telegram chat is always made in a Telegram client and adopted. Every other
+ platform can.
+- **May this connection?** A per-connection switch, set when you register a
+ messaging app and changeable afterwards on its row in **Messaging Apps**.
+ It defaults on. Turn it off where the bot holds no such permission on the
+ platform, or where channels are meant to be made by people rather than
+ appearing from Switch. It can only ever narrow the first half — a connection
+ cannot be granted an ability its platform does not have, and trying is
+ refused rather than stored.
+
+The answer reaches everyone who acts on it. The dashboard and Switch Console do
+not offer "create a new channel" for a connection that will not, and say which
+of the two reasons applies. `list_bridges` carries `can_create_channels`, so an
+agent can pick a bridge that works rather than discovering it by failing. And a
+create that is refused is a `400` explaining what to do instead — make the
+channel on the platform, add the app to it, and Switch adopts it as a room.
## Deployment knobs
diff --git a/docs/bridges/SLACK_SETUP.md b/docs/bridges/SLACK_SETUP.md
index d75ac07b6..abcce2e80 100644
--- a/docs/bridges/SLACK_SETUP.md
+++ b/docs/bridges/SLACK_SETUP.md
@@ -146,7 +146,7 @@ Regardless of how you created the app:
## 3. Onboard the bridge in Switch
As a gateway admin, onboard the bridge from the **operator dashboard**:
-**Messaging Apps → Add bridge → Slack**, give it a display name (e.g. "Acme
+**Messaging Apps → Register messaging app → Slack**, give it a display name (e.g. "Acme
Slack"), and fill in the fields below.
Fields (`SlackConnectionConfig`):
diff --git a/docs/bridges/TEAMS_SETUP.md b/docs/bridges/TEAMS_SETUP.md
index d516150f2..235dec415 100644
--- a/docs/bridges/TEAMS_SETUP.md
+++ b/docs/bridges/TEAMS_SETUP.md
@@ -55,7 +55,7 @@ separate ops task before you can onboard the bridge.
## Onboard the bridge in Switch
As a gateway admin, onboard the bridge from the **operator dashboard**:
-**Messaging Apps → Add bridge → Teams**, give it a display name (e.g. "Acme
+**Messaging Apps → Register messaging app → Teams**, give it a display name (e.g. "Acme
Teams"), and fill in the fields below.
Fields (`TeamsConnectionConfig`):
diff --git a/docs/bridges/TELEGRAM_SETUP.md b/docs/bridges/TELEGRAM_SETUP.md
new file mode 100644
index 000000000..563a272cf
--- /dev/null
+++ b/docs/bridges/TELEGRAM_SETUP.md
@@ -0,0 +1,303 @@
+# Telegram collaboration bridge setup
+
+Connects Telegram groups and channels to Switch. A **single bot** backs every
+Switch agent. Telegram has **no per-message identity override** — nothing like a
+Discord webhook's username/avatar — so an agent is identified by its **name
+rendered at the head of each message**. Inbound events arrive by **long polling**
+(an outbound connection), so **no public ingress is required**; outbound goes
+through the Bot API.
+
+Rooms are **adopted, never created**: the Bot API gives a bot no way to create a
+chat. A chat's Switch room is provisioned when the bot is **added to the group**
+(Telegram does signal this, unlike Discord) or on the first bridged message.
+
+Setup is one BotFather setting, once, and then adding the bot to each chat. The
+bot is never promoted, and needs no permissions in a group.
+
+## Prerequisites
+
+- A Telegram account, to talk to [@BotFather](https://t.me/BotFather).
+- A Telegram group or channel you can add a bot to.
+- The Switch gateway reachable by an admin to onboard the bridge.
+
+## 1. Create the bot and turn Group Privacy off
+
+1. Open [@BotFather](https://t.me/BotFather) in any Telegram client and send
+ `/newbot`.
+2. Give it a display name (e.g. "Agent Switch") and a username ending in `bot`
+ (e.g. `acme_switch_bot`). The username is the `bot_username`.
+3. BotFather replies with the **token** — this is the `bot_token`. It has the
+ shape `<bot id>:<hmac>`. Treat it like a password; anyone holding it controls
+ the bot. Do not paste it into a chat, a ticket or a room, and revoke it with
+ BotFather's `/revoke` if you ever do.
+4. **Turn Group Privacy off**, before adding the bot anywhere:
+ `/mybots` → the bot → **Bot Settings** → **Group Privacy** → **Turn off**.
+
+**Why, and why now.** Telegram runs bots in *privacy mode* by default: in a
+group a bot is given only messages that start with `/`, replies to its own
+messages, and messages that tag it. A bridge that cannot see the conversation is
+a bridge in name only. Telegram reads this setting **when the bot joins a chat**,
+so doing it first means every group you add the bot to afterwards just works;
+doing it later means removing the bot from each existing group and adding it
+back.
+
+There is one alternative, and it is worse for most people: a bot that is an
+**administrator** of a chat is exempt from privacy mode whatever the setting
+says. That is a promotion per group instead of a setting per bot, it converts a
+basic group into a supergroup, and Telegram's "add as admin" chat picker leaves
+basic groups out — so it is offered as a repair for a single chat (below), not
+as the way in.
+
+5. As a gateway admin, onboard the bridge from the **operator dashboard**:
+ **Messaging Apps → Register messaging app → Telegram**, give it a display
+ name (e.g. "Acme Telegram"), and fill in the fields below.
+
+Fields (`TelegramConnectionConfig`):
+
+| Field | Required | Description |
+| --- | --- | --- |
+| `bot_token` | yes | Bot token from BotFather, shaped `<bot id>:<hmac>`. |
+| `bot_username` | yes | The bot's username, with or without the leading `@`. Used to build `t.me` links and to spot when the bot itself is tagged. |
+
+On success the bridge starts polling.
+
+## 2. Link a chat to Switch — from Telegram
+
+**This is the normal way, and it needs nothing from Switch.** In any Telegram
+client:
+
+1. Create a group, or open one you already have.
+2. Add the bot to it like any other member: the group's title → **Add Members**
+ → search for `@acme_switch_bot` → confirm.
+3. That is the whole of it. Telegram tells the bridge it was added, Switch
+ creates a room for the chat, and the bot posts in the group saying whether
+ it can see the conversation. The room appears in the dashboard and in
+ Switch Console on its own.
+
+The bot needs **no permissions and no admin status** in a group. It is a
+member, like anyone else.
+
+A room made this way is a room like any other — add agents to it with
+`!invite-agent @agent-name` in the chat (see [Slash commands](#slash-commands)
+for the `/` forms), or from the dashboard.
+
+**Nothing is created from the Switch side.** Switch cannot make a Telegram
+chat — the Bot API has no call for it — so the chat always exists first and
+Switch adopts it. That is recorded against the connection rather than left to
+be discovered: a Telegram connection reports that it cannot create channels,
+the room forms in the dashboard and Switch Console do not offer the option, and
+an agent calling `create_room` on it is told the same in the error rather than
+getting a failure it cannot interpret. See
+[Channel creation](README.md#channel-creation) for the setting that carries
+this, which applies to every platform.
+
+## 3. Or add the bot from the dashboard
+
+The same thing, one click, when you would rather start from Switch.
+
+On the bridge's row in **Messaging Apps**, the link icon opens **Add to a chat**
+with a single link: **Add to a Telegram group**. It lists every group you can add
+a member to. Pick one and confirm — again, no permissions. Switch creates the
+room as the bot lands.
+
+The icon is shown to admins, and only while the bridge is running — the link is
+built by the live bridge, so a bridge that failed to start offers none.
+
+There is deliberately **no one-click link for a channel**. Telegram's
+`?startgroup` link needs no special parameter and works everywhere, but adding a
+bot to a channel requires the `admin=` parameter, which not every Telegram
+client implements — the ones that do not simply open a chat with the bot, which
+is indistinguishable from a link that does nothing. Rather than ship a link that
+works for some people, channels are added by hand (below).
+
+## 4. Adding the bot to a broadcast channel
+
+A channel is not a group, and Telegram admits a bot to one as an administrator
+or not at all. In the channel: **Administrators** → **Add Admin** → search for
+the bot → grant **Post Messages**, **Edit Messages** and **Delete Messages**.
+Nothing else is needed, and Switch adopts the channel as a room the moment the
+bot lands.
+
+A bot cannot be added to a chat by Switch, and it cannot add anyone else: people
+join from a Telegram client or an invite link.
+
+## Mention-only chats, and how to repair one
+
+A chat where privacy mode is still in force still works, in a reduced way
+Telegram enforces before anything reaches Switch. The bot receives:
+
+- messages that tag it (`@acme_switch_bot`) or tag an agent whose name appears
+ in the same message,
+- replies to its own messages,
+- `/` commands.
+
+It does **not** receive ordinary conversation, so agents will not follow a
+discussion nobody addresses them in. That is a supported way to run — some
+groups would rather the bot saw only what is aimed at it — and it is disclosed
+rather than left to be discovered: the bot posts a notice in the chat saying it
+can only see messages that tag it, and the bridge logs a warning naming each
+such chat at startup.
+
+You will land here if the bot was added to the chat **before** Group Privacy was
+turned off, since Telegram reads that setting at join time. Two ways out:
+
+- **Every chat, once** — turn Group Privacy off (step 1), then remove the bot
+ from the affected chat and add it back.
+- **This chat, now** — make the bot an administrator of it. No particular right
+ is needed; admin status alone is the exemption. If the chat is a basic group,
+ Telegram converts it to a supergroup and issues a new chat id at that moment —
+ expected, and nothing to do: the room follows the new id and says so.
+
+Either way the bot confirms in the chat that it can now see the conversation,
+and a demotion is announced the same way.
+
+## Clickable "Open in Switch Console" links (`GATEWAY_PUBLIC_URL`)
+
+**Set this one.** On Telegram it is what makes the "Open in Switch Console"
+link a link at all, not a refinement — the bridge logs a warning at startup
+when it is missing.
+
+Telegram renders only `http(s)` and `tg:` URLs. A `switchdash://session?…`
+deeplink is neither, and Telegram does not ignore it politely: depending on the
+client it drops the link and leaves the words behind, or the API rejects the
+whole message. So without this set, the bridge does not offer Telegram a link
+it cannot render — it posts the address as a tap-to-copy code span instead,
+which works but is not a link. With it set, the link is a real one and opens
+Switch Console from the Telegram app and from Telegram Web alike.
+
+Set **`GATEWAY_PUBLIC_URL`** on switch-core to the Switch
+API's public origin — scheme + host only, **no path** — the same host Switch Console
+reports as its `server` (distinct from the operator UI):
+
+```dotenv
+# .env / deployment env
+GATEWAY_PUBLIC_URL=https://switch-api.acme.com
+```
+
+When set, Switch rewrites the deeplink to a clickable
+`https://<switch-api-host>/deeplink/session?…` redirect (a `302` back to the
+`switchdash://` scheme) at runtime-state ingestion — so both the bridged
+working/awaiting-input status message **and** the `!status` command surface a
+clickable link. When unset, the address is posted as a code span — visible and
+tap-to-copy, and disclosed as the fallback it is.
+
+The value is validated at startup: it must be scheme + host only. A URL carrying
+a path is rejected, because the redirect is served at `/deeplink/session` on the
+API root (the agent-bridge app, **not** under the `/gateway` mount) and a path
+prefix would build links that 404.
+
+## Slash commands
+
+`/` is Telegram's own command convention, and the bridge publishes the in-room
+command set to Telegram on every start, so typing `/` in the chat lists them
+with descriptions. Nothing to do in BotFather — `/setcommands` is not needed,
+and anything set there by hand is overwritten on the next start.
+
+Telegram will not accept a hyphen in a registered command, so the hyphenated
+names are published in their underscore spelling. Both resolve to the same
+command, and so does the `!` form:
+
+- `/invite_agent @agent-name` — as offered by the menu, and the form the bot
+ advertises in a room with no agents in it: it is the only one Telegram will
+ autocomplete or render as a tappable command
+- `/invite-agent @agent-name` — typed in full; accepted, but Telegram's client
+ tokenises the command as `/invite` and will not offer it
+- `!invite-agent @agent-name` — Switch's own prefix, works on every platform
+
+The `/` forms matter beyond convenience: in a mention-only chat, a `/`-prefixed
+message is one of the few things the bot receives at all.
+
+### Commands that take an argument
+
+Telegram **sends** a command the instant you tap it in the `/` list — it does
+not put it in the composer for you to finish, and the Bot API has no way to
+declare that a command takes an argument. So tapping `/invite_agent` sends it
+bare.
+
+Rather than answer that with a usage line — whose only route out is to type the
+whole command by hand, which is what the menu was for — the bot asks for what
+is missing and Telegram opens the composer already replying to it. Answer with
+the agent's name alone and the command runs:
+
+> **/invite_agent** needs one more thing — the registered agent to add to this
+> room.
+> Reply to this message with it.
+
+Typing the command with its argument in one go skips the prompt entirely. The
+prompt is one-shot, so a conversation that carries on under it is treated as
+ordinary chat rather than more arguments.
+
+This also works in a mention-only chat: a reply to the bot is one of the few
+things Telegram delivers there.
+
+`/start` is Telegram's own handshake rather than a Switch command — it is what
+the dashboard's install links send once the bot has been added — so the bridge
+answers it itself instead of passing it on as an unknown command.
+
+## One instance per bot token
+
+Telegram delivers each update to **one** long-polling caller and rejects the
+others with a `Conflict`. Two processes sharing a bot token therefore split the
+inbound traffic between them at random, which looks like this: the bridge still
+sends fine, agents still post, but messages from people are seen intermittently
+or not at all.
+
+So:
+
+- **Do not run switch-core with more than one replica** while a Telegram bridge
+ is configured on it.
+- **Give each environment its own bot.** A dev deployment and a production
+ deployment on the same token will steal each other's messages. Make a second
+ bot in BotFather for dev.
+- After a redeploy, make sure the previous instance is actually gone — an old
+ process still holding the token produces exactly this symptom.
+
+The bridge logs an error naming this when Telegram reports the conflict, so
+check the logs for "Another process is polling Telegram" before looking
+anywhere else.
+
+## Notes
+
+- **Room icon.** Switch Console shows a Telegram icon for Telegram rooms
+ (`telegram.svg`, keyed to `bridge_type` `"telegram"`).
+- **"Open in Telegram".** A chat with a public username links straight to
+ `t.me/<name>`. A private supergroup uses Telegram's internal address, which
+ only opens for members of that chat. A **basic group** — one Telegram has
+ never upgraded to a supergroup — has no address at all, so no button is
+ shown; adding enough members, or setting a public link, converts it and the
+ button appears.
+- **A group that becomes a supergroup keeps its room.** Telegram issues a brand
+ new chat id at that moment, and it does it silently — promoting a bot or
+ adding members is enough to trigger it. The bridge follows the change and
+ re-points the room at the new id, then says so in the chat. Before that was
+ automatic the symptom was one-way traffic: sends still arrived, because
+ Telegram forwards them to the new chat, while nothing anyone typed reached
+ Switch again.
+- **Message formatting.** Agent Markdown is converted to the HTML subset Telegram
+ accepts (bold, italic, strikethrough, code, pre, links). Telegram's own
+ MarkdownV2 is deliberately not used: it requires escaping ordinary punctuation
+ and rejects an entire message over one stray character. If Telegram ever
+ refuses the markup anyway, the message is re-sent unformatted and a warning is
+ logged — it is never dropped.
+- **No tables.** Telegram does not render Markdown tables; they arrive as raw
+ `| … |` text. Use one short line per item with bold labels, as on Slack.
+- **Message length.** Telegram rejects anything over 4096 characters, so long
+ agent output is split across several messages on line boundaries.
+- **Threads.** In forum-enabled supergroups, messages carry a real topic id and
+ threading works properly. Elsewhere Telegram has only reply chains, so a
+ threaded reply is anchored to the message being replied to.
+- **Attachments.** Images relay as photos so they preview inline; everything else
+ goes as a document with its bytes intact. Several files sent together arrive as
+ one album (Telegram allows 2–10 items of the same kind). Inbound files are
+ capped at **20MB** — a Bot API limit, regardless of the bridge's own ceiling —
+ and anything over it is disclosed in the room rather than dropped.
+- **Mentions.** People with a public `@username` are mentioned by handle.
+ Everyone else is mentioned by numeric id, which works because Switch supplies
+ the bridge with the known user mapping up front.
+- **DMs.** A 1:1 chat with the bot is bridged, but Switch cannot start one —
+ Telegram DMs are opened by the user. Message the bot first and the conversation
+ is picked up.
+- **Creating channels.** Switch cannot provision a Telegram chat, and says so
+ before you try: the connection reports that it cannot create channels, so the
+ room forms omit the option and `list_bridges` tells an agent the same. Calling
+ it anyway is a `400` naming the chat to make and the bot to add, not a 500.
diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.ts
index 67c34a834..655e3472b 100644
--- a/gateway/src/data/api.ts
+++ b/gateway/src/data/api.ts
@@ -108,14 +108,31 @@ export interface AddressingPolicy {
rules: AddressingRule[];
}
+export interface BridgeInstallLink {
+ key: string;
+ label: string;
+ description: string;
+ url: string;
+}
+
export interface BridgeDetail {
bridge_id: string;
bridge_type: string;
display_name: string;
status: string;
agent_greetings_enabled: boolean;
+ // Whether the platform can create channels at all. Fixed per platform —
+ // not something an operator can change.
+ channel_creation_supported: boolean;
+ // Whether this operator has allowed this connection to create channels.
+ // Only meaningful when channel_creation_supported is true.
+ channel_creation_enabled: boolean;
room_count: number;
created_at: string;
+ // Empty for platforms whose app is installed through their own admin UI.
+ install_links?: BridgeInstallLink[];
+ // What those links do not cover — chats that have to be joined by hand.
+ install_note?: string | null;
}
export interface ExternalUserSummary {
@@ -711,6 +728,8 @@ export async function deleteApiKey(keyId: string): Promise<boolean> {
export interface BridgeTypeInfo {
key: string;
config_schema: ConnectorTypeConfigSchema;
+ // Whether this platform can create channels at all. Fixed per platform.
+ channel_creation_supported: boolean;
}
export async function fetchBridges(): Promise<BridgeDetail[] | null> {
@@ -725,6 +744,9 @@ export async function createBridge(
bridgeType: string,
displayName: string,
connectionConfig: Record<string, unknown>,
+ // Defaults to true on the backend when omitted. Posting true for a platform
+ // that doesn't support channel creation returns 400.
+ channelCreationEnabled?: boolean,
): Promise<BridgeDetail> {
const res = await fetch(`${BASE}/collaborations`, {
method: "POST",
@@ -734,6 +756,7 @@ export async function createBridge(
bridge_type: bridgeType,
display_name: displayName,
connection_config: connectionConfig,
+ channel_creation_enabled: channelCreationEnabled,
}),
});
if (!res.ok) {
@@ -776,9 +799,14 @@ export async function deleteBridge(bridgeId: string): Promise<boolean> {
return res?.ok ?? false;
}
+export interface BridgeUpdateInput {
+ agent_greetings_enabled?: boolean;
+ channel_creation_enabled?: boolean;
+}
+
export async function updateBridge(
bridgeId: string,
- update: { agent_greetings_enabled: boolean },
+ update: BridgeUpdateInput,
): Promise<BridgeDetail | null> {
return fetchJson<BridgeDetail>(`/collaborations/${bridgeId}`, {
method: "PATCH",
diff --git a/gateway/src/pages/collaborations/AddToChatDialog.tsx b/gateway/src/pages/collaborations/AddToChatDialog.tsx
new file mode 100644
index 000000000..d6db590b6
--- /dev/null
+++ b/gateway/src/pages/collaborations/AddToChatDialog.tsx
@@ -0,0 +1,63 @@
+import OpenInNewOutlined from "@mui/icons-material/OpenInNewOutlined";
+import {
+ Alert,
+ Button,
+ Dialog,
+ DialogActions,
+ DialogContent,
+ DialogTitle,
+ Stack,
+ Typography,
+} from "@mui/material";
+import type { BridgeDetail } from "../../data/api";
+
+interface Props {
+ /** The bridge to add to a chat, or null when the dialog is closed. */
+ bridge: BridgeDetail | null;
+ onClose: () => void;
+}
+
+/** "Add this messaging app to a chat", for the bridges that have such a link.
+ *
+ * Everything here comes from the bridge: the adapter decides which links exist
+ * and what each one does, and supplies a note for the kinds of chat no link can
+ * reach. The dialog knows nothing about any particular platform — a bridge with
+ * no links never opens it, because the row shows no button. */
+export default function AddToChatDialog({ bridge, onClose }: Props) {
+ const links = bridge?.install_links ?? [];
+
+ return (
+ <Dialog open={!!bridge} onClose={onClose} maxWidth="sm" fullWidth>
+ <DialogTitle>Add {bridge?.display_name} to a chat</DialogTitle>
+ <DialogContent>
+ <Stack spacing={2.5} sx={{ mt: 0.5 }}>
+ {links.map((link) => (
+ <Stack key={link.key} spacing={1} alignItems="flex-start">
+ <Button
+ variant="contained"
+ startIcon={<OpenInNewOutlined />}
+ href={link.url}
+ target="_blank"
+ rel="noreferrer noopener"
+ >
+ {link.label}
+ </Button>
+ <Typography variant="body2" color="text.secondary">
+ {link.description}
+ </Typography>
+ </Stack>
+ ))}
+
+ {bridge?.install_note && (
+ <Alert severity="info" variant="outlined">
+ {bridge.install_note}
+ </Alert>
+ )}
+ </Stack>
+ </DialogContent>
+ <DialogActions>
+ <Button onClick={onClose}>Close</Button>
+ </DialogActions>
+ </Dialog>
+ );
+}
diff --git a/gateway/src/pages/collaborations/CollaborationsPage.tsx b/gateway/src/pages/collaborations/CollaborationsPage.tsx
index d6243f73c..2ae99d390 100644
--- a/gateway/src/pages/collaborations/CollaborationsPage.tsx
+++ b/gateway/src/pages/collaborations/CollaborationsPage.tsx
@@ -1,3 +1,4 @@
+import AddLinkOutlined from "@mui/icons-material/AddLinkOutlined";
import AddOutlined from "@mui/icons-material/AddOutlined";
import DeleteOutline from "@mui/icons-material/DeleteOutline";
import {
@@ -13,6 +14,7 @@ import {
IconButton,
Stack,
Switch,
+ Tooltip,
Typography,
} from "@mui/material";
import type { GridColDef } from "@mui/x-data-grid";
@@ -22,6 +24,7 @@ import { type BridgeDetail, deleteBridge, updateBridge } from "../../data/api";
import { useAuth } from "../../data/AuthContext";
import { useBridges } from "../../data/hooks";
import { formatDate, titleCase } from "../../theme/hootFormat";
+import AddToChatDialog from "./AddToChatDialog";
import RegisterMessagingAppDialog from "./RegisterMessagingAppDialog";
type BridgeRow = BridgeDetail & { id: string };
@@ -40,6 +43,7 @@ export default function CollaborationsPage() {
const [deleting, setDeleting] = useState(false);
const [savingId, setSavingId] = useState<string | null>(null);
const [registerOpen, setRegisterOpen] = useState(false);
+ const [installTarget, setInstallTarget] = useState<BridgeDetail | null>(null);
const handleDelete = useCallback(async () => {
if (!deleteTarget) return;
@@ -60,6 +64,16 @@ export default function CollaborationsPage() {
[refetch],
);
+ const handleToggleChannelCreation = useCallback(
+ async (bridgeId: string, enabled: boolean) => {
+ setSavingId(bridgeId);
+ await updateBridge(bridgeId, { channel_creation_enabled: enabled });
+ setSavingId(null);
+ refetch();
+ },
+ [refetch],
+ );
+
const columns = useMemo<GridColDef<BridgeRow>[]>(
() => [
{
@@ -105,6 +119,32 @@ export default function CollaborationsPage() {
/>
),
},
+ {
+ field: "channel_creation_enabled",
+ headerName: "Channel creation",
+ width: 160,
+ sortable: false,
+ renderCell: ({ row }: { row: BridgeRow }) => {
+ const control = (
+ <Switch
+ size="small"
+ checked={row.channel_creation_supported && row.channel_creation_enabled}
+ disabled={
+ !isAdmin || savingId === row.bridge_id || !row.channel_creation_supported
+ }
+ onChange={(e) =>
+ handleToggleChannelCreation(row.bridge_id, e.target.checked)
+ }
+ />
+ );
+ if (row.channel_creation_supported) return control;
+ return (
+ <Tooltip title={`${row.display_name} cannot create channels from Switch.`}>
+ <span>{control}</span>
+ </Tooltip>
+ );
+ },
+ },
{
field: "created_at",
headerName: "Created",
@@ -116,19 +156,42 @@ export default function CollaborationsPage() {
{
field: "actions" as const,
headerName: "",
- width: 60,
+ width: 110,
sortable: false,
filterable: false,
+ // Right-aligned and bottom-anchored to the same edge on every
+ // row: rows carry one icon or two depending on whether the
+ // platform offers an install link, and without this the delete
+ // buttons sit at different x positions down the column.
+ align: "right" as const,
renderCell: ({ row }: { row: BridgeRow }) => (
- <IconButton size="small" onClick={() => setDeleteTarget(row)}>
- <DeleteOutline fontSize="small" />
- </IconButton>
+ <Stack
+ direction="row"
+ spacing={0.5}
+ alignItems="center"
+ justifyContent="flex-end"
+ height="100%"
+ >
+ {(row.install_links ?? []).length > 0 && (
+ <Tooltip title="Add this app to a chat">
+ <IconButton
+ size="small"
+ onClick={() => setInstallTarget(row)}
+ >
+ <AddLinkOutlined fontSize="small" />
+ </IconButton>
+ </Tooltip>
+ )}
+ <IconButton size="small" onClick={() => setDeleteTarget(row)}>
+ <DeleteOutline fontSize="small" />
+ </IconButton>
+ </Stack>
),
},
]
: []),
],
- [isAdmin, savingId, handleToggleGreetings],
+ [isAdmin, savingId, handleToggleGreetings, handleToggleChannelCreation],
);
const rows = useMemo<BridgeRow[]>(
@@ -164,6 +227,11 @@ export default function CollaborationsPage() {
onSuccess={() => refetch()}
/>
+ <AddToChatDialog
+ bridge={installTarget}
+ onClose={() => setInstallTarget(null)}
+ />
+
<Dialog open={!!deleteTarget} onClose={() => setDeleteTarget(null)}>
<DialogTitle>Delete collaboration bridge</DialogTitle>
<DialogContent>
diff --git a/gateway/src/pages/collaborations/RegisterMessagingAppDialog.tsx b/gateway/src/pages/collaborations/RegisterMessagingAppDialog.tsx
index 363dc773e..ad58cd5de 100644
--- a/gateway/src/pages/collaborations/RegisterMessagingAppDialog.tsx
+++ b/gateway/src/pages/collaborations/RegisterMessagingAppDialog.tsx
@@ -1,14 +1,17 @@
import {
Alert,
Button,
+ Checkbox,
CircularProgress,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
+ FormControlLabel,
MenuItem,
Stack,
TextField,
+ Typography,
} from "@mui/material";
import { useCallback, useMemo, useState } from "react";
import { type BridgeDetail, createBridge } from "../../data/api";
@@ -34,6 +37,7 @@ export default function RegisterMessagingAppDialog({
const [selectedType, setSelectedType] = useState("");
const [displayName, setDisplayName] = useState("");
const [config, setConfig] = useState<Record<string, string>>({});
+ const [channelCreationEnabled, setChannelCreationEnabled] = useState(true);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -42,11 +46,15 @@ export default function RegisterMessagingAppDialog({
[bridgeTypes, selectedType],
);
const configSchema = selectedTypeInfo?.config_schema;
+ // Unknown until the type list has loaded; assume supported so the checkbox
+ // isn't forced off while that request is in flight.
+ const channelCreationSupported = selectedTypeInfo?.channel_creation_supported ?? true;
const handleTypeChange = useCallback((key: string) => {
// Switching type clears any fields entered for the previous one.
setSelectedType(key);
setConfig({});
+ setChannelCreationEnabled(true);
setError(null);
}, []);
@@ -54,6 +62,7 @@ export default function RegisterMessagingAppDialog({
setSelectedType("");
setDisplayName("");
setConfig({});
+ setChannelCreationEnabled(true);
setError(null);
}, []);
@@ -74,7 +83,12 @@ export default function RegisterMessagingAppDialog({
setSubmitting(true);
setError(null);
try {
- const bridge = await createBridge(selectedType, displayName.trim(), config);
+ const bridge = await createBridge(
+ selectedType,
+ displayName.trim(),
+ config,
+ channelCreationSupported && channelCreationEnabled,
+ );
onSuccess(bridge);
reset();
onClose();
@@ -83,7 +97,17 @@ export default function RegisterMessagingAppDialog({
} finally {
setSubmitting(false);
}
- }, [canSubmit, selectedType, displayName, config, onSuccess, reset, onClose]);
+ }, [
+ canSubmit,
+ selectedType,
+ displayName,
+ config,
+ channelCreationSupported,
+ channelCreationEnabled,
+ onSuccess,
+ reset,
+ onClose,
+ ]);
return (
<Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>
@@ -121,6 +145,25 @@ export default function RegisterMessagingAppDialog({
fullWidth
required
/>
+ <Stack spacing={0.5}>
+ <FormControlLabel
+ control={
+ <Checkbox
+ checked={channelCreationSupported && channelCreationEnabled}
+ disabled={!channelCreationSupported}
+ onChange={(e) => setChannelCreationEnabled(e.target.checked)}
+ />
+ }
+ label="Allow creating channels from Switch"
+ />
+ {!channelCreationSupported && (
+ <Typography variant="caption" color="text.secondary">
+ {humanize(selectedType)} has no way to create channels from
+ Switch, so this connection can only be used with existing
+ channels.
+ </Typography>
+ )}
+ </Stack>
{configSchema &&
Object.entries(configSchema.properties).map(([field, prop]) => (
<TextField
diff --git a/gateway/src/pages/rooms/RoomCreateFormBody.tsx b/gateway/src/pages/rooms/RoomCreateFormBody.tsx
index ac1785df4..59601189d 100644
--- a/gateway/src/pages/rooms/RoomCreateFormBody.tsx
+++ b/gateway/src/pages/rooms/RoomCreateFormBody.tsx
@@ -24,7 +24,7 @@ import {
} from "@mui/material";
import AddIcon from "@mui/icons-material/Add";
import DeleteOutline from "@mui/icons-material/DeleteOutline";
-import { useCallback, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router";
import { type RoomRoleSpec, createRoom } from "../../data/api";
import { AccessSelect } from "../../components/AccessControls";
@@ -65,6 +65,34 @@ export default function RoomCreateFormBody() {
const hasBridge = !!bridgeId;
+ const selectedBridge = useMemo(
+ () => (bridges ?? []).find((b) => b.bridge_id === bridgeId),
+ [bridges, bridgeId],
+ );
+
+ // True when this connection cannot be used to create a new channel, either
+ // because the platform has no such capability or because an admin has
+ // turned it off for this connection.
+ const channelCreationBlocked =
+ !!selectedBridge &&
+ !(selectedBridge.channel_creation_supported && selectedBridge.channel_creation_enabled);
+
+ const channelCreationBlockedReason = useMemo(() => {
+ if (!selectedBridge || !channelCreationBlocked) return null;
+ if (!selectedBridge.channel_creation_supported) {
+ return `${selectedBridge.display_name} cannot create channels from Switch. Create the channel on the platform, then add the app to it.`;
+ }
+ return "Channel creation is turned off for this connection. An admin can turn it on in Messaging Apps.";
+ }, [selectedBridge, channelCreationBlocked]);
+
+ // If the user had "Create new channel" selected and then picks a bridge
+ // that can't do that, flip the selection rather than leaving it invalid.
+ useEffect(() => {
+ if (channelCreationBlocked && channelSource === "new") {
+ setChannelSource("existing");
+ }
+ }, [channelCreationBlocked, channelSource]);
+
const addRole = useCallback(
() => setRoles((rs) => [...rs, { name: "", instructions: "", exclusive: false }]),
[],
@@ -330,6 +358,7 @@ export default function RoomCreateFormBody() {
value="new"
control={<Radio size="small" />}
label="Create new channel"
+ disabled={channelCreationBlocked}
/>
<FormControlLabel
value="existing"
@@ -338,6 +367,12 @@ export default function RoomCreateFormBody() {
/>
</RadioGroup>
+ {channelCreationBlockedReason && (
+ <Alert severity="info" variant="outlined">
+ {channelCreationBlockedReason}
+ </Alert>
+ )}
+
{channelSource === "existing" ? (
<TextField
label="External channel ID"