Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(telegram): mark the message an agent is working on with π (#274)
Louis Amaudruz5e7a6f6d6e70
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4b01954df..293c62044 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -45,6 +45,21 @@ version of their own to them without also giving them a release of their own.### [Unreleased]#### Added+- Telegram marks the message an agent is working on with **π**, and clears it+ when the turn ends β in groups, channels and 1:1 chats alike, with no+ administrator rights needed. Outside forum topics Telegram has no threads, so+ the mark goes on the last thing a person said, which is what the agent is+ answering. A chat with reactions switched off loses the mark, not the turn+ (CHOO-2314).+- Telegram setup docs now spell out that BotFather shows the bot token **once**,+ and what to do if it was not saved (CHOO-2314).++#### Known limitations+- **Telegram cannot autocomplete an agent's name.** Slack's per-agent user+ groups have no Telegram equivalent: `@` autocomplete offers only real chat+ members, there is no user-group concept, and every agent posts through one+ bot. Real per-agent autocomplete would need a Telegram bot account per agent+ (CHOO-2314).- Mattermost marks the message an agent is working on with **π**, added when theturn opens and removed when it ends. Inside a thread the mark goes on thereply that asked rather than the root it hangs off, and an agent handling twodiff --git a/core/switch_core/bridges/collaboration/telegram/adapter.py b/core/switch_core/bridges/collaboration/telegram/adapter.pyindex bb902f8f2..e6896eb7d 100644--- a/core/switch_core/bridges/collaboration/telegram/adapter.py+++ b/core/switch_core/bridges/collaboration/telegram/adapter.py@@ -16,6 +16,7 @@ from telegram import (InputMediaDocument,InputMediaPhoto,LinkPreviewOptions,+ ReactionTypeEmoji,ReplyParameters,Update,)@@ -85,6 +86,11 @@ _SUPERGROUP_PREFIX = "-100"_NO_PREVIEW = LinkPreviewOptions(is_disabled=True)+# Marks the message an agent is working on. Telegram only accepts reactions+# from a fixed set, and π is in it β the same one Slack uses, so the signal+# reads the same wherever a room is bridged.+_WORKING_REACTION = "\U0001f440"+# 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,@@ -189,6 +195,24 @@ class TelegramAdapter(CollaborationAdapter):# 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.+ # chat id -> the last message a person sent there. Outside forum topics+ # Telegram has no thread object, so a turn is reported with no root and+ # there is nothing else to say which message a reaction belongs on.+ # Bounded like _seen_ids: one entry per chat the bot has ever seen.+ self._last_inbound: OrderedDict[str, str] = OrderedDict()+ self._last_inbound_max = 1000+ # (chat id, thread root) -> the message that actually asked in it.+ # A forum topic keeps the same root for every message in it, so the+ # mark belongs on the latest question rather than on the topic.+ # Bounded for the same reason as _seen_ids.+ self._thread_trigger: OrderedDict[tuple[str, str], str] = OrderedDict()+ self._thread_trigger_max = 1000+ # Messages currently carrying the π, as (chat id, message id), so a+ # turn reporting its activity repeatedly reacts once.+ self._reacted: set[tuple[str, str]] = set()+ # (chat id, agent name) -> every message that agent has marked. An+ # agent asked two things at once marks both, and the turn ends once.+ self._agent_reactions: dict[tuple[str, str], set[str]] = {}# ββ Lifecycle ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@@ -855,6 +879,93 @@ class TelegramAdapter(CollaborationAdapter):except Exception:logger.exception("Failed to trigger typing in Telegram chat %s", channel_id)+ # ββ Working reaction βββββββββββββββββββββββββββββββββββββββββββββββββββββ++ def _note_inbound(self, chat_id: str, root_id: str | None, message_id: str) -> None:+ """Remember the message a reaction should go on if this chat asks next."""+ if root_id:+ key = (chat_id, root_id)+ self._thread_trigger.pop(key, None)+ self._thread_trigger[key] = message_id+ while len(self._thread_trigger) > self._thread_trigger_max:+ self._thread_trigger.popitem(last=False)+ self._last_inbound.pop(chat_id, None)+ self._last_inbound[chat_id] = message_id+ while len(self._last_inbound) > self._last_inbound_max:+ self._last_inbound.popitem(last=False)++ def _reaction_anchor(self, chat_id: str, thread_root_id: str | None) -> str | None:+ """The message the π goes on.++ Inside a forum topic every message shares one root, so the mark belongs+ on the latest question asked there rather than on the topic itself.+ Everywhere else Telegram has no thread object and the turn is reported+ with no root at all, so the last thing a person said in the chat stands+ in: that is what the agent is replying to, and the message a reader is+ looking at while they wait.+ """+ if thread_root_id:+ return self._thread_trigger.get((chat_id, thread_root_id), thread_root_id)+ return self._last_inbound.get(chat_id)++ async def _begin_working_reaction(+ self, chat_id: str, agent_name: str, thread_root_id: str | None+ ) -> None:+ """Mark what this agent is working on, once per turn."""+ asked_on = self._reaction_anchor(chat_id, thread_root_id)+ if not asked_on:+ return+ self._agent_reactions.setdefault((chat_id, agent_name), set()).add(asked_on)+ await self._mark_working(chat_id, asked_on, working=True)++ async def _end_working_reactions(self, chat_id: str, agent_name: str) -> None:+ """Unmark everything this agent marked β the turn ends only once.++ An agent asked two things at once works on both and marks both, but the+ report that ends the turn names one chat. Clearing only that would+ leave the other message marked as in progress for good.+ """+ for ref in sorted(self._agent_reactions.pop((chat_id, agent_name), set())):+ await self._mark_working(chat_id, ref, working=False)++ async def _mark_working(+ self, chat_id: str, message_id: str, *, working: bool+ ) -> None:+ """Put π on the message being worked on, and take it off after.++ This is Telegram's one real progress affordance in a group. A bot may+ react to anyone's message without being an administrator, it needs no+ thread, and it says *which* message is being handled β which the status+ message, sitting at the bottom of the chat, cannot.++ A chat can have reactions switched off. That costs the mark, not the+ turn, so a refusal is logged and the tracked state left as it was for a+ later attempt to correct.+ """+ key = (chat_id, message_id)+ if working == (key in self._reacted):+ return+ try:+ bot = self._require_bot()+ await bot.set_message_reaction(+ chat_id=self._chat_id(chat_id),+ message_id=int(message_id),+ reaction=[ReactionTypeEmoji(_WORKING_REACTION)] if working else [],+ )+ except TelegramError as e:+ logger.warning(+ "Could not %s the working reaction on %s in %s: %s",+ "add" if working else "remove",+ message_id,+ chat_id,+ e,+ )+ return+ if working:+ self._reacted.add(key)+ else:+ self._reacted.discard(key)+# ββ Runtime state ββββββββββββββββββββββββββββββββββββββββββββββββββββββββasync def _apply_runtime_state(@@ -877,8 +988,19 @@ class TelegramAdapter(CollaborationAdapter):The working indicator stays up through `awaiting-input` (the agent ismid-turn, just paused) and the pings go with it when the turn ends orresumes.++ In a 1:1 chat Telegram will draw the progress itself, and better: an+ animated "Thinkingβ¦" attributed to the bot rather than a message in the+ history. Where that is available the posted message is not used, and+ any earlier one is taken down. It is a private-chat method, so a+ bridged group always gets the posted message."""key = (channel_id, agent_name)+ if state in ("working", "awaiting-input"):+ await self._begin_working_reaction(channel_id, agent_name, thread_root_id)+ else:+ await self._end_working_reactions(channel_id, agent_name)+if state == "working":await self._clear_input_pings(channel_id, agent_name)body = self._working_body(detail, deeplink_url)@@ -1255,6 +1377,7 @@ class TelegramAdapter(CollaborationAdapter):)root_id = self._root_id_of(message)message_ref = f"{chat_id}:{message.message_id}"+ self._note_inbound(chat_id, root_id, str(message.message_id))if await self._handle_start(content.strip(), chat_id, channel_type):returndiff --git a/core/tests/switch_core/bridges/collaboration/test_telegram_adapter.py b/core/tests/switch_core/bridges/collaboration/test_telegram_adapter.pyindex 856012e9a..a5c37d12d 100644--- a/core/tests/switch_core/bridges/collaboration/test_telegram_adapter.py+++ b/core/tests/switch_core/bridges/collaboration/test_telegram_adapter.py@@ -149,7 +149,10 @@ class _FakeBot:self.edits: list[dict[str, Any]] = []self.deletes: list[dict[str, Any]] = []self.actions: list[dict[str, Any]] = []+ self.reactions: list[dict[str, Any]] = []self.files: dict[str, _FakeFileHandle] = {}+ # Set to an exception to make every set_message_reaction raise it.+ self.reaction_error: Exception | None = Noneself.published_commands: list[Any] = []self.chat: _FakeChat = _FakeChat()# What getChatMember reports for the bot itself in `chat`.@@ -202,6 +205,11 @@ class _FakeBot:async def send_chat_action(self, **kwargs: Any) -> None:self.actions.append(kwargs)+ async def set_message_reaction(self, **kwargs: Any) -> None:+ if self.reaction_error is not None:+ raise self.reaction_error+ self.reactions.append(kwargs)+async def set_my_commands(self, commands: Any) -> None:self.published_commands = list(commands)@@ -1233,6 +1241,195 @@ def test_the_status_message_follows_the_conversation() -> None:assert _bot(adapter).deletes[0]["message_id"] == int(original.split(":")[1])+# ββ Working reaction βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+++def _ask(adapter: TelegramAdapter, message_id: int = 11, **kwargs: Any) -> None:+ """Deliver an inbound message, so the adapter knows what is being answered."""+ adapter._on_message = lambda m: _collect([], m)+ _run(adapter._handle_message(_FakeInbound(message_id=message_id, **kwargs)))+++def _emoji(call: dict[str, Any]) -> list[str]:+ return [r.emoji for r in call["reaction"]]+++def test_working_puts_the_eyes_on_the_message_that_asked() -> None:+ adapter = _adapter()+ _ask(adapter, message_id=11)++ _run(+ adapter.apply_runtime_state(+ str(CHAT_ID), "scout", "working", mention_handle=None, thread_root_id=None+ )+ )++ assert _emoji(_bot(adapter).reactions[0]) == ["π"]+ assert _bot(adapter).reactions[0]["message_id"] == 11+++def test_the_eyes_come_off_when_the_turn_ends() -> None:+ adapter = _adapter()+ _ask(adapter, message_id=11)+ _run(+ adapter.apply_runtime_state(+ str(CHAT_ID), "scout", "working", mention_handle=None, thread_root_id=None+ )+ )++ _run(+ adapter.apply_runtime_state(+ str(CHAT_ID), "scout", "idle", mention_handle=None, thread_root_id=None+ )+ )++ assert _emoji(_bot(adapter).reactions[-1]) == []+ assert _bot(adapter).reactions[-1]["message_id"] == 11+++def test_the_eyes_go_up_once_however_often_the_activity_changes() -> None:+ adapter = _adapter()+ _ask(adapter, message_id=11)++ for detail in ("reading", "editing", "running tests"):+ _run(+ adapter.apply_runtime_state(+ str(CHAT_ID),+ "scout",+ "working",+ mention_handle=None,+ thread_root_id=None,+ detail=detail,+ )+ )++ assert len(_bot(adapter).reactions) == 1+++def test_the_eyes_stay_up_while_the_agent_waits_for_input() -> None:+ # awaiting-input is mid-turn, not the end of one: the agent is still on it.+ adapter = _adapter()+ _ask(adapter, message_id=11)+ _run(+ adapter.apply_runtime_state(+ str(CHAT_ID), "scout", "working", mention_handle=None, thread_root_id=None+ )+ )++ _run(+ adapter.apply_runtime_state(+ str(CHAT_ID),+ "scout",+ "awaiting-input",+ mention_handle="alice",+ thread_root_id=None,+ )+ )++ assert [_emoji(c) for c in _bot(adapter).reactions] == [["π"]]+++def test_the_eyes_follow_the_newest_question_in_the_chat() -> None:+ # Telegram reports no thread, so "what is being worked on" is whatever was+ # asked last β not the first thing the agent was ever asked.+ adapter = _adapter()+ _ask(adapter, message_id=11)+ _run(+ adapter.apply_runtime_state(+ str(CHAT_ID), "scout", "working", mention_handle=None, thread_root_id=None+ )+ )+ _run(+ adapter.apply_runtime_state(+ str(CHAT_ID), "scout", "idle", mention_handle=None, thread_root_id=None+ )+ )++ _ask(adapter, message_id=12)+ _run(+ adapter.apply_runtime_state(+ str(CHAT_ID), "scout", "working", mention_handle=None, thread_root_id=None+ )+ )++ assert [c["message_id"] for c in _bot(adapter).reactions] == [11, 11, 12]+++def test_a_reply_is_marked_on_itself_not_on_what_it_replied_to() -> None:+ adapter = _adapter()+ _ask(adapter, message_id=11)+ _ask(adapter, message_id=12, reply_to_message=_FakeInbound(message_id=11))++ _run(+ adapter.apply_runtime_state(+ str(CHAT_ID), "scout", "working", mention_handle=None, thread_root_id="11"+ )+ )++ assert _bot(adapter).reactions[0]["message_id"] == 12+++def test_every_message_an_agent_marked_is_cleared_by_the_one_turn_ending() -> None:+ # Two chats, one agent, one turn end β both marks have to come off.+ adapter = _adapter()+ other = str(-100999)+ _ask(adapter, message_id=11)+ _ask(adapter, message_id=21, chat=_FakeChat(chat_id=-100999))+ for channel in (str(CHAT_ID), other):+ _run(+ adapter.apply_runtime_state(+ channel, "scout", "working", mention_handle=None, thread_root_id=None+ )+ )++ for channel in (str(CHAT_ID), other):+ _run(+ adapter.apply_runtime_state(+ channel, "scout", "idle", mention_handle=None, thread_root_id=None+ )+ )++ cleared = [c["message_id"] for c in _bot(adapter).reactions if not c["reaction"]]+ assert sorted(cleared) == [11, 21]+++def test_a_chat_that_never_spoke_is_not_reacted_to() -> None:+ # Nothing to mark is not an error, and must not invent a message id.+ adapter = _adapter()++ _run(+ adapter.apply_runtime_state(+ str(CHAT_ID), "scout", "working", mention_handle=None, thread_root_id=None+ )+ )++ assert _bot(adapter).reactions == []+ assert "Working on it" in _bot(adapter).messages[0]["text"]+++def test_a_refused_reaction_is_logged_and_the_turn_carries_on(+ caplog: pytest.LogCaptureFixture,+) -> None:+ # Reactions can be switched off per chat. That costs the signal, not the turn.+ adapter = _adapter()+ _ask(adapter, message_id=11)+ _bot(adapter).reaction_error = BadRequest("REACTION_INVALID")++ with caplog.at_level(logging.WARNING):+ _run(+ adapter.apply_runtime_state(+ str(CHAT_ID),+ "scout",+ "working",+ mention_handle=None,+ thread_root_id=None,+ )+ )++ assert any("working reaction" in r.getMessage() for r in caplog.records)+ assert "Working on it" in _bot(adapter).messages[0]["text"]++# ββ Translation ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdiff --git a/docs/bridges/TELEGRAM_SETUP.md b/docs/bridges/TELEGRAM_SETUP.mdindex 75f9d5834..c0e955ce9 100644--- a/docs/bridges/TELEGRAM_SETUP.md+++ b/docs/bridges/TELEGRAM_SETUP.md@@ -27,10 +27,21 @@ bot is never promoted, and needs no permissions in a group.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:+ shape `<bot id>:<hmac>`.+4. **Save the token now, before going any further.** You need it in step 5, and+ BotFather's message is the only time it is shown to you β there is no screen+ anywhere that displays an existing token again. Put it straight into your+ password manager or your deployment's secret store.++ Treat it like a password: anyone holding it controls the bot. Do not paste+ it into a chat, a ticket, a room or a commit.++ **If you lost it, or pasted it somewhere you shouldn't have**, you do not+ need a new bot β issue a new token with `/token` in BotFather (`/mybots` β+ the bot β **API Token** β **Revoke current token** does the same and+ invalidates the old one immediately). Update `bot_token` on the connection+ afterwards, or the bridge stops polling.+5. **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@@ -48,7 +59,7 @@ basic group into a supergroup, and Telegram's "add as admin" chat picker leavesbasic groups out β so it is offered as a repair for a single chat (below), notas the way in.-5. As a gateway admin, onboard the bridge from the **operator dashboard**:+6. As a gateway admin, onboard the bridge from the **operator dashboard**:**Messaging Apps β Register messaging app β Telegram**, give it a displayname (e.g. "Acme Telegram"), and fill in the fields below.@@ -63,6 +74,14 @@ On success the bridge starts polling.## 2. Link a chat to Switch β from Telegram+> **A 1:1 chat with the bot is not a room.** Switch bridges Telegram *groups*,+> supergroups and channels. Messaging the bot directly reaches the **lobby**,+> which answers with setup guidance and nothing else β no room is created, no+> agent is reachable, and an agent cannot be given a private Telegram chat with+> someone. To talk to an agent one-to-one on Telegram, make a group containing+> just you and the bot. See+> [Why there is no Telegram DM](#why-there-is-no-telegram-dm).+**This is the normal way, and it needs nothing from Switch.** In any Telegramclient:@@ -257,6 +276,84 @@ things Telegram delivers there.the dashboard's install links send once the bot has been added β so the bridgeanswers it itself instead of passing it on as an unknown command.+## Knowing an agent is working on it++Two signals, and which you get depends on the kind of chat.++**π on the message that asked β everywhere.** When an agent starts a turn the+bot reacts to the message it is answering, and clears the reaction when the+turn ends. This works in groups, supergroups, channels and 1:1 chats, needs no+administrator rights, and is the same reaction the Slack bridge uses, so a room+bridged to either place reads the same.++It marks the *last thing a person said* in the chat, because outside forum+topics Telegram has no threads β only reply chains β so there is no thread for+a status to belong to. If an agent is asked two things at once, both messages+are marked and both are cleared when the turn ends.++A chat can have reactions switched off. Then the mark is lost and the turn+carries on; the bridge logs it rather than failing the turn.++**The "βοΈ Working on itβ¦" message.** Alongside the reaction, the bridge posts a+status message and edits it in place as the agent's activity changes, removing+it when the turn ends.++Telegram has a native animated "Thinkingβ¦" placeholder β the one it uses for+its own AI features β but it is **not reachable here**. It is written with+`sendMessageDraft`, whose `chat_id` Telegram documents as a *private chat*, and+Switch does not bridge Telegram 1:1 chats: a private chat with the bot is the+lobby, which answers with setup guidance rather than becoming a room. The same+restriction applies to the richer `sendRichMessageDraft` and its+`<tg-thinking>` block, so a newer Bot API does not change this.++## Why there is no Telegram DM++On Slack and Discord an agent can be given a 1:1 room with a person. **On+Telegram it cannot**, and this is a deliberate limit rather than an unfinished+feature.++A private chat with the bot maps to the **lobby**: the bridge recognises it,+replies with guidance on linking a real chat, and stops there. No room is+provisioned and no agent ever receives the message. Creating a room with+`channel_type="direct"` on a Telegram connection fails for the same reason it+fails for every other type β a Telegram bot cannot create a chat at all.++The reason is that one bot fronts every Switch agent. In a group that works,+because each message is labelled with the agent's name and mark, and `@name`+picks out who is being addressed. In a 1:1 there is no such handle: the chat is+between you and *the bot*, so "which agent am I talking to" has no answer the+platform can express, and every agent you own would share one conversation.++**What to do instead:** create a Telegram group with just you and the bot, and+invite the one agent you want. It behaves like a DM, and the agent is+addressable by name.++One consequence worth knowing: **Telegram's native "Thinkingβ¦" placeholder is+out of reach.** It is a private-chat-only API (`sendMessageDraft`, and the+richer `sendRichMessageDraft` with its `<tg-thinking>` block), and Switch has no+private chats to use it in. Progress is shown with π and the posted status+message instead.++## What Telegram cannot do: agent-name autocomplete++The Slack bridge gives each agent a **user group**, so typing `@` in the+composer autocompletes the agent's name. **There is no Telegram equivalent, and+this is not a gap that can be closed by configuration.**++- Telegram's `@` autocomplete offers only real members of the chat.+- There is no user-group or alias concept for a bot to register names in.+- Every Switch agent posts through the *same* bot, so the only handle that+ autocompletes is the bot's own.++Address an agent by typing its name after the bot's `@handle`, or use+`!list-agents` to see the names available in the chat. The `/` command menu is+the only autocompleting affordance the platform offers a bot, and it lists+commands, not agents.++The one route to real per-agent autocomplete is a separate Telegram bot account+per agent β a different design, not a setting, and not something this bridge+does.+## One instance per bot tokenTelegram delivers each update to **one** long-polling caller and rejects the