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
fix(bridge): resolve outbound Slack mentions from external_users (CHOO-1781)
Louis Amaudruz12f417fe391b
diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.pyindex f8cb3010f..f015a39e3 100644--- a/core/switch_core/bridges/collaboration/adapter.py+++ b/core/switch_core/bridges/collaboration/adapter.py@@ -454,6 +454,17 @@ class CollaborationAdapter(ABC):@abstractmethoddef translate_inbound(self, raw_message: str) -> str: ...+ def prime_mention_targets(self, targets: dict[str, str]) -> None:+ """Supply known ``username -> external user id`` pairs for this bridge.++ Called on startup with every external user on the bridge, and again as+ new ones are provisioned. Platforms that address people by an opaque id+ (Slack's ``<@U…>``) need the mapping to render an outbound ``@name`` as+ a real mention; without it the name goes out as plain text and the+ person is never notified. Default is a no-op, since platforms that+ mention by handle (Mattermost) need no mapping at all."""+ return None+async def ensure_channel_subscriptions(self, channels: list[tuple[str, str]]) -> None:diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.pyindex 8a33c104e..cb362cb35 100644--- a/core/switch_core/bridges/collaboration/bridge_core.py+++ b/core/switch_core/bridges/collaboration/bridge_core.py@@ -195,6 +195,10 @@ class BridgeCore:for user in users}+ self._adapter.prime_mention_targets(+ {user.external_username: user.external_user_id for user in users}+ )+for user in users:self._user_puppets[user.external_user_id] = user.client_id@@ -950,6 +954,7 @@ class BridgeCore:self._user_puppets[external_user_id] = client.client_idself._puppet_matrix_ids.add(client.matrix_user_id)+ self._adapter.prime_mention_targets({external_username: external_user_id})logger.info("Created puppet %s for external user %s on bridge %s",diff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.pyindex 730412727..6ad45df86 100644--- a/core/switch_core/bridges/collaboration/slack/adapter.py+++ b/core/switch_core/bridges/collaboration/slack/adapter.py@@ -64,8 +64,9 @@ class SlackAdapter(CollaborationAdapter):# message per channel — used to thread the "thinking" indicator into the# conversation the agent is responding to.self._last_thread_ts: dict[str, str] = {}- # Slack username → user id, for resolving outbound @mentions to real- # Slack mentions. Populated as users are resolved.+ # Folded Slack username → user id, for resolving outbound @mentions to+ # real Slack mentions. Primed from the bridge's known external users and+ # topped up as new ones are resolved.self._username_to_id: dict[str, str] = {}self._thinking_ts: dict[tuple[str, str], str] = {}@@ -672,6 +673,22 @@ class SlackAdapter(CollaborationAdapter):message = re.sub(r"<(https?://[^|>]+)\|([^>]+)>", r"[\2](\1)", message)return re.sub(r"<(https?://[^>]+)>", r"\1", message)+ def prime_mention_targets(self, targets: dict[str, str]) -> None:+ for name, external_id in targets.items():+ self._remember_mention_target(name, external_id)++ def _remember_mention_target(self, name: str, external_id: str) -> None:+ """Record a name → Slack id pair for outbound mention rendering.++ Slack handles are case-insensitive, so the map is keyed on the folded+ name. App and bot senders also reach here — their `external_id` is a+ `B…` bot id, which cannot form a valid user mention — so only real user+ ids (`U…`, or `W…` on enterprise grid) are kept; emitting `<@B…>` would+ render as broken markup rather than a mention."""+ if not external_id.startswith(("U", "W")):+ return+ self._username_to_id[name.casefold()] = external_id+def _translate_mentions_to_slack(self, content: str) -> str:"""Rewrite `@username` to a Slack `<@USER_ID>` mention for users we know,so Slack renders the person's display name. Unknown names (e.g. agents,@@ -679,10 +696,10 @@ class SlackAdapter(CollaborationAdapter):def _replace(match: re.Match[str]) -> str:username = match.group(1)- user_id = self._username_to_id.get(username)+ user_id = self._username_to_id.get(username.casefold())return f"<@{user_id}>" if user_id else match.group(0)- return re.sub(r"@([a-z0-9][a-z0-9._-]*)", _replace, content)+ return re.sub(r"@([A-Za-z0-9][A-Za-z0-9._-]*)", _replace, content)# ── Socket Mode event handling ───────────────────────────────────────────@@ -1107,7 +1124,7 @@ class SlackAdapter(CollaborationAdapter):)resolved = SlackUser(name=name, display_name=display_name)self._user_cache[slack_user_id] = resolved- self._username_to_id[name] = slack_user_id+ self._remember_mention_target(name, slack_user_id)return resolvedexcept SlackApiError as e:logger.warning("Failed to resolve Slack user %s: %s", slack_user_id, e)diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_mention_resolution.py b/core/tests/switch_core/bridges/collaboration/test_bridge_mention_resolution.pynew file mode 100644index 000000000..0f2ae6a9c--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_mention_resolution.py@@ -0,0 +1,161 @@+from __future__ import annotations++from collections.abc import AsyncIterator+from contextlib import asynccontextmanager+from types import SimpleNamespace+from typing import Any++from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.slack.adapter import (+ SlackAdapter,+ SlackConnectionConfig,+)++# Outbound `@name` mentions are rewritten to real Slack `<@U…>` mentions from a+# name → id map held in the adapter. The map used to be filled only as a side+# effect of resolving an inbound sender, so it was empty after every restart and+# a person was mentionable only once they happened to post again — the mention+# went out as plain text and they were never notified. The `external_users` table+# holds both halves of that mapping permanently, so the bridge (which has DB+# access; the adapter deliberately does not) primes the adapter from it.++BRIDGE_ID = "bridge-1"+++def _adapter() -> SlackAdapter:+ return SlackAdapter(+ config=SlackConnectionConfig(+ bot_token="xoxb-test",+ app_token="xapp-test",+ workspace_id="T123",+ )+ )+++def _external_user(username: str, external_id: str, client_id: str) -> SimpleNamespace:+ return SimpleNamespace(+ external_username=username,+ external_user_id=external_id,+ client_id=client_id,+ )+++def _session_factory() -> Any:+ async def _commit() -> None:+ return None++ @asynccontextmanager+ async def _factory() -> AsyncIterator[object]:+ yield SimpleNamespace(commit=_commit)++ return _factory+++def _loading_bridge(adapter: SlackAdapter, users: list[SimpleNamespace]) -> Any:+ """A BridgeCore stand-in with just what `_load_existing_puppets` touches."""++ async def _get_by_bridge(_session: object, bridge_id: str) -> list[SimpleNamespace]:+ assert bridge_id == BRIDGE_ID+ return users++ async def _get_client(_session: object, _client_id: str) -> None:+ return None++ return SimpleNamespace(+ _adapter=adapter,+ _bridge_id=BRIDGE_ID,+ _session_factory=_session_factory(),+ _external_user_store=SimpleNamespace(get_by_bridge=_get_by_bridge),+ _client_store=SimpleNamespace(get=_get_client),+ _client_lifecycle=SimpleNamespace(get=lambda _id: None),+ _user_puppets={},+ _puppet_matrix_ids=set(),+ )+++async def test_startup_priming_makes_a_never_seen_user_mentionable() -> None:+ adapter = _adapter()+ bridge = _loading_bridge(adapter, [_external_user("doe.jane", "U123", "client-1")])++ # Nothing has posted since startup, so the live-resolution path has not run.+ assert adapter.translate_outbound("@doe.jane ping") == "@doe.jane ping"++ await BridgeCore._load_existing_puppets(bridge)++ assert adapter.translate_outbound("@doe.jane ping") == "<@U123> ping"+++async def test_priming_resolves_a_handle_with_capitals() -> None:+ adapter = _adapter()+ bridge = _loading_bridge(+ adapter, [_external_user("Timo.Meyer", "U456", "client-2")]+ )++ await BridgeCore._load_existing_puppets(bridge)++ # The mention pattern and the lookup are both case-insensitive: Slack handles+ # are, and the token a sender types need not match the stored casing.+ assert adapter.translate_outbound("@Timo.Meyer ping") == "<@U456> ping"+ assert adapter.translate_outbound("@timo.meyer ping") == "<@U456> ping"+++async def test_app_rows_are_skipped_while_human_rows_are_primed() -> None:+ adapter = _adapter()+ # An app's row stores its display name against a `B…` bot id, which cannot+ # form a valid user mention. Priming must skip it while still taking the+ # human row alongside it — asserting both in one pass so this cannot pass by+ # virtue of nothing being primed at all.+ bridge = _loading_bridge(+ adapter,+ [+ _external_user("datadog", "BDATADOG", "client-3"),+ _external_user("doe.jane", "U123", "client-1"),+ ],+ )++ await BridgeCore._load_existing_puppets(bridge)++ assert adapter.translate_outbound("@datadog alert") == "@datadog alert"+ assert adapter.translate_outbound("@doe.jane alert") == "<@U123> alert"+++async def test_new_puppet_is_mentionable_without_waiting_for_a_restart() -> None:+ adapter = _adapter()+ created_client = SimpleNamespace(+ client_id="client-9", matrix_user_id="@ext_new:switch.local"+ )++ async def _get_by_name(_session: object, _name: str) -> None:+ return None++ async def _create_and_start(**_kwargs: Any) -> SimpleNamespace:+ return created_client++ async def _create(_session: object, _user: object) -> None:+ return None++ bridge = SimpleNamespace(+ _adapter=adapter,+ _bridge_id=BRIDGE_ID,+ _bridge_type="slack",+ _session_factory=_session_factory(),+ _puppet_locks={},+ _user_puppets={},+ _puppet_matrix_ids=set(),+ _agent_store=SimpleNamespace(get_by_name=_get_by_name),+ _client_lifecycle=SimpleNamespace(create_and_start=_create_and_start),+ _external_user_store=SimpleNamespace(create=_create),+ )++ await BridgeCore._create_puppet(bridge, "U789", "new.person")++ assert adapter.translate_outbound("@new.person welcome") == "<@U789> welcome"+++def test_unknown_name_is_still_left_as_plain_text() -> None:+ # Agents have no Slack id, so their names must survive untouched rather than+ # being rewritten into something Slack cannot render.+ adapter = _adapter()+ adapter.prime_mention_targets({"doe.jane": "U123"})++ assert adapter.translate_outbound("@some-agent hello") == "@some-agent hello"