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(discord): agent name autocomplete and a mark on the message being answered (CHOO-2316) (#272)
Louis Amaudruz015a290455d3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2d2a1f9c7..0ecf17874 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -47,6 +47,30 @@ version of their own to them without also giving them a release of their own.### [0.19.0] - 2026-08-22#### Added+- Each agent gets a mentionable **Discord role**, so its `@name` autocompletes+ in the composer and arrives as a real pill rather than plain text that only+ looks like one. The roles are minted empty and permissionless — mentioning one+ notifies nobody — and an inbound `<@&…>` resolves back to the agent's name+ before the addressing layer sees it. A Discord role carries no metadata, so an+ agent's role is the one named exactly after it: a role made by hand is adopted+ rather than duplicated, and one that has members is never deleted. Off with+ `agent_roles: false`, and it turns itself off, saying why, on a server missing+ Manage Roles or at Discord's 250-role cap (CHOO-2316).+- Discord puts **👀 on the message an agent is answering** for as long as its+ turn lasts. The posted status says an agent is busy; the reaction is what says+ which message it is busy with, and an agent answering two people at once marks+ both and clears both together. Needs the bot's Add Reactions permission;+ without it the bridge warns and posts no reaction rather than faking one+ (CHOO-2316).++#### Fixed+- A Discord command argument naming someone picked from the composer's `@` menu+ is resolved to their name instead of being refused. Both the slash and typed+ `!` forms branch off before the translation an ordinary message gets, so an+ agent or person chosen from the menu arrived as raw `<@&…>` / `<@…>` markup+ and was rejected as "not a single name" — quoting a string the invoker never+ typed. Newly reachable because an agent's name now autocompletes, but the+ typed form was wrong before that too (CHOO-2316).- Telegram marks the message an agent is working on with **👀**, and clears itwhen the turn ends — in groups, channels and 1:1 chats alike, with noadministrator rights needed. Outside forum topics Telegram has no threads, sodiff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.pyindex 909ea34ca..27e1524ca 100644--- a/core/switch_core/bridges/collaboration/adapter.py+++ b/core/switch_core/bridges/collaboration/adapter.py@@ -301,6 +301,7 @@ class CollaborationAdapter(ABC):deeplink_url: str | None = None,detail: str | None = None,trigger_thread_root_id: str | None = None,+ anchor_message_ref: str | None = None,) -> None:"""Serialise against any other runtime-indicator work for this agent,then apply the state. Adapters override ``_apply_runtime_state``."""@@ -314,6 +315,7 @@ class CollaborationAdapter(ABC):deeplink_url=deeplink_url,detail=detail,trigger_thread_root_id=trigger_thread_root_id,+ anchor_message_ref=anchor_message_ref,)async def reposition_runtime_state(@@ -336,6 +338,7 @@ class CollaborationAdapter(ABC):deeplink_url: str | None = None,detail: str | None = None,trigger_thread_root_id: str | None = None,+ anchor_message_ref: str | None = None,) -> None:"""Surface a Switch Console-managed agent's runtime state on the channel.@@ -356,6 +359,13 @@ class CollaborationAdapter(ABC):distinction reads it, and its callers should not have to restate avalue the other adapters ignore.+ ``anchor_message_ref`` is the external post the agent reports it is+ answering — the last message it was actually handed. Unlike the two+ above it names a *message* rather than a thread, and it is set whether+ or not that message opened one, so an adapter can mark the message+ itself (Discord puts a reaction on it) without moving where the status+ is posted. None when nothing the agent was handed crossed this bridge.+``deeplink_url``, when set, is an https link (served by the gateway) thatopens the agent's session in the Switch Console desktop app; adapters thatpost a visible status message append it so a reader can jump there.diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.pyindex 9c56fa18d..1453fcc6f 100644--- a/core/switch_core/bridges/collaboration/bridge_core.py+++ b/core/switch_core/bridges/collaboration/bridge_core.py@@ -1518,6 +1518,15 @@ class BridgeCore:event.thread_id)+ # The message the agent says it is answering. Resolved whichever way+ # the status is positioned, so an adapter can mark that message without+ # also moving the status onto it.+ anchor_message_ref: str | None = None+ if event.anchor_event_id is not None:+ anchor_message_ref = await self._external_post_for_matrix_event(+ event.anchor_event_id+ )+# Where a persistent status belongs, which on an adapter that asks for# it is the thread the reply will open on the message being worked on.anchor_ref = event.thread_id@@ -1544,6 +1553,7 @@ class BridgeCore:deeplink_url=event.deeplink_url,detail=event.detail,trigger_thread_root_id=trigger_thread_ref,+ anchor_message_ref=anchor_message_ref,)await self._follow_reported_anchor(channel_id,diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.pyindex bf2e46581..95ef948cc 100644--- a/core/switch_core/bridges/collaboration/discord/adapter.py+++ b/core/switch_core/bridges/collaboration/discord/adapter.py@@ -12,6 +12,7 @@ from typing import Any, ClassVarimport discordfrom discord import app_commands+from pydantic import Fieldfrom switch_core.bridges.agent.commands import COMMANDS_BY_NAMEfrom switch_core.bridges.agent.commands import Command as InRoomCommand@@ -46,10 +47,27 @@ _WEBHOOK_NAME = "Switch Bridge"_READY_TIMEOUT = 30.0+# Put on the message an agent is working on for as long as its turn lasts.+_WORKING_REACTION = "👀"++# Discord's error code for "Maximum number of guild roles reached" (250).+_MAX_GUILD_ROLES_CODE = 30005+class DiscordConnectionConfig(BridgeConnectionConfig):bot_token: strguild_id: str+ # Both registration forms build themselves from this schema, so what is+ # written here is the only explanation an operator gets next to the+ # checkbox.+ agent_roles: bool = Field(+ default=True,+ title="Agent name autocomplete",+ description=(+ "Give each agent a mentionable Discord role so its name completes "+ "when you type @. Needs Manage Roles."+ ),+ )class DiscordAdapter(CollaborationAdapter):@@ -92,6 +110,20 @@ class DiscordAdapter(CollaborationAdapter):# Webhook messages delete cleanly on Discord, so runtime state renders# as a persistent message (see the base class's _working_msg) rather# than the one-shot typing indicator.+ # Message refs currently carrying the "being worked on" reaction, and+ # per agent the set it has marked — a turn ends once but may have+ # marked several messages.+ self._eyes: set[str] = set()+ self._agent_eyes: dict[tuple[str, str], set[str]] = {}+ # Set once Discord has told us it will not host agent roles, so the+ # bridge stops asking and says so only once.+ self._agent_roles_off_reason: str | None = None+ # Folded agent name -> the guild role that agent is mentioned by, for+ # the roles this bridge has minted or adopted. Only these are rendered+ # as role pills on the way out: a role carries no metadata on Discord,+ # so anything wider would risk turning a passing "@moderators" into a+ # real ping of somebody's real role.+ self._agent_role_ids: dict[str, int] = {}# ── Lifecycle ────────────────────────────────────────────────────────────@@ -577,6 +609,7 @@ class DiscordAdapter(CollaborationAdapter):deeplink_url: str | None = None,detail: str | None = None,trigger_thread_root_id: str | None = None,+ anchor_message_ref: str | None = None,) -> None:"""Render runtime state as persistent, truly-deletable status messages.@@ -587,7 +620,17 @@ class DiscordAdapter(CollaborationAdapter):mid-turn, just paused) and the pings are removed alongside it whenthe turn goes idle or resumes to `working`. When the agent wasaddressed in a thread, messages surface in that thread.++ Alongside them the message the agent is answering carries 👀 for as long+ as the turn lasts. The status sits where the conversation is, so the+ reaction is the only thing that says *which* message is being handled —+ and it needs nothing from Discord but a permission, so it is there at+ the channel root as well as inside a thread."""+ # Marked before the branching below, because the working branch returns+ # early when it only has to refresh the message in place.+ await self._track_turn(channel_id, anchor_message_ref, agent_name, state=state)+key = (channel_id, agent_name)if state == "working":await self._clear_input_pings(channel_id, agent_name)@@ -617,6 +660,75 @@ class DiscordAdapter(CollaborationAdapter):await self._clear_working(channel_id, agent_name)await self._clear_input_pings(channel_id, agent_name)+ async def _track_turn(+ self,+ channel_id: str,+ anchor_message_ref: str | None,+ agent_name: str,+ *,+ state: str,+ ) -> None:+ """Mark every message this agent is working on, and unmark them together.++ An agent asked two things at once works on both, and each message gets+ its own 👀 — but the turn ends **once**, naming only the message it last+ touched. Clearing just that one leaves the first marked as being worked+ on for good, so they are remembered per agent and cleared together.+ """+ akey = (channel_id, agent_name)+ if state in ("working", "awaiting-input"):+ if anchor_message_ref is None:+ return+ self._agent_eyes.setdefault(akey, set()).add(anchor_message_ref)+ await self._mark_being_read(anchor_message_ref, working=True)+ return++ for ref in sorted(self._agent_eyes.pop(akey, set())):+ await self._mark_being_read(ref, working=False)++ async def _mark_being_read(self, message_ref: str, *, working: bool) -> None:+ """Put 👀 on the message an agent is working on, and take it off after.++ Needs only the Add Reactions permission, and works at the channel root+ as well as inside a thread — so it is the progress signal that is always+ available. A guild that has not granted the permission gets one warning+ and no reaction, rather than a mark that is not there.+ """+ location_id, message_id = self._parse_message_ref(message_ref)+ if not message_id or self._client is None:+ return+ if working == (message_ref in self._eyes):+ return++ try:+ channel = await self._get_channel(int(location_id))+ message = channel.get_partial_message(int(message_id))+ if working:+ await message.add_reaction(_WORKING_REACTION)+ self._eyes.add(message_ref)+ else:+ await message.remove_reaction(_WORKING_REACTION, self._client.user)+ self._eyes.discard(message_ref)+ except discord.NotFound:+ # The message (or the reaction) is gone; the end state is what was+ # wanted either way.+ self._eyes.discard(message_ref)+ except discord.Forbidden:+ logger.warning(+ "Discord refused the working reaction on %s — the bot is missing "+ "the Add Reactions permission here. Turns show the posted status "+ "message; only the mark on the message being answered is missing. "+ "Re-invite the bot with the permissions in DISCORD_SETUP.md.",+ message_ref,+ )+ except (discord.HTTPException, ValueError) as e:+ logger.warning(+ "Could not %s the working reaction on Discord message %s: %s",+ "add" if working else "remove",+ message_ref,+ e,+ )+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:@@ -809,10 +921,137 @@ class DiscordAdapter(CollaborationAdapter):async def create_agent_identity(self, agent_name: str, agent_description: str) -> None:- pass+ """Give the agent a mentionable guild role so its name completes on `@`.++ Discord only autocompletes things it knows about, and an agent is not a+ Discord member — one bot serves all of them, differentiated per message+ by the webhook override. A role is the one handle a bot can mint that+ still appears in the composer's `@` menu, so each agent gets one. The+ role is left empty and carries no permissions: it exists to be+ completable and to arrive as a structured mention, and mentioning it+ notifies nobody.+ """+ if not self._agent_roles_available():+ return+ if agent_name.casefold() in self._agent_role_ids:+ return++ guild = await self._get_guild()+ # A role whose name is exactly the agent's is taken to be that agent's,+ # so a role made by hand — the only way to use this where the bot may+ # not manage roles — is adopted rather than duplicated. The match has to+ # be exact: a server's own role must never be captured by an agent that+ # happens to be named similarly.+ existing = discord.utils.get(guild.roles, name=agent_name)+ if existing is not None:+ self._agent_role_ids[agent_name.casefold()] = existing.id+ logger.info(+ "Adopted existing Discord role %s for agent %s", existing.id, agent_name+ )+ return++ try:+ role = await guild.create_role(+ name=agent_name,+ mentionable=True,+ hoist=False,+ permissions=discord.Permissions.none(),+ reason="Switch agent name autocomplete",+ )+ except discord.Forbidden:+ self._disable_agent_roles(+ "the bot is missing the Manage Roles permission — re-invite it "+ "with the permissions in DISCORD_SETUP.md."+ )+ return+ except discord.HTTPException as e:+ if e.code != _MAX_GUILD_ROLES_CODE:+ raise+ self._disable_agent_roles(+ "this server has reached Discord's hard limit of 250 roles — "+ "free some, or turn agent name autocomplete off for this bridge."+ )+ return++ self._agent_role_ids[agent_name.casefold()] = role.id+ logger.info("Created Discord role %s for agent %s", role.id, agent_name)async def remove_agent_identity(self, agent_name: str) -> None:- pass+ """Delete the agent's role, unless people are wearing it.++ A Discord role carries no metadata, so an agent's role is recognised by+ its name alone. That is fine for mentioning — the worst case is a stale+ pill — but not for deleting: a role that happens to share an agent's+ name may be somebody's real role. One with members is therefore left+ alone and said so, since an agent's own role never has any.+ """+ if not self._agent_roles_available():+ return++ guild = await self._get_guild()+ role_id = self._agent_role_ids.pop(agent_name.casefold(), None)+ role = (+ guild.get_role(role_id)+ if role_id is not None+ else discord.utils.get(guild.roles, name=agent_name)+ )+ if role is None:+ return+ if role.members:+ logger.warning(+ "Left the Discord role %s in place: agent %s is gone but %d "+ "member(s) hold that role, so it is not ours to delete.",+ role.id,+ agent_name,+ len(role.members),+ )+ return++ try:+ await role.delete(reason="Switch agent removed")+ except discord.Forbidden:+ self._disable_agent_roles(+ "the bot is missing the Manage Roles permission — re-invite it "+ "with the permissions in DISCORD_SETUP.md."+ )+ return+ logger.info("Deleted Discord role %s for agent %s", role.id, agent_name)++ # ── Agent roles ──────────────────────────────────────────────────────────++ def _agent_roles_available(self) -> bool:+ return self._config.agent_roles and not self._agent_roles_off_reason++ def _disable_agent_roles(self, reason: str) -> None:+ """Stop attempting agent roles on this bridge, saying why, once.++ The setting is on by default, so a server that simply cannot host them+ is an ordinary situation rather than a misconfiguration — but it must+ not be a silent one, and it must not repeat the complaint for every+ agent on every startup.+ """+ if self._agent_roles_off_reason:+ return+ self._agent_roles_off_reason = reason+ logger.warning(+ "Discord agent roles are unavailable on this server: %s Agent names "+ "will not autocomplete in the Discord composer; agents remain "+ "addressable by typing their name.",+ reason,+ )++ def _guild_from_cache(self) -> Any:+ return self._client.get_guild(self._guild_id) if self._client else None++ def _role_name(self, role_id: int) -> str | None:+ guild = self._guild_from_cache()+ role = guild.get_role(role_id) if guild else None+ return getattr(role, "name", None)++ def _member_name(self, user_id: int) -> str | None:+ guild = self._guild_from_cache()+ member = guild.get_member(user_id) if guild else None+ return getattr(member, "name", None)async def get_channel_agent_names(self, channel_id: str) -> list[str]:return []@@ -821,18 +1060,35 @@ class DiscordAdapter(CollaborationAdapter):def translate_outbound(self, content: str) -> str:# Discord renders markdown natively (bold, code, headers, masked- # links), so only @username mentions need rewriting to real Discord- # mentions for users we have resolved. Agents and unknown names stay- # plain text.+ # links), so only @name mentions need rewriting to real Discord+ # mentions: a resolved user, or an agent that has a role of its own so+ # it reads as the same pill a person would have picked from the `@`+ # menu. Unknown names stay plain text.def _replace(match: re.Match[str]) -> str:user_id = self._username_to_id.get(match.group(1))- return f"<@{user_id}>" if user_id else match.group(0)+ if user_id:+ return f"<@{user_id}>"+ role_id = self._agent_role_ids.get(match.group(1).casefold())+ return f"<@&{role_id}>" if role_id else match.group(0)return re.sub(r"@([a-z0-9][a-z0-9._-]*)", _replace, content)def translate_inbound(self, raw_message: str) -> str:def _replace_user(match: re.Match[str]) -> str:- name = self._user_names.get(int(match.group(1)))+ # The cache only knows people who have posted. Someone picked from+ # the `@` menu may not have, so fall back to the guild.+ user_id = int(match.group(1))+ name = self._user_names.get(user_id) or self._member_name(user_id)+ return f"@{name}" if name else match.group(0)++ def _replace_role(match: re.Match[str]) -> str:+ # An agent's role is how its name reaches the composer's `@` menu,+ # so picking it there sends `<@&123>` rather than the typed name.+ # Resolving it back to the role's name is what lets the rest of+ # Switch treat it as an ordinary mention — the addressing layer+ # matches on the name and knows nothing about Discord. A role that+ # is not an agent's still reads better as its name than as markup.+ name = self._role_name(int(match.group(1)))return f"@{name}" if name else match.group(0)def _replace_channel(match: re.Match[str]) -> str:@@ -842,7 +1098,8 @@ class DiscordAdapter(CollaborationAdapter):name = getattr(channel, "name", None)return f"#{name}" if name else match.group(0)- message = re.sub(r"<@!?(\d+)>", _replace_user, raw_message)+ message = re.sub(r"<@&(\d+)>", _replace_role, raw_message)+ message = re.sub(r"<@!?(\d+)>", _replace_user, message)return re.sub(r"<#(\d+)>", _replace_channel, message)# ── Gateway event handling ───────────────────────────────────────────────@@ -900,6 +1157,11 @@ class DiscordAdapter(CollaborationAdapter):stripped = content.strip()if stripped.startswith("!") and self._on_command:parts = stripped.split(None, 1)+ # An ordinary message is translated downstream, but a command+ # branches off before that — and its arguments are exactly where a+ # mention picked from the `@` menu lands, as `<@&123>` markup the+ # dispatcher cannot match a name against.+ args = self.translate_inbound(parts[1].strip()) if len(parts) > 1 else ""await self._on_command(InboundCommand(channel_id=channel_id,@@ -907,7 +1169,7 @@ class DiscordAdapter(CollaborationAdapter):sender_id=str(author.id),sender_name=username,command=parts[0].lstrip("!"),- args=parts[1].strip() if len(parts) > 1 else "",+ args=args,message_ref=message_ref,root_id=root_id,channel_name=channel_name,@@ -965,6 +1227,15 @@ class DiscordAdapter(CollaborationAdapter):the Slack slash path, which posts the same visible notice because aslash invocation is otherwise invisible to the channel."""+ # An option is a text field, and Discord offers its `@` autocomplete+ # inside one — so picking the agent from the menu submits the raw+ # `<@&123>` markup rather than the name it renders as. The commands+ # downstream read names, and every other inbound path already goes+ # through this, so a slash argument does too.+ values = {+ name: self.translate_inbound(value) if isinstance(value, str) else value+ for name, value in values.items()+ }shown = self._format_invocation(command, values)# Reassembly is pure and instant, so it runs before the ack: a baddiff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.pyindex 8e81b529f..2039354ce 100644--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py@@ -505,6 +505,7 @@ class MattermostAdapter(CollaborationAdapter):deeplink_url: str | None = None,detail: str | None = None,trigger_thread_root_id: str | None = None,+ anchor_message_ref: str | None = None,) -> None:"""Surface runtime state as a posted message that is **never deleted**.diff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.pyindex f9dbd50f8..ab477ce8d 100644--- a/core/switch_core/bridges/collaboration/slack/adapter.py+++ b/core/switch_core/bridges/collaboration/slack/adapter.py@@ -711,6 +711,7 @@ class SlackAdapter(CollaborationAdapter):deeplink_url: str | None = None,detail: str | None = None,trigger_thread_root_id: str | None = None,+ anchor_message_ref: str | None = None,) -> None:"""Render runtime state as persistent, truly-deletable status messages.diff --git a/core/switch_core/bridges/collaboration/teams/adapter.py b/core/switch_core/bridges/collaboration/teams/adapter.pyindex 726f4ba45..b5e198487 100644--- a/core/switch_core/bridges/collaboration/teams/adapter.py+++ b/core/switch_core/bridges/collaboration/teams/adapter.py@@ -549,6 +549,7 @@ class TeamsAdapter(CollaborationAdapter):deeplink_url: str | None = None,detail: str | None = None,trigger_thread_root_id: str | None = None,+ anchor_message_ref: str | None = None,) -> None:"""Persistent status messages, mirroring Slack.diff --git a/core/switch_core/bridges/collaboration/telegram/adapter.py b/core/switch_core/bridges/collaboration/telegram/adapter.pyindex e6896eb7d..b70d18688 100644--- a/core/switch_core/bridges/collaboration/telegram/adapter.py+++ b/core/switch_core/bridges/collaboration/telegram/adapter.py@@ -979,6 +979,7 @@ class TelegramAdapter(CollaborationAdapter):deeplink_url: str | None = None,detail: str | None = None,trigger_thread_root_id: str | None = None,+ anchor_message_ref: str | None = None,) -> None:"""Render runtime state as persistent, deletable status messages.diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_runtime_state_thread.py b/core/tests/switch_core/bridges/collaboration/test_bridge_runtime_state_thread.pyindex 39974487f..2ecd902ce 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_runtime_state_thread.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_runtime_state_thread.py@@ -27,6 +27,7 @@ class _FakeAdapter:self.runtime_state_follows_anchor = follows_anchorself.applied: list[str | None] = []self.trigger_threads: list[str | None] = []+ self.anchors: list[str | None] = []def agents_with_live_runtime_state(self, channel_id: str) -> list[str]:return []@@ -42,9 +43,11 @@ class _FakeAdapter:deeplink_url: str | None,detail: str | None,trigger_thread_root_id: str | None = None,+ anchor_message_ref: str | None = None,) -> None:self.applied.append(thread_root_id)self.trigger_threads.append(trigger_thread_root_id)+ self.anchors.append(anchor_message_ref)async def reposition_runtime_state(self, channel_id: str, agent_name: str, thread_root_id: str | None@@ -159,3 +162,28 @@ def test_a_threaded_trigger_reports_its_thread() -> None:_report(bridge, thread_id="$thread", anchor_event_id="$thread")assert bridge.adapter_spy.trigger_threads == ["post-thread"]+++# ── The message being answered, as distinct from where the status goes ───────+++def test_the_answered_message_is_reported_even_at_the_channel_root() -> None:+ """Marking a message and moving the status onto it are separate choices.++ Discord leaves the status where the conversation is and puts a reaction on+ the message instead, so it needs the anchor without opting into the move.+ """+ bridge = _bridge(follows_anchor=False, posts={"$trigger": "post-trigger"})++ _report(bridge, thread_id=None, anchor_event_id="$trigger")++ assert bridge.adapter_spy.applied == [None]+ assert bridge.adapter_spy.anchors == ["post-trigger"]+++def test_an_unmapped_answered_message_is_reported_as_absent() -> None:+ bridge = _bridge(follows_anchor=False, posts={})++ _report(bridge, thread_id=None, anchor_event_id="$unknown")++ assert bridge.adapter_spy.anchors == [None]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.pyindex bbba1d669..c2955da6d 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@@ -66,7 +66,9 @@ def test_discord_adapter_registers_with_expected_required_fields() -> None:assert service.get_registered_types() == ["discord"]schema = service.get_config_schema("discord")- assert set(schema["properties"]) == {"bot_token", "guild_id"}+ # agent_roles is offered but not required: it needs Manage Roles and room+ # under Discord's 250-role cap, so a connection stays valid without it.+ assert set(schema["properties"]) == {"bot_token", "guild_id", "agent_roles"}assert set(schema["required"]) == {"bot_token", "guild_id"}diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py b/core/tests/switch_core/bridges/collaboration/test_discord_adapter.pyindex 3d353f48f..2ff6c4d82 100644--- a/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py+++ b/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py@@ -186,12 +186,16 @@ class _FakeWebhook:class _FakeClient:- def __init__(self, channels: dict[int, Any]) -> None:+ def __init__(self, channels: dict[int, Any], guild: Any | None = None) -> None:self._channels = channels+ self._guild = guilddef get_channel(self, channel_id: int) -> Any | None:return self._channels.get(channel_id)+ def get_guild(self, guild_id: int) -> Any | None:+ return self._guild if guild_id == GUILD_ID else None+async def fetch_channel(self, channel_id: int) -> Any:channel = self._channels.get(channel_id)if channel is None:@@ -414,6 +418,44 @@ def test_bang_command_routed_to_on_command() -> None:assert cmd.root_id == f"{CHANNEL_ID}:3000"+def test_a_command_argument_picked_from_the_at_menu_arrives_as_a_name() -> None:+ """A typed command branches off before the message translation downstream.++ Its arguments are exactly where a mention picked from the `@` menu lands,+ and an agent's role makes that the obvious way to name one — so the markup+ has to be resolved here or the dispatcher matches a name against `<@&123>`.+ """++ class _Named:+ def __init__(self, name: str) -> None:+ self.name = name++ class _Guild:+ id = GUILD_ID++ def get_role(self, role_id: int) -> Any | None:+ return _Named("switch-expert-v1") if role_id == 7 else None++ def get_member(self, user_id: int) -> Any | None:+ return None++ class _Client:+ def get_guild(self, guild_id: int) -> Any | None:+ return _Guild() if guild_id == GUILD_ID else None++ adapter = _adapter()+ adapter._client = _Client() # type: ignore[assignment]+ commands = _capture_commands(adapter)++ _run(+ adapter._handle_message(+ _gateway_message(channel=_FakeChannel(), content="!invite-agent <@&7>")+ )+ )++ assert commands[0].args == "@switch-expert-v1"++# ── Attachments ──────────────────────────────────────────────────────────────diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_agent_roles.py b/core/tests/switch_core/bridges/collaboration/test_discord_agent_roles.pynew file mode 100644index 000000000..30f193d3a--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_discord_agent_roles.py@@ -0,0 +1,325 @@+"""The mentionable Discord role that makes an agent's name autocomplete.++An agent is not a Discord member — one bot serves all of them — so nothing+Discord knows about carries an agent's name, and `@` in the composer never+offers one. A role is the one handle a bot can mint that does appear there. It+is left empty and permissionless: it exists to be completable, and mentioning+it notifies nobody.++The awkward part is that a Discord role carries no metadata, so there is+nowhere to record that a role is ours. These pin down what follows from that.+"""++from __future__ import annotations++import asyncio+import logging+from typing import Any++import discord+import pytest++from switch_core.bridges.collaboration.discord.adapter import (+ DiscordAdapter,+ DiscordConnectionConfig,+)++GUILD_ID = 900+++def _run(coro: Any) -> Any:+ loop = asyncio.new_event_loop()+ try:+ return loop.run_until_complete(coro)+ finally:+ loop.close()+++class _FakeResponse:+ status = 403+ reason = "Forbidden"+++class _FakeRole:+ def __init__(+ self,+ role_id: int,+ name: str,+ *,+ members: list[object] | None = None,+ guild: _FakeGuild | None = None,+ ) -> None:+ self.id = role_id+ self.name = name+ self.members = members or []+ self._guild = guild++ async def delete(self, *, reason: str | None = None) -> None:+ assert self._guild is not None+ if self._guild.delete_error is not None:+ raise self._guild.delete_error+ self._guild.roles.remove(self)+ self._guild.deleted.append(self.id)+++class _FakeGuild:+ def __init__(self, roles: list[_FakeRole] | None = None) -> None:+ self.id = GUILD_ID+ self.roles = roles or []+ for role in self.roles:+ role._guild = self+ self.created: list[dict[str, Any]] = []+ self.deleted: list[int] = []+ self.create_error: Exception | None = None+ self.delete_error: Exception | None = None+ self._next_id = 1000++ def get_role(self, role_id: int) -> _FakeRole | None:+ return next((r for r in self.roles if r.id == role_id), None)++ async def create_role(self, **kwargs: Any) -> _FakeRole:+ if self.create_error is not None:+ raise self.create_error+ self.created.append(kwargs)+ self._next_id += 1+ role = _FakeRole(self._next_id, kwargs["name"], guild=self)+ self.roles.append(role)+ return role+++class _FakeClient:+ def __init__(self, guild: _FakeGuild) -> None:+ self._guild = guild+ self.user = object()++ def get_guild(self, guild_id: int) -> _FakeGuild | None:+ return self._guild if guild_id == self._guild.id else None+++def _adapter(guild: _FakeGuild, *, agent_roles: bool = True) -> DiscordAdapter:+ made = DiscordAdapter(+ config=DiscordConnectionConfig(+ bot_token="token", guild_id=str(GUILD_ID), agent_roles=agent_roles+ )+ )+ made._client = _FakeClient(guild) # type: ignore[assignment]+ return made+++def _http(code: int) -> discord.HTTPException:+ error = discord.HTTPException(_FakeResponse(), "no")+ error.code = code+ return error+++# ── Provisioning ─────────────────────────────────────────────────────────────+++def test_an_agent_gets_a_mentionable_role_of_its_own() -> None:+ guild = _FakeGuild()+ adapter = _adapter(guild)++ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))++ assert len(guild.created) == 1+ made = guild.created[0]+ assert made["name"] == "flint-tracker"+ assert made["mentionable"] is True+++def test_the_role_carries_no_permissions_and_is_not_hoisted() -> None:+ # It exists to be completable. Anything else it granted would be a+ # privilege nobody asked for, attached to a name people will mention.+ guild = _FakeGuild()+ adapter = _adapter(guild)++ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))++ made = guild.created[0]+ assert made["permissions"] == discord.Permissions.none()+ assert made["hoist"] is False+++def test_provisioning_the_same_agent_twice_makes_one_role() -> None:+ guild = _FakeGuild()+ adapter = _adapter(guild)++ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))+ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))++ assert len(guild.created) == 1+++def test_nothing_is_created_when_the_setting_is_off() -> None:+ guild = _FakeGuild()+ adapter = _adapter(guild, agent_roles=False)++ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))++ assert guild.created == []+++# ── Roles made by hand ───────────────────────────────────────────────────────+++def test_a_role_already_named_for_the_agent_is_adopted() -> None:+ """Where the bot may not manage roles, making one by hand is the only way+ to use this — so a role whose name is exactly an agent's is taken to be+ that agent's rather than duplicated."""+ guild = _FakeGuild([_FakeRole(7, "flint-tracker")])+ adapter = _adapter(guild)++ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))++ assert guild.created == []+ assert adapter._agent_role_ids["flint-tracker"] == 7+++def test_a_similarly_named_role_is_not_captured() -> None:+ # The match has to be exact: a server's own role must never be taken over+ # by an agent that happens to be named nearby.+ guild = _FakeGuild([_FakeRole(7, "Flint Trackers")])+ adapter = _adapter(guild)++ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))++ assert len(guild.created) == 1+++# ── Retiring an agent ────────────────────────────────────────────────────────+++def test_the_role_goes_when_the_agent_does() -> None:+ guild = _FakeGuild()+ adapter = _adapter(guild)+ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))++ _run(adapter.remove_agent_identity("flint-tracker"))++ assert guild.deleted == [1001]+++def test_a_role_people_are_wearing_is_left_alone(+ caplog: pytest.LogCaptureFixture,+) -> None:+ """A role carries no metadata, so an agent's is recognised by name alone.++ That is fine for mentioning — the worst case is a stale pill — but deleting+ on a name match could take out somebody's real role. An agent's own role+ never has members, so one that does is not ours.+ """+ guild = _FakeGuild([_FakeRole(7, "flint-tracker", members=[object()])])+ adapter = _adapter(guild)++ with caplog.at_level(logging.WARNING):+ _run(adapter.remove_agent_identity("flint-tracker"))++ assert guild.deleted == []+ assert "not ours to delete" in caplog.text+++def test_removing_an_agent_that_never_had_a_role_is_quiet() -> None:+ guild = _FakeGuild()+ adapter = _adapter(guild)++ _run(adapter.remove_agent_identity("flint-tracker"))++ assert guild.deleted == []+++# ── A server that cannot host them ───────────────────────────────────────────+++def test_a_missing_manage_roles_permission_is_named_once(+ caplog: pytest.LogCaptureFixture,+) -> None:+ guild = _FakeGuild()+ guild.create_error = discord.Forbidden(_FakeResponse(), "missing perms")+ adapter = _adapter(guild)++ with caplog.at_level(logging.WARNING):+ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))+ _run(adapter.create_agent_identity("chalk-tracker", "Tracks chalk"))++ complaints = [+ r for r in caplog.records if "agent roles are unavailable" in r.getMessage()+ ]+ assert len(complaints) == 1+ assert "Manage Roles" in complaints[0].getMessage()+++def test_a_server_out_of_roles_says_so_rather_than_retrying(+ caplog: pytest.LogCaptureFixture,+) -> None:+ # Discord caps a server at 250 roles, hard. Nothing about that gets better+ # by asking again, so it stops and names the cap.+ guild = _FakeGuild()+ guild.create_error = _http(30005)+ adapter = _adapter(guild)++ with caplog.at_level(logging.WARNING):+ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))+ _run(adapter.create_agent_identity("chalk-tracker", "Tracks chalk"))++ assert guild.created == []+ assert "250 roles" in caplog.text+++def test_an_unrecognised_refusal_is_not_swallowed() -> None:+ # Latching on anything at all would turn a transient Discord outage into a+ # bridge that quietly never provisions again.+ guild = _FakeGuild()+ guild.create_error = _http(50035)+ adapter = _adapter(guild)++ with pytest.raises(discord.HTTPException):+ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))+++# ── Translation ──────────────────────────────────────────────────────────────+++def test_a_role_mention_arrives_as_the_agents_name() -> None:+ """Picking the agent from the `@` menu sends `<@&id>`, not the typed name.++ Resolving it back is what lets the rest of Switch treat it as an ordinary+ mention — the addressing layer matches on the name and knows nothing about+ Discord.+ """+ guild = _FakeGuild([_FakeRole(7, "flint-tracker")])+ adapter = _adapter(guild)++ assert adapter.translate_inbound("hey <@&7> look") == "hey @flint-tracker look"+++def test_a_mention_of_a_role_we_know_nothing_about_still_reads_as_a_name() -> None:+ guild = _FakeGuild([_FakeRole(7, "moderators")])+ adapter = _adapter(guild)++ assert adapter.translate_inbound("<@&7> please") == "@moderators please"+++def test_a_mention_of_a_role_that_is_gone_is_left_as_it_came() -> None:+ adapter = _adapter(_FakeGuild())++ assert adapter.translate_inbound("<@&7> please") == "<@&7> please"+++def test_an_agent_name_goes_out_as_its_role_pill() -> None:+ guild = _FakeGuild()+ adapter = _adapter(guild)+ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))++ assert adapter.translate_outbound("ask @flint-tracker") == "ask <@&1001>"+++def test_a_name_that_is_not_an_agents_is_not_turned_into_a_ping() -> None:+ """Only roles this bridge minted or adopted for an agent become pills.++ Anything wider and a passing "@moderators" in an agent's message becomes a+ real ping of somebody's real role.+ """+ guild = _FakeGuild([_FakeRole(7, "moderators")])+ adapter = _adapter(guild)++ assert adapter.translate_outbound("ask @moderators") == "ask @moderators"diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_slash_commands.py b/core/tests/switch_core/bridges/collaboration/test_discord_slash_commands.pyindex 214785d4b..15873ff7d 100644--- a/core/tests/switch_core/bridges/collaboration/test_discord_slash_commands.py+++ b/core/tests/switch_core/bridges/collaboration/test_discord_slash_commands.py@@ -450,3 +450,107 @@ def test_dispatch_failure_when_adapter_not_started_is_reported() -> None:assert len(interaction.edits) == 1assert "Failed to run" in interaction.edits[0]+++# ── Mentions picked from the `@` menu ────────────────────────────────────────+#+# A slash option is a text field, and Discord offers its `@` autocomplete inside+# one. Now that each agent has a role of its own, picking it there is the+# obvious thing to do — and it submits `<@&123>` markup, not the name it renders+# as. Left untranslated the command is refused as "not a single name", naming a+# string the invoker never typed.+++class _FakeNamed:+ def __init__(self, name: str) -> None:+ self.name = name+++class _RoleGuild:+ def __init__(self, roles: dict[int, str], members: dict[int, str]) -> None:+ self.id = GUILD_ID+ self._roles = roles+ self._members = members++ def get_role(self, role_id: int) -> Any | None:+ name = self._roles.get(role_id)+ return _FakeNamed(name) if name else None++ def get_member(self, user_id: int) -> Any | None:+ name = self._members.get(user_id)+ return _FakeNamed(name) if name else None+++class _RoleClient:+ def __init__(self, guild: _RoleGuild) -> None:+ self._guild = guild++ def get_guild(self, guild_id: int) -> Any | None:+ return self._guild if guild_id == self._guild.id else None+++def _adapter_with_roles(+ roles: dict[int, str] | None = None, members: dict[int, str] | None = None+) -> DiscordAdapter:+ adapter = _adapter()+ adapter._client = _RoleClient(_RoleGuild(roles or {}, members or {})) # type: ignore[assignment]+ return adapter+++def test_an_agent_picked_from_the_menu_reaches_dispatch_as_its_name() -> None:+ adapter = _adapter_with_roles({1540343032090599435: "switch-expert-v1"})+ commands = _capture_commands(adapter)++ _invoke(+ adapter,+ _FakeInteraction(_FakeChannel()),+ "invite-agent",+ agent="<@&1540343032090599435>",+ )++ assert commands[0].args == "@switch-expert-v1"+++def test_the_running_notice_shows_the_name_not_the_markup() -> None:+ adapter = _adapter_with_roles({7: "switch-expert-v1"})+ _capture_commands(adapter)+ interaction = _FakeInteraction(_FakeChannel())++ _invoke(adapter, interaction, "invite-agent", agent="<@&7>")++ assert "switch-expert-v1" in interaction.responses[0]["content"]+ assert "<@&7>" not in interaction.responses[0]["content"]+++def test_a_person_picked_from_the_menu_resolves_without_having_posted() -> None:+ # The username cache only knows people who have said something. Someone+ # picked from the `@` menu may not have.+ adapter = _adapter_with_roles(members={55: "louis212"})+ commands = _capture_commands(adapter)++ _invoke(adapter, _FakeInteraction(_FakeChannel()), "reset", target="<@55>")++ assert commands[0].args == "@louis212"+++def test_a_typed_name_is_still_taken_verbatim() -> None:+ adapter = _adapter_with_roles({7: "switch-expert-v1"})+ commands = _capture_commands(adapter)++ _invoke(adapter, _FakeInteraction(_FakeChannel()), "invite-agent", agent="helper")++ assert commands[0].args == "@helper"+++def test_a_mention_of_something_gone_is_still_refused_clearly() -> None:+ # Nothing to resolve it to, so it stays markup and hits the existing+ # "must be a single name" refusal — which is now accurate rather than+ # misleading.+ adapter = _adapter_with_roles()+ commands = _capture_commands(adapter)+ interaction = _FakeInteraction(_FakeChannel())++ _invoke(adapter, interaction, "invite-agent", agent="<@&7>")++ assert commands == []+ assert interaction.responses[0]["ephemeral"] is Truediff --git a/core/tests/switch_core/bridges/collaboration/test_discord_working_reaction.py b/core/tests/switch_core/bridges/collaboration/test_discord_working_reaction.pynew file mode 100644index 000000000..e0893fa05--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_discord_working_reaction.py@@ -0,0 +1,254 @@+"""The 👀 Discord puts on the message an agent is answering.++The status message says an agent is busy; it does not say *what with*. The+reaction is what ties a turn to the message that started it, and it is the one+progress signal that costs nothing but a permission — so it has to survive a+missing permission, a deleted message, and an agent answering two people at+once, without ever leaving a mark behind.+"""++from __future__ import annotations++import asyncio+import logging+from typing import Any++import discord+import pytest++from switch_core.bridges.collaboration.discord.adapter import (+ DiscordAdapter,+ DiscordConnectionConfig,+)++GUILD_ID = 900+CHANNEL_ID = 100+++def _run(coro: Any) -> Any:+ loop = asyncio.new_event_loop()+ try:+ return loop.run_until_complete(coro)+ finally:+ loop.close()+++class _FakeResponse:+ status = 403+ reason = "Forbidden"+++class _FakePartialMessage:+ def __init__(self, channel: _FakeChannel, message_id: int) -> None:+ self.id = message_id+ self._channel = channel++ async def add_reaction(self, emoji: str) -> None:+ if self._channel.reaction_error is not None:+ raise self._channel.reaction_error+ self._channel.reactions.append(("add", self.id, emoji))++ async def remove_reaction(self, emoji: str, member: Any) -> None:+ if self._channel.reaction_error is not None:+ raise self._channel.reaction_error+ self._channel.reactions.append(("remove", self.id, emoji))+++class _FakeChannel:+ def __init__(self, channel_id: int = CHANNEL_ID) -> None:+ self.id = channel_id+ self.reactions: list[tuple[str, int, str]] = []+ self.reaction_error: Exception | None = None++ def get_partial_message(self, message_id: int) -> _FakePartialMessage:+ return _FakePartialMessage(self, message_id)+++class _FakeClient:+ def __init__(self, channels: dict[int, Any]) -> None:+ self._channels = channels+ self.user = object()++ def get_channel(self, channel_id: int) -> Any | None:+ return self._channels.get(channel_id)++ async def fetch_channel(self, channel_id: int) -> Any:+ channel = self._channels.get(channel_id)+ if channel is None:+ raise discord.NotFound(_FakeResponse(), "unknown channel")+ return channel+++def channel() -> _FakeChannel:+ return _FakeChannel()+++def adapter(channel: _FakeChannel) -> DiscordAdapter:+ made = DiscordAdapter(+ config=DiscordConnectionConfig(bot_token="token", guild_id=str(GUILD_ID))+ )+ made._client = _FakeClient({CHANNEL_ID: channel}) # type: ignore[assignment]+ return made+++def _state(+ adapter: DiscordAdapter,+ state: str,+ *,+ anchor: str | None,+ agent: str = "scribe",+) -> None:+ _run(adapter._track_turn(str(CHANNEL_ID), anchor, agent, state=state))+++# ── The mark goes on, and comes off ──────────────────────────────────────────+++def test_the_message_being_answered_is_marked(+ adapter: DiscordAdapter, channel: _FakeChannel+) -> None:+ _state(adapter, "working", anchor=f"{CHANNEL_ID}:11")++ assert channel.reactions == [("add", 11, "👀")]+++def test_the_mark_comes_off_when_the_turn_ends(+ adapter: DiscordAdapter, channel: _FakeChannel+) -> None:+ _state(adapter, "working", anchor=f"{CHANNEL_ID}:11")+ _state(adapter, "idle", anchor=None)++ assert channel.reactions == [("add", 11, "👀"), ("remove", 11, "👀")]+++def test_a_refreshed_turn_does_not_mark_twice(+ adapter: DiscordAdapter, channel: _FakeChannel+) -> None:+ # The activity refresh reports `working` over and over with the same+ # anchor; each one must not cost an API call.+ _state(adapter, "working", anchor=f"{CHANNEL_ID}:11")+ _state(adapter, "working", anchor=f"{CHANNEL_ID}:11")++ assert channel.reactions == [("add", 11, "👀")]+++def test_the_mark_stays_up_while_the_agent_waits_for_input(+ adapter: DiscordAdapter, channel: _FakeChannel+) -> None:+ # `awaiting-input` is mid-turn, not the end of one.+ _state(adapter, "working", anchor=f"{CHANNEL_ID}:11")+ _state(adapter, "awaiting-input", anchor=f"{CHANNEL_ID}:11")++ assert ("remove", 11, "👀") not in channel.reactions+++def test_a_turn_with_nothing_bridged_to_mark_is_not_an_error(+ adapter: DiscordAdapter, channel: _FakeChannel+) -> None:+ # A turn the agent started from somewhere other than this channel has no+ # anchor here — there is nothing to mark, and nothing to complain about.+ _state(adapter, "working", anchor=None)++ assert channel.reactions == []+++# ── Two questions at once ────────────────────────────────────────────────────+++def test_both_messages_are_marked_and_both_are_cleared(+ adapter: DiscordAdapter, channel: _FakeChannel+) -> None:+ """A turn ends once, naming only the message it last touched.++ Clearing just that one would leave the first marked as being worked on for+ good — which is why the marks are held per agent rather than per message.+ """+ _state(adapter, "working", anchor=f"{CHANNEL_ID}:11")+ _state(adapter, "working", anchor=f"{CHANNEL_ID}:22")+ _state(adapter, "idle", anchor=None)++ assert channel.reactions == [+ ("add", 11, "👀"),+ ("add", 22, "👀"),+ ("remove", 11, "👀"),+ ("remove", 22, "👀"),+ ]+++def test_one_agent_ending_its_turn_leaves_another_agent_marked(+ adapter: DiscordAdapter, channel: _FakeChannel+) -> None:+ _state(adapter, "working", anchor=f"{CHANNEL_ID}:11", agent="scribe")+ _state(adapter, "working", anchor=f"{CHANNEL_ID}:22", agent="courier")+ _state(adapter, "idle", anchor=None, agent="scribe")++ assert ("remove", 11, "👀") in channel.reactions+ assert ("remove", 22, "👀") not in channel.reactions+++# ── Inside a thread ──────────────────────────────────────────────────────────+++def test_a_message_inside_a_thread_is_marked_in_that_thread(+ adapter: DiscordAdapter,+) -> None:+ """The reaction goes where the message is, not where the room is.++ A message posted in a thread is bridged into the parent channel's room, but+ it lives in the thread — which on Discord is a channel of its own, and the+ only place the reaction can be added.+ """+ thread = _FakeChannel(channel_id=777)+ adapter._client._channels[777] = thread # type: ignore[union-attr]++ _state(adapter, "working", anchor="777:33")++ assert thread.reactions == [("add", 33, "👀")]+++# ── When Discord says no ─────────────────────────────────────────────────────+++def test_a_missing_permission_is_named_rather_than_faked(+ adapter: DiscordAdapter,+ channel: _FakeChannel,+ caplog: pytest.LogCaptureFixture,+) -> None:+ channel.reaction_error = discord.Forbidden(_FakeResponse(), "missing perms")++ with caplog.at_level(logging.WARNING):+ _state(adapter, "working", anchor=f"{CHANNEL_ID}:11")++ assert channel.reactions == []+ assert "Add Reactions" in caplog.text+++def test_a_refused_mark_is_not_recorded_as_present(+ adapter: DiscordAdapter, channel: _FakeChannel+) -> None:+ # Recording a mark that was refused would make the retry on the next+ # activity report a no-op, so the guild would never recover the reaction+ # once the permission is granted.+ channel.reaction_error = discord.Forbidden(_FakeResponse(), "missing perms")+ _state(adapter, "working", anchor=f"{CHANNEL_ID}:11")++ channel.reaction_error = None+ _state(adapter, "working", anchor=f"{CHANNEL_ID}:11")++ assert channel.reactions == [("add", 11, "👀")]+++def test_a_deleted_message_ends_the_turn_cleanly(+ adapter: DiscordAdapter, channel: _FakeChannel+) -> None:+ _state(adapter, "working", anchor=f"{CHANNEL_ID}:11")++ channel.reaction_error = discord.NotFound(_FakeResponse(), "unknown message")+ _state(adapter, "idle", anchor=None)++ # The mark is forgotten, so a later turn on a fresh message still marks.+ channel.reaction_error = None+ _state(adapter, "working", anchor=f"{CHANNEL_ID}:11")+ assert channel.reactions[-1] == ("add", 11, "👀")diff --git a/docs/bridges/DISCORD_SETUP.md b/docs/bridges/DISCORD_SETUP.mdindex 8dea26e05..fdef24056 100644--- a/docs/bridges/DISCORD_SETUP.md+++ b/docs/bridges/DISCORD_SETUP.md@@ -49,9 +49,13 @@ Build an OAuth2 invite URL (Developer Portal → **OAuth2 → URL Generator**):- **Send Messages** + **Send Messages in Threads** — post agent replies.- **Manage Webhooks** — mint the per-channel webhook agents post through.- **Manage Channels** / **Manage Roles** — set per-member channel permission- overwrites (`channel.set_permissions`) when provisioning access.+ overwrites (`channel.set_permissions`) when provisioning access, and mint+ the per-agent role that makes an agent's name autocomplete (see [Agent name+ autocomplete](#agent-name-autocomplete-agent_roles)).- **Read Message History** — thread-aware replies.- **Attach Files** — relay agent image attachments.+ - **Add Reactions** — put 👀 on the message an agent is working on (see+ [Knowing an agent is working](#knowing-an-agent-is-working)).Open the generated URL and add the bot to your server.@@ -72,11 +76,63 @@ Fields (`DiscordConnectionConfig`):| --- | --- | --- || `bot_token` | yes | Bot token from the Developer Portal. || `guild_id` | yes | The Discord server (guild) id the bridge is scoped to. |+| `agent_roles` | no (default on) | Give each agent a mentionable role so its name autocompletes. See below. |On success the bridge opens its Gateway WebSocket to that guild. Post in achannel the bot can see (or have an agent post) and the Switch room is created onthe first bridged message.+## Agent name autocomplete (`agent_roles`)++An agent is not a Discord member — one bot serves all of them, differentiated+per message by a webhook override — so by default nothing Discord knows about+carries an agent's name and typing `@` never offers one. With this on, each+agent gets a **mentionable role named exactly after it**, so `@flint-tracker`+completes in the composer and arrives as a real pill. The role is empty and+carries no permissions: mentioning it notifies nobody, and Switch resolves the+mention back to the agent's name on the way in.++Roles are provisioned for every existing agent when the bridge starts, and for+each new agent as it registers. Two limits are worth knowing before you turn it+on:++- **Discord caps a server at 250 roles, hard.** A server that hits the cap gets+ one warning naming it, and the bridge stops trying — agents stay addressable+ by typing their name.+- **A role carries no metadata**, so there is nowhere to record that a role+ belongs to Switch. An agent's role is therefore the one whose name matches it+ **exactly**. Two consequences: a role you created by hand for an agent is+ adopted rather than duplicated (which is how to use this on a server where+ the bot may not manage roles), and when an agent is deleted its role is only+ deleted if **nobody holds it** — one with members is left in place, and the+ bridge says so.++Renaming an agent leaves its old role behind; delete it by hand.++Turn it off (`agent_roles: false`) on a server that is near the role cap or+where role management is restricted.++## Knowing an agent is working++When a Switch Console-managed agent starts on a message, two things appear:++- **👀 on the message it is answering**, removed when its turn ends. This is the+ only signal that says *which* message is being handled — an agent answering+ two people at once marks both, and clears both together. It needs the **Add+ Reactions** permission; without it the bridge logs a warning and posts no+ reaction rather than a mark that is not there.+- **A "⚙️ Working on it…" message** posted under the agent's own name and+ avatar, edited in place as the activity changes and deleted when the turn+ ends.++**What Discord cannot do here.** There is no native progress surface — nothing+like Slack's agent card — so the working message is one Switch renders itself.+The typing indicator is not usable as a real indicator either: it expires after+about 10 seconds, has no "stop" call, and shows the *bot* rather than the agent,+so with two agents working it would read as one anonymous "Switch Bridge is+typing". Discord's "thinking…" placeholder is interaction-only (slash commands),+which does not cover an ordinary `@agent` message.+## Slash commandsSwitch's in-room commands are also registered as native Discord slash commands,