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
Post the tagged-agent heads-up from the writing process, and skip it when only room agents are tagged (CHOO-3667)
Abel Dantas2826e9da31dd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8b9791612..5fd9c4fe4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -159,6 +159,15 @@ version of their own to them without also giving them a release of their own.compares it only when someone signs in.#### Changed+- **The heads-up for tagging an agent that isn't in the room comes from the+ process that wrote the message, and costs nothing when every name tagged+ is one of the room's agents.** The admin's consumer, which reads every+ message in a workspace on one process, checked each message with an `@`:+ two database sessions and a lookup for every name tagged. Under load that+ one process fell behind the rest. The check now runs once a message has+ committed, on whichever process wrote it, and only when the message tags+ a name that is none of the room's agents (a role, a person, an agent not+ in the room). The warnings read as before.- **An agent's stream reads in one database session per pass, and pooledconnections are no longer pinged before use.** A pass that delivered amessage opened a session for each of its reads, six pool checkouts and sixdiff --git a/core/switch_core/clients/command_consumer.py b/core/switch_core/clients/command_consumer.pyindex e97b6a93d..5560b5216 100644--- a/core/switch_core/clients/command_consumer.py+++ b/core/switch_core/clients/command_consumer.py@@ -4,22 +4,15 @@ import loggingimport timefrom typing import TYPE_CHECKING, Literal-from switch_core.agent_display_name import agent_label_with_identifierfrom switch_core.bridges.agent.commands import dispatch_admin_commandfrom switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistryfrom switch_core.clients.actor import SystemActorfrom switch_core.clients.admin_messages import (- ADMIN_MARKER,AdminMessageType,admin_extra_content,)from switch_core.clients.agent_admin import AgentAdministration, AgentDeletionRequestsfrom switch_core.clients.consumer import Consumer-from switch_core.clients.mentions import (- mention_regex,- strip_emphasis,- unique_mention_tokens,-)from switch_core.clients.room_meta import RoomMetafrom switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.agent_session_store import AgentSessionStore@@ -31,8 +24,7 @@ from switch_core.db.stores.room_role_store import RoomRoleStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.events import CommandEvent-from switch_core.room_wide_mention import is_reserved_mention_name-from switch_core.transport import InboundMessage, RoomRef+from switch_core.transport import RoomRefif TYPE_CHECKING:from switch_core.room_service import RoomService@@ -46,11 +38,10 @@ DELETE_CONFIRM_SECONDS = 120.0class CommandConsumer(Consumer[SystemActor]):"""Reads every room for Switch itself, and answers through its SystemActor.- Two jobs:- 1. Observe room messages and post heads-up notices when a message tags an- agent that is not a member, or a room-role with no live holder.- 2. Handle the room/info/alias `!` commands (the admin-owned set) and- render their results as admin messages.+ Handles the room/info/alias `!` commands (the admin-owned set) and+ renders their results as admin messages. The heads-up for a message that+ tags an agent not in the room, or a role nobody live-holds, is posted by+ the router once the message commits (`clients/mention_warnings.py`).Every admin message carries the admin marker so it renders natively perbridge and never triggers another member (loop-safe). The system is not an@@ -104,26 +95,6 @@ class CommandConsumer(Consumer[SystemActor]):# ── Event hooks ───────────────────────────────────────────────────────────- async def on_message(self, room: RoomRef, event: InboundMessage) -> None:- content = event.content- # Never react to admin/system messages — including our own notices —- # so the rail can't loop on itself.- if ADMIN_MARKER in content:- return- body = event.body or ""- if "@" not in body:- return-- meta = await self._resolve_room_meta(room.room_id)- if meta is None:- return-- thread_id = event.thread_root_id- thread_root = thread_id if thread_id is not None else event.event_id-- await self._warn_unreachable_roles(room, event, meta.room_id, thread_root)- await self._warn_absent_agents(room, event, meta.room_id, thread_root)-async def on_command(self, room: RoomRef, event: CommandEvent) -> None:await dispatch_admin_command(self, room, event)@@ -164,122 +135,8 @@ class CommandConsumer(Consumer[SystemActor]):metered=False,)- async def _warn_unreachable_roles(- self,- room: RoomRef,- event: InboundMessage,- room_id: str,- thread_id: str | None,- ) -> None:- """Warn when a tagged room-role has no LIVE holder.-- A role with no live lease (unassigned, or a stale lease whose holder's- session is gone — shown free by `!roles`) routes to nobody, so the admin- posts a heads-up in the triggering message's thread. A role WITH a live- holder is not flagged: that holder is addressed and responds.- """- body = getattr(event, "body", "") or ""- if "@" not in body:- return- unreachable: list[str] = []- async with self.session_factory() as session:- roles = await self._room_role_store.list_roles(session, room_id)- for role in roles:- if mention_regex(role.name).search(strip_emphasis(body)) is None:- continue- if not await self._room_role_store.has_live_holder(- session, role.id, self._connections.live_connection_ids()- ):- unreachable.append(role.name)- handle = self._sender_handle(event)- for name in unreachable:- notice = (- f"⚠️ @{handle} no agent currently holds the **{name}** role — "- f"your message may go unanswered. Run `!roles` to see "- f"availability, or have an agent assume it."- )- await self.actor.send_admin(- room.room_id,- notice,- message_type=AdminMessageType.UNREACHABLE_ROLE,- thread_root_id=thread_id,- mentions=[event.sender],- )-- async def _warn_absent_agents(- self,- room: RoomRef,- event: InboundMessage,- room_id: str,- thread_id: str | None,- ) -> None:- """Warn when a tagged agent is not a member of the room.-- An `@name` that resolves to a registered agent which is not in this room- routes to nobody, so the admin posts a heads-up in the triggering- message's thread naming the absent agent(s). Tokens that map to a- room-role (handled by `_warn_unreachable_roles`), to a current member,- to no agent at all (a human user or a typo), or that is a room-wide- mention word (`@everyone` pages the room's people) are ignored.- """- body = getattr(event, "body", "") or ""- if "@" not in body:- return- tokens = unique_mention_tokens(body)- if not tokens:- return- absent: list[str] = []- async with self.session_factory() as session:- member_ids = set(await self._room_store.get_agent_ids(session, room_id))- role_names = {- role.name.lower()- for role in await self._room_role_store.list_roles(session, room_id)- }- for token in tokens:- if token.lower() in role_names or is_reserved_mention_name(token):- continue- agent = await self._agent_store.get_by_name_insensitive(session, token)- if agent is None or agent.id in member_ids:- continue- absent.append(- agent_label_with_identifier(agent.display_name, agent.name)- )- if not absent:- return- names = ", ".join(f"**{label}**" for label in absent)- verb = "isn't" if len(absent) == 1 else "aren't"- pronoun = "it" if len(absent) == 1 else "them"- handle = self._sender_handle(event)- notice = (- f"⚠️ @{handle} {names} {verb} in this room, so your message won't "- f"reach {pronoun}. Add the agent from the room's detail page in the "- f"gateway, or have an agent with room-management tools invite it."- )- await self.actor.send_admin(- room.room_id,- notice,- message_type=AdminMessageType.ABSENT_AGENT,- thread_root_id=thread_id,- mentions=[event.sender],- )-# ── Helpers ────────────────────────────────────────────────────────────────- def _sender_handle(self, event: InboundMessage) -> str:- """The @-handle to tag the message sender with.-- Prefers the bridge-provided `sender_name` (the external username, which- the collaboration bridge rewrites into a real @mention on Slack /- Mattermost); falls back to the participant id's localpart for a client with no- bridge-provided name (paired with `mentions=[event.sender]` so the- mention renders as a pill).- """- content = event.content- name = content.get("sender_name")- if name:- return str(name)- return str(event.sender).split(":")[0].lstrip("@")-async def _resolve_room_meta(self, transport_room_id: str) -> RoomMeta | None:if transport_room_id in self._room_meta_cache:return self._room_meta_cache[transport_room_id]diff --git a/core/switch_core/clients/mention_warnings.py b/core/switch_core/clients/mention_warnings.pynew file mode 100644index 000000000..05545518b--- /dev/null+++ b/core/switch_core/clients/mention_warnings.py@@ -0,0 +1,195 @@+"""The admin's heads-up for a message that tags something that cannot answer:+a room role nobody live-holds, or an agent that is not in the room.++The router posts them once a message has committed, on whichever process+wrote it (`delivery/router.py`), and only for a message that tags a name+that is none of the room's agents (`unmatched_mentions`). Deciding the+message has read the room's agents already, so a message that tags only them+costs nothing here; one that tags anything else costs what it always did.+"""++from __future__ import annotations++from collections.abc import Iterable++from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.agent_display_name import agent_label_with_identifier+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.clients.actor import SystemActor+from switch_core.clients.admin_messages import AdminMessageType+from switch_core.clients.mentions import (+ mention_regex,+ strip_emphasis,+ unique_mention_tokens,+)+from switch_core.db.session_scope import tenant_session+from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.room_role_store import RoomRoleStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.room_wide_mention import is_reserved_mention_name+from switch_core.transport import InboundMessage, RoomRef+++def unmatched_mentions(body: str, names: Iterable[str]) -> list[str]:+ """The names `body` tags that are none of `names` (the room's agents'+ names and aliases) and no room-wide mention word, compared without case,+ each once."""+ known = {name.lower() for name in names}+ return [+ token+ for token in unique_mention_tokens(body)+ if token.lower() not in known and not is_reserved_mention_name(token)+ ]+++class MentionWarnings:+ def __init__(+ self,+ *,+ actor: SystemActor,+ tenant_id: str,+ session_factory: async_sessionmaker[AsyncSession],+ connections: AgentConnectionRegistry,+ room_store: RoomStore,+ room_role_store: RoomRoleStore,+ agent_store: AgentStore,+ ) -> None:+ self.actor = actor+ self.tenant_id = tenant_id+ self.session_factory = session_factory+ self._connections = connections+ self._room_store = room_store+ self._room_role_store = room_role_store+ self._agent_store = agent_store++ async def check(+ self,+ room: RoomRef,+ event: InboundMessage,+ room_id: str,+ member_ids: set[str],+ ) -> None:+ """Both warnings for `event`, in the thread it starts or is in.+ `member_ids` are the room's agents as the router read them."""+ thread_id = event.thread_root_id+ thread_root = thread_id if thread_id is not None else event.event_id+ await self._warn_unreachable_roles(room, event, room_id, thread_root)+ await self._warn_absent_agents(room, event, room_id, thread_root, member_ids)++ async def _warn_unreachable_roles(+ self,+ room: RoomRef,+ event: InboundMessage,+ room_id: str,+ thread_id: str | None,+ ) -> None:+ """Warn when a tagged room-role has no LIVE holder.++ A role with no live lease (unassigned, or a stale lease whose holder's+ session is gone — shown free by `!roles`) routes to nobody, so the admin+ posts a heads-up in the triggering message's thread. A role WITH a live+ holder is not flagged: that holder is addressed and responds.+ """+ body = getattr(event, "body", "") or ""+ if "@" not in body:+ return+ unreachable: list[str] = []+ async with tenant_session(self.session_factory, self.tenant_id) as session:+ roles = await self._room_role_store.list_roles(session, room_id)+ for role in roles:+ if mention_regex(role.name).search(strip_emphasis(body)) is None:+ continue+ if not await self._room_role_store.has_live_holder(+ session, role.id, self._connections.live_connection_ids()+ ):+ unreachable.append(role.name)+ handle = self._sender_handle(event)+ for name in unreachable:+ notice = (+ f"⚠️ @{handle} no agent currently holds the **{name}** role — "+ f"your message may go unanswered. Run `!roles` to see "+ f"availability, or have an agent assume it."+ )+ await self.actor.send_admin(+ room.room_id,+ notice,+ message_type=AdminMessageType.UNREACHABLE_ROLE,+ thread_root_id=thread_id,+ mentions=[event.sender],+ )++ async def _warn_absent_agents(+ self,+ room: RoomRef,+ event: InboundMessage,+ room_id: str,+ thread_id: str | None,+ member_ids: set[str] | None = None,+ ) -> None:+ """Warn when a tagged agent is not a member of the room.++ An `@name` that resolves to a registered agent which is not in this room+ routes to nobody, so the admin posts a heads-up in the triggering+ message's thread naming the absent agent(s). Tokens that map to a+ room-role (handled by `_warn_unreachable_roles`), to a current member,+ to no agent at all (a human user or a typo), or that is a room-wide+ mention word (`@everyone` pages the room's people) are ignored.+ `member_ids` are the room's agents when the caller has read them.+ """+ body = getattr(event, "body", "") or ""+ if "@" not in body:+ return+ tokens = unique_mention_tokens(body)+ if not tokens:+ return+ absent: list[str] = []+ async with tenant_session(self.session_factory, self.tenant_id) as session:+ if member_ids is None:+ member_ids = set(await self._room_store.get_agent_ids(session, room_id))+ role_names = {+ role.name.lower()+ for role in await self._room_role_store.list_roles(session, room_id)+ }+ for token in tokens:+ if token.lower() in role_names or is_reserved_mention_name(token):+ continue+ agent = await self._agent_store.get_by_name_insensitive(session, token)+ if agent is None or agent.id in member_ids:+ continue+ absent.append(+ agent_label_with_identifier(agent.display_name, agent.name)+ )+ if not absent:+ return+ names = ", ".join(f"**{label}**" for label in absent)+ verb = "isn't" if len(absent) == 1 else "aren't"+ pronoun = "it" if len(absent) == 1 else "them"+ handle = self._sender_handle(event)+ notice = (+ f"⚠️ @{handle} {names} {verb} in this room, so your message won't "+ f"reach {pronoun}. Add the agent from the room's detail page in the "+ f"gateway, or have an agent with room-management tools invite it."+ )+ await self.actor.send_admin(+ room.room_id,+ notice,+ message_type=AdminMessageType.ABSENT_AGENT,+ thread_root_id=thread_id,+ mentions=[event.sender],+ )++ def _sender_handle(self, event: InboundMessage) -> str:+ """The @-handle to tag the message sender with.++ Prefers the bridge-provided `sender_name` (the external username, which+ the collaboration bridge rewrites into a real @mention on Slack /+ Mattermost); falls back to the participant id's localpart for a client with no+ bridge-provided name (paired with `mentions=[event.sender]` so the+ mention renders as a pill).+ """+ content = event.content+ name = content.get("sender_name")+ if name:+ return str(name)+ return str(event.sender).split(":")[0].lstrip("@")diff --git a/core/switch_core/delivery/router.py b/core/switch_core/delivery/router.pyindex 44c8d416d..ad0c74434 100644--- a/core/switch_core/delivery/router.py+++ b/core/switch_core/delivery/router.py@@ -72,8 +72,9 @@ from sqlalchemy.exc import DBAPIErrorfrom switch_core.attachments import ATTACHMENT_GROUP_KEY, parse_attachment_groupfrom switch_core.budgets import BudgetGuard-from switch_core.clients.actor import AgentActor, ClientConfig-from switch_core.clients.admin_messages import PLATFORM_MARKER+from switch_core.clients.actor import AgentActor, ClientConfig, SystemActor+from switch_core.clients.admin_messages import ADMIN_MARKER, PLATFORM_MARKER+from switch_core.clients.mention_warnings import MentionWarnings, unmatched_mentionsfrom switch_core.clients.room_meta import RoomMetafrom switch_core.db.models import (Agent,@@ -118,6 +119,7 @@ from switch_core.transport.types import (InboundMedia,InboundMembership,InboundMessage,+ RoomRef,)if TYPE_CHECKING:@@ -583,14 +585,24 @@ class Routed:)if self._deadline_in is not None:router.flush_groups_after(reads.tenant_id, self._deadline_in)- work: list[tuple[AgentRecipient, Callable[[], Awaitable[None]]]] = []+ work: list[tuple[str, Callable[[], Awaitable[None]]]] = []row = self._rowfor recipient, delivery in plan.deliveries:if delivery.after is not None:- work.append((recipient, _bind(recipient, delivery.after, row)))+ work.append(+ (recipient.agent.name, _bind(recipient, delivery.after, row))+ )if plan.arrival is not None:arrival = plan.arrival- work.append((arrival, _bind(arrival, lambda _row: arrival.greet(), row)))+ work.append(+ (+ arrival.agent.name,+ _bind(arrival, lambda _row: arrival.greet(), row),+ )+ )+ warning = router.mention_warning(reads, row)+ if warning is not None:+ work.append(("Switch", warning))if work:router.after_commit(reads.tenant_id, reads.room_id, work)@@ -709,11 +721,11 @@ class _AfterCommit:self,tenant_id: str,room_id: str,- work: list[tuple[AgentRecipient, Callable[[], Awaitable[None]]]],+ work: list[tuple[str, Callable[[], Awaitable[None]]]],) -> None:+ """Queue `work`, each piece named by who it posts as."""queue = self._queues.setdefault(room_id, deque())- for recipient, run in work:- queue.append((recipient.agent.name, run))+ queue.extend(work)if room_id not in self._runners:self._runners[room_id] = asyncio.get_running_loop().create_task(self._drain(tenant_id, room_id), context=contextvars.Context()@@ -724,7 +736,7 @@ class _AfterCommit:try:with tenant_scope(tenant_id), log_context(room_id=room_id):while queue:- agent_name, run = queue.popleft()+ poster, run = queue.popleft()try:await run()except asyncio.CancelledError:@@ -732,9 +744,9 @@ class _AfterCommit:except Exception:metrics().increment(ROUTING_FAILURES, {"stage": "after_commit"})logger.error(- "A reply owed by agent %s in room %s could not be "+ "A reply owed by %s in room %s could not be ""posted; the message it answers was delivered",- agent_name,+ poster,room_id,exc_info=True,)@@ -775,6 +787,7 @@ class MessageRouter:# The "machine is waking" notices posted for each agent's rooms.self._cloud_waking: dict[str, set[tuple[str, int]]] = {}self._after = _AfterCommit()+ self._admin_for: Callable[[str], SystemActor | None] | None = Noneself._timers: set[asyncio.TimerHandle] = set()self._flushes: set[asyncio.Task[None]] = set()@@ -1635,10 +1648,58 @@ class MessageRouter:self,tenant_id: str,room_id: str,- work: list[tuple[AgentRecipient, Callable[[], Awaitable[None]]]],+ work: list[tuple[str, Callable[[], Awaitable[None]]]],) -> None:self._after.add(tenant_id, room_id, work)+ def use_admin(self, admin_for: Callable[[str], SystemActor | None]) -> None:+ """Who posts as Switch in a tenant, for the heads-up a message owes+ when it tags something that cannot answer. Given once the clients are+ running; until then no heads-up is posted."""+ self._admin_for = admin_for++ def mention_warning(+ self, reads: RoomReads, row: InboundEvent+ ) -> Callable[[], Awaitable[None]] | None:+ """The heads-up check `row` owes, or None when it tags no name but the+ room's agents.++ Deciding the row read the room's agents already, so this costs no read+ for a message that tags only them, which is most of them. A message+ that tags anything else (a role, a person, an agent not in the room) is+ checked once it has committed, on this process. Switch's own messages+ are never checked, so a heads-up cannot set off another.+ """+ if self._admin_for is None or not isinstance(row, InboundMessage):+ return None+ if ADMIN_MARKER in row.content or "@" not in (row.body or ""):+ return None+ names = [member.agent.name for member in reads.members]+ names += [member.alias for member in reads.members if member.alias]+ if not unmatched_mentions(row.body, names):+ return None+ admin = self._admin_for(reads.tenant_id)+ if admin is None:+ return None+ services = self.services+ warnings = MentionWarnings(+ actor=admin,+ tenant_id=reads.tenant_id,+ session_factory=services.session_factory,+ connections=services.connections,+ room_store=services.room_store,+ room_role_store=services.room_role_store,+ agent_store=services.agent_store,+ )+ room = RoomRef(room_id=reads.transport_room_id)+ member_ids = {member.agent.id for member in reads.members}+ room_id = reads.room_id++ async def check() -> None:+ await warnings.check(room, row, room_id, member_ids)++ return check+async def idle(self) -> None:"""Wait for the replies already owed, and posts already being decided,to be done."""diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex a1025feea..f5c32fbfb 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -937,6 +937,18 @@ async def run(config: SwitchConfig, process_id: str) -> None:# Clients registered or deleted in another process are started or stopped# here too (`clients/client_signals.py`).ClientSignals(lifecycle=client_lifecycle, bus=signal_bus)+ # Every process runs each tenant's admin actor, so the process that wrote+ # a message posts the heads-up it owes (`clients/mention_warnings.py`).+ router.use_admin(+ lambda tenant_id: next(+ (+ client+ for client in client_lifecycle.get_by_type("admin", tenant_id)+ if isinstance(client, SystemActor)+ ),+ None,+ )+ )# ── Collaboration bridge lifecycle ───────────────────────────────────────collab_lifecycle = CollaborationBridgeLifecycleService(diff --git a/core/tests/switch_core/clients/test_command_consumer.py b/core/tests/switch_core/clients/test_command_consumer.pyindex f9f394f4c..27ceee5f9 100644--- a/core/tests/switch_core/clients/test_command_consumer.py+++ b/core/tests/switch_core/clients/test_command_consumer.py@@ -8,6 +8,7 @@ from switch_core.bridges.agent.commands import dispatch_admin_commandfrom switch_core.clients.actor import SystemActorfrom switch_core.clients.admin_messages import ADMIN_MARKER, AdminMessageTypefrom switch_core.clients.command_consumer import CommandConsumer+from switch_core.clients.mention_warnings import MentionWarnings, unmatched_mentionsfrom switch_core.events import CommandEventfrom switch_core.transport import InboundMessage, RoomRef@@ -57,7 +58,7 @@ def _admin_client(roles: list[SimpleNamespace] | None = None,live_role_ids: set[str] | None = None,) -> tuple[SimpleNamespace, list[dict[str, object]]]:- """Fake CommandConsumer surface for the warning methods.+ """Fake MentionWarnings surface for the warning methods.`members`: agent ids in the room. `agents_by_name`: registered agents keyedby lowercased name (the case-insensitive resolver). `roles`: defined room@@ -110,6 +111,7 @@ def _admin_client(actor.send_admin = lambda *a, **k: SystemActor.send_admin(actor, *a, **k)client = SimpleNamespace(actor=actor,+ tenant_id="tenant-1",session_factory=_session_factory,_connections=_no_connections(),_room_store=SimpleNamespace(get_agent_ids=_get_agent_ids),@@ -119,7 +121,7 @@ def _admin_client(),_agent_store=SimpleNamespace(get_by_name_insensitive=_get_by_name_insensitive),)- client._sender_handle = lambda event: CommandConsumer._sender_handle(client, event)+ client._sender_handle = lambda event: MentionWarnings._sender_handle(client, event)return client, sent@@ -129,12 +131,32 @@ def _marker_type(entry: dict[str, object]) -> object:return extra[ADMIN_MARKER]["type"] # type: ignore[index]+class TestUnmatchedMentions:+ def test_a_name_of_the_rooms_agents_is_matched_without_case(self) -> None:+ assert (+ unmatched_mentions("@Reviewer and @helper, look", ["reviewer", "helper"])+ == []+ )++ def test_any_other_name_is_unmatched_once(self) -> None:+ assert unmatched_mentions("@web-searcher @alice @web-searcher", ["helper"]) == [+ "web-searcher",+ "alice",+ ]++ def test_a_room_wide_mention_word_is_not_a_name(self) -> None:+ assert unmatched_mentions("@everyone @here hello", []) == []++ def test_no_tags_no_names(self) -> None:+ assert unmatched_mentions("nobody tagged", []) == []++class TestAdminUnreachableRoleWarning:async def test_warns_when_no_live_holder(self) -> None:roles = [SimpleNamespace(id="r-mgr", name="manager")]client, sent = _admin_client(roles=roles, live_role_ids=set())event = _event("@manager please review")- await CommandConsumer._warn_unreachable_roles(+ await MentionWarnings._warn_unreachable_roles(client, _room(), event, "room-1", None)assert len(sent) == 1@@ -145,7 +167,7 @@ class TestAdminUnreachableRoleWarning:roles = [SimpleNamespace(id="r-mgr", name="manager")]client, sent = _admin_client(roles=roles, live_role_ids=set())event = _event("@manager review?", sender_name="bob")- await CommandConsumer._warn_unreachable_roles(+ await MentionWarnings._warn_unreachable_roles(client, _room(), event, "room-1", None)assert "@bob" in sent[0]["body"]@@ -155,7 +177,7 @@ class TestAdminUnreachableRoleWarning:roles = [SimpleNamespace(id="r-mgr", name="manager")]client, sent = _admin_client(roles=roles, live_role_ids=set())event = _event("@manager please review")- await CommandConsumer._warn_unreachable_roles(+ await MentionWarnings._warn_unreachable_roles(client, _room(), event, "room-1", "thread-42")assert sent[0]["thread_root_id"] == "thread-42"@@ -164,7 +186,7 @@ class TestAdminUnreachableRoleWarning:roles = [SimpleNamespace(id="r-mgr", name="manager")]client, sent = _admin_client(roles=roles, live_role_ids={"r-mgr"})event = _event("@manager status?")- await CommandConsumer._warn_unreachable_roles(+ await MentionWarnings._warn_unreachable_roles(client, _room(), event, "room-1", None)assert sent == []@@ -173,7 +195,7 @@ class TestAdminUnreachableRoleWarning:roles = [SimpleNamespace(id="r-mgr", name="manager")]client, sent = _admin_client(roles=roles, live_role_ids=set())event = _event("just chatting, no tags")- await CommandConsumer._warn_unreachable_roles(+ await MentionWarnings._warn_unreachable_roles(client, _room(), event, "room-1", None)assert sent == []@@ -182,7 +204,7 @@ class TestAdminUnreachableRoleWarning:roles = [SimpleNamespace(id="r-lead", name="lead")]client, sent = _admin_client(roles=roles, live_role_ids=set())event = _event("@lead-dev ping")- await CommandConsumer._warn_unreachable_roles(+ await MentionWarnings._warn_unreachable_roles(client, _room(), event, "room-1", None)assert sent == []@@ -197,7 +219,7 @@ class TestAdminAbsentAgentWarning:}client, sent = _admin_client(agents_by_name=agents)event = _event("@web-searcher can you look this up?")- await CommandConsumer._warn_absent_agents(+ await MentionWarnings._warn_absent_agents(client, _room(), event, "room-1", None)assert len(sent) == 1@@ -213,7 +235,7 @@ class TestAdminAbsentAgentWarning:}client, sent = _admin_client(agents_by_name=agents)event = _event("@web-searcher ping", sender_name="carol")- await CommandConsumer._warn_absent_agents(+ await MentionWarnings._warn_absent_agents(client, _room(), event, "room-1", None)assert "@carol" in sent[0]["body"]@@ -227,7 +249,7 @@ class TestAdminAbsentAgentWarning:}client, sent = _admin_client(agents_by_name=agents)event = _event("@web-searcher ping")- await CommandConsumer._warn_absent_agents(+ await MentionWarnings._warn_absent_agents(client, _room(), event, "room-1", "thread-42")assert sent[0]["thread_root_id"] == "thread-42"@@ -240,7 +262,7 @@ class TestAdminAbsentAgentWarning:}client, sent = _admin_client(members={"a-web"}, agents_by_name=agents)event = _event("@web-searcher status?")- await CommandConsumer._warn_absent_agents(+ await MentionWarnings._warn_absent_agents(client, _room(), event, "room-1", None)assert sent == []@@ -249,7 +271,7 @@ class TestAdminAbsentAgentWarning:# A human user or a typo resolves to no agent — stay silent.client, sent = _admin_client(agents_by_name={})event = _event("@dave what do you think?")- await CommandConsumer._warn_absent_agents(+ await MentionWarnings._warn_absent_agents(client, _room(), event, "room-1", None)assert sent == []@@ -262,7 +284,7 @@ class TestAdminAbsentAgentWarning:}client, sent = _admin_client(agents_by_name=agents)event = _event("@cc-bug-fixing-2 please run")- await CommandConsumer._warn_absent_agents(+ await MentionWarnings._warn_absent_agents(client, _room(), event, "room-1", None)assert sent == []@@ -276,7 +298,7 @@ class TestAdminAbsentAgentWarning:}client, sent = _admin_client(agents_by_name=agents)event = _event("@everyone the deploy is at five")- await CommandConsumer._warn_absent_agents(+ await MentionWarnings._warn_absent_agents(client, _room(), event, "room-1", None)assert sent == []@@ -286,7 +308,7 @@ class TestAdminAbsentAgentWarning:roles = [SimpleNamespace(id="r-mgr", name="manager")]client, sent = _admin_client(agents_by_name={}, roles=roles)event = _event("@manager please review")- await CommandConsumer._warn_absent_agents(+ await MentionWarnings._warn_absent_agents(client, _room(), event, "room-1", None)assert sent == []@@ -302,7 +324,7 @@ class TestAdminAbsentAgentWarning:}client, sent = _admin_client(agents_by_name=agents)event = _event("@web-searcher @doc-expert can you pair up?")- await CommandConsumer._warn_absent_agents(+ await MentionWarnings._warn_absent_agents(client, _room(), event, "room-1", None)assert len(sent) == 1@@ -320,7 +342,7 @@ class TestAdminAbsentAgentWarning:}client, sent = _admin_client(agents_by_name=agents)event = _event("@switchdev can you look this up?")- await CommandConsumer._warn_absent_agents(+ await MentionWarnings._warn_absent_agents(client, _room(), event, "room-1", None)assert "**Switch Dev (`switchdev`)**" in sent[0]["body"]@@ -331,7 +353,7 @@ class TestAdminAbsentAgentWarning:}client, sent = _admin_client(agents_by_name=agents)event = _event("@switchdev ping")- await CommandConsumer._warn_absent_agents(+ await MentionWarnings._warn_absent_agents(client, _room(), event, "room-1", None)assert "**switchdev**" in sent[0]["body"]@@ -345,7 +367,7 @@ class TestAdminAbsentAgentWarning:}client, sent = _admin_client(agents_by_name=agents)event = _event("@switchdev ping", sender_name="carol")- await CommandConsumer._warn_absent_agents(+ await MentionWarnings._warn_absent_agents(client, _room(), event, "room-1", None)body = sent[0]["body"]@@ -363,7 +385,7 @@ class TestAdminAbsentAgentWarning:}client, sent = _admin_client(agents_by_name=agents)event = _event("@switchdev ping")- await CommandConsumer._warn_absent_agents(+ await MentionWarnings._warn_absent_agents(client, _room(), event, "room-1", None)assert "](https://example.invalid)" not in sent[0]["body"]diff --git a/core/tests/switch_core/clients/test_command_consumer_ownership.py b/core/tests/switch_core/clients/test_command_consumer_ownership.pyindex e54d7289d..4ec5423e3 100644--- a/core/tests/switch_core/clients/test_command_consumer_ownership.py+++ b/core/tests/switch_core/clients/test_command_consumer_ownership.py@@ -4,9 +4,9 @@ Against real PostgreSQL, two "processes" on one database, each wired the way`main` wires one: its own message listener, client factory, lifecycle,process lease, ownership and cursor writer. Both run the tenant's admin actor,so either can write as Switch, but only the one that owns the admin client-runs its `CommandConsumer`. A message tagging an agent that is not in the room-is answered with one warning, not one per process, and one said while no-process read for the admin is answered by the next owner, once.+runs its `CommandConsumer`. A `!help` is answered once, not once per process,+and one typed while no process read for the admin is answered by the next+owner, once."""from __future__ import annotations@@ -58,7 +58,6 @@ from switch_core.transport.observer import IgnoreParticipantMessagesfrom switch_core.transport.room_cache import RoomCacheLimits, RoomDeliveryCachefrom tests.ownership import process_lease_onfrom tests.routing import router_on-from tests.switch_core.test_room_wide_mention_wakes_no_agent import _make_agentTIMEOUT = 10.0@@ -202,7 +201,6 @@ async def room(session_factory: async_sessionmaker[AsyncSession]) -> _Room:await session.flush()await RoomStore().add_client(session, admin.id, room.id)await RoomStore().add_client(session, speaker.id, room.id)- await _make_agent(session, "absentee")await session.commit()return _Room(room_id=room.id,@@ -232,9 +230,10 @@ async def two(await process.stop()-async def _say(- session_factory: async_sessionmaker[AsyncSession], room: _Room, body: str+async def _type_help(+ session_factory: async_sessionmaker[AsyncSession], room: _Room) -> None:+ """`!help` typed in the room, as the command row a bridge writes."""async with session_factory() as session:await MessageStore().create(session,@@ -244,18 +243,23 @@ async def _say(sender_id=room.speaker,sender_client_id=room.speaker_id,sender_name="person",- event_type="m.room.message",- msgtype="m.text",- body=body,+ event_type="com.switch.command",+ msgtype=None,+ body=None,formatted_body=None,- content={"body": body, "sender_name": "person"},+ content={+ "command": "help",+ "args": "",+ "user_id": room.speaker,+ "user_name": "person",+ },),[],)await session.commit()-async def _warnings(+async def _answers(session_factory: async_sessionmaker[AsyncSession], room: _Room) -> list[Message]:async with session_factory() as session:@@ -270,19 +274,19 @@ async def _warnings(rowfor row in rowsif (row.content or {}).get(ADMIN_MARKER, {}).get("type")- == AdminMessageType.ABSENT_AGENT.value+ == AdminMessageType.COMMAND_RESULT.value]-async def _eventually_warned(+async def _eventually_answered(session_factory: async_sessionmaker[AsyncSession], room: _Room, count: int) -> list[Message]:async with asyncio.timeout(TIMEOUT):- while len(await _warnings(session_factory, room)) < count:+ while len(await _answers(session_factory, room)) < count:await asyncio.sleep(0.05)# Long enough for a second reader, had there been one, to have answered.await asyncio.sleep(0.5)- return await _warnings(session_factory, room)+ return await _answers(session_factory, room)class TestOneAdminConsumer:@@ -307,11 +311,11 @@ class TestOneAdminConsumer:two: tuple[_Process, _Process],room: _Room,) -> None:- await _say(session_factory, room, "@absentee are you there?")+ await _type_help(session_factory, room)- warnings = await _eventually_warned(session_factory, room, 1)+ answers = await _eventually_answered(session_factory, room, 1)- assert len(warnings) == 1+ assert len(answers) == 1async def test_the_next_owner_answers_what_was_said_while_nobody_read(self,@@ -321,14 +325,14 @@ class TestOneAdminConsumer:) -> None:a, b = twoowner, other = (a, b) if a.lifecycle.owns(room.admin_id) else (b, a)- await _say(session_factory, room, "@absentee first")- await _eventually_warned(session_factory, room, 1)+ await _type_help(session_factory, room)+ await _eventually_answered(session_factory, room, 1)await owner.stop()- await _say(session_factory, room, "@absentee said with nobody reading")+ await _type_help(session_factory, room)await other.ownership.balance()- warnings = await _eventually_warned(session_factory, room, 2)+ answers = await _eventually_answered(session_factory, room, 2)assert other.lifecycle.owns(room.admin_id)- assert len(warnings) == 2+ assert len(answers) == 2diff --git a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py b/core/tests/switch_core/db/test_tenant_exemption_allowlist.pyindex 96f8f0951..f6669508d 100644--- a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py+++ b/core/tests/switch_core/db/test_tenant_exemption_allowlist.py@@ -171,7 +171,6 @@ _RAW_SESSION_FACTORY_MODULES = {"switch_core.bridges.collaboration.collaboration_core","switch_core.bridges.collaboration.lifecycle_service","switch_core.delivery.recipient",- "switch_core.clients.command_consumer","switch_core.clients.client_lifecycle_service","switch_core.provisioning.postgres","switch_core.room_service",diff --git a/core/tests/switch_core/delivery/test_mention_warnings.py b/core/tests/switch_core/delivery/test_mention_warnings.pynew file mode 100644index 000000000..cab619e31--- /dev/null+++ b/core/tests/switch_core/delivery/test_mention_warnings.py@@ -0,0 +1,128 @@+"""The heads-up for a message that tags an agent not in the room, or a role+nobody live-holds, is posted by the process that wrote the message once it+has committed (`clients/mention_warnings.py`), and a message that tags only+the room's agents is not checked at all."""++from __future__ import annotations++from typing import Any++import pytest+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.clients.admin_messages import AdminMessageType, admin_extra_content+from switch_core.clients.mention_warnings import MentionWarnings+from switch_core.db.models import TENANT_ZERO_ID+from tests.routing import add_member, make_agent, make_person, make_room, process_on++SessionFactory = async_sessionmaker[AsyncSession]+++class _Admin:+ """Switch's admin actor, recording what it would post."""++ def __init__(self) -> None:+ self.posted: list[dict[str, Any]] = []++ async def send_admin(+ self,+ room_id: str,+ body: str,+ *,+ message_type: AdminMessageType,+ thread_root_id: str | None,+ mentions: list[str] | None = None,+ ) -> None:+ self.posted.append(+ {+ "room_id": room_id,+ "body": body,+ "type": message_type,+ "thread_root_id": thread_root_id,+ }+ )+++def _checks(monkeypatch: pytest.MonkeyPatch) -> list[str]:+ """The messages a heads-up check ran for."""+ ran: list[str] = []+ check = MentionWarnings.check++ async def recording(self: MentionWarnings, room: Any, event: Any, *a: Any) -> None:+ ran.append(event.body)+ await check(self, room, event, *a)++ monkeypatch.setattr(MentionWarnings, "check", recording)+ return ran+++async def test_tagging_an_agent_not_in_the_room_is_warned_by_the_writer(+ session_factory: SessionFactory,+) -> None:+ here = process_on(session_factory)+ admin = _Admin()+ here.router.use_admin(+ lambda tenant_id: admin if tenant_id == TENANT_ZERO_ID else None # type: ignore[return-value]+ )+ room = await make_room(session_factory)+ alice = await make_person(session_factory, "alice")+ helper, helper_client = await make_agent(session_factory, "helper")+ await make_agent(session_factory, "absentee")+ await add_member(session_factory, room, helper_client, agent=helper)+ await add_member(session_factory, room, alice)++ event_id = await here.say(room, "@helper and @absentee, a look?", sender=alice)+ await here.idle()++ assert [posted["type"] for posted in admin.posted] == [+ AdminMessageType.ABSENT_AGENT+ ]+ assert "absentee" in admin.posted[0]["body"]+ assert admin.posted[0]["room_id"] == room.transport_room_id+ assert admin.posted[0]["thread_root_id"] == event_id+++async def test_tagging_only_the_rooms_agents_is_not_checked(+ session_factory: SessionFactory, monkeypatch: pytest.MonkeyPatch+) -> None:+ here = process_on(session_factory)+ admin = _Admin()+ here.router.use_admin(lambda _tenant_id: admin) # type: ignore[arg-type,return-value]+ ran = _checks(monkeypatch)+ room = await make_room(session_factory)+ alice = await make_person(session_factory, "alice")+ for name in ("helper", "reviewer"):+ agent, client = await make_agent(session_factory, name)+ await add_member(session_factory, room, client, agent=agent)+ await add_member(session_factory, room, alice)++ await here.say(room, "@helper and @Reviewer, a look?", sender=alice)+ await here.idle()++ # The agents' offline notices tag alice, a person, so those are checked.+ assert "@helper and @Reviewer, a look?" not in ran+ assert admin.posted == []+++async def test_switchs_own_messages_are_not_checked(+ session_factory: SessionFactory, monkeypatch: pytest.MonkeyPatch+) -> None:+ here = process_on(session_factory)+ admin = _Admin()+ here.router.use_admin(lambda _tenant_id: admin) # type: ignore[arg-type,return-value]+ ran = _checks(monkeypatch)+ room = await make_room(session_factory)+ alice = await make_person(session_factory, "alice")+ await make_agent(session_factory, "absentee")+ await add_member(session_factory, room, alice)++ await here.say(+ room,+ "@alice @absentee is not in this room",+ sender=alice,+ extra_content=admin_extra_content(AdminMessageType.ABSENT_AGENT),+ )+ await here.idle()++ assert ran == []+ assert admin.posted == []