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(slack): resolve agent mentions that crossed a workspace boundary (#327)
Louis Amaudruz9097eb35dfd1
diff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.pyindex d0f0dc658..326145513 100644--- a/core/switch_core/bridges/collaboration/slack/adapter.py+++ b/core/switch_core/bridges/collaboration/slack/adapter.py@@ -35,6 +35,9 @@ from switch_core.bridges.collaboration.models import (InboundUserJoin,OutboundAttachment,)+from switch_core.bridges.collaboration.slack.agent_groups import (+ SlackAgentGroupDirectory,+)from switch_core.bridges.collaboration.slack.avatar import on_slack_backgroundlogger = logging.getLogger(__name__)@@ -226,6 +229,13 @@ class SlackAdapter(CollaborationAdapter):# opened for it — which was most turns.runtime_state_follows_anchor: ClassVar[bool] = True+ # Every Slack bridge in this process shares one, because resolving a+ # mention that crossed a workspace boundary means reading a group another+ # bridge minted. Rebind it to a fresh instance to isolate a test.+ agent_group_directory: ClassVar[SlackAgentGroupDirectory] = (+ SlackAgentGroupDirectory()+ )+def __init__(self, *, config: SlackConnectionConfig) -> None:super().__init__()self._config = config@@ -374,6 +384,7 @@ class SlackAdapter(CollaborationAdapter):passself._socket_client = Noneself._web_client = None+ self.agent_group_directory.forget(self._team_id)logger.info("Slack adapter stopped")# ── Messaging ────────────────────────────────────────────────────────────@@ -1562,6 +1573,7 @@ class SlackAdapter(CollaborationAdapter):await self._web_client.usergroups_disable(usergroup=group_id)self._agent_group_ids.pop(folded, None)self._agent_group_names.pop(group_id, None)+ self.agent_group_directory.discard(self._team_id, group_id)self._agent_groups_disabled[folded] = group_idlogger.info("Disabled Slack user group %s for agent %s", group_id, agent_name)@@ -1706,6 +1718,7 @@ class SlackAdapter(CollaborationAdapter):def _remember_agent_group(self, group_id: str, agent_name: str) -> None:self._agent_group_ids[agent_name.casefold()] = group_idself._agent_group_names[group_id] = agent_name+ self.agent_group_directory.add(self._team_id, group_id, agent_name)@staticmethoddef _usergroup_handle(agent_name: str) -> str:@@ -1783,6 +1796,7 @@ class SlackAdapter(CollaborationAdapter):else:self._remember_agent_group(group_id, name)+ self.agent_group_directory.replace(self._team_id, self._agent_group_names)self._agent_groups_loaded = Truelogger.info("Loaded %d Slack agent user groups (%d disabled, %d other groups seen)",@@ -2401,11 +2415,19 @@ class SlackAdapter(CollaborationAdapter):resolves to its real name. Groups we do not know are left untouched: aworkspace's own group is not an agent, and rewriting it would invent amention of someone who does not exist.++ An id this workspace never minted may still be an agent's. On an+ Enterprise Grid org the composer offers a sibling workspace's group, so+ the mention arrives here naming a group only that bridge knows —+ consulting the shared directory is what keeps the agent addressable+ from either side of the org."""def _replace(match: re.Match[str]) -> str:group_id = match.group(1)- agent_name = self._agent_group_names.get(group_id)+ agent_name = self._agent_group_names.get(+ group_id+ ) or self.agent_group_directory.resolve(group_id)if agent_name:return f"@{agent_name}"label = match.group(2)diff --git a/core/switch_core/bridges/collaboration/slack/agent_groups.py b/core/switch_core/bridges/collaboration/slack/agent_groups.pynew file mode 100644index 000000000..c864399e9--- /dev/null+++ b/core/switch_core/bridges/collaboration/slack/agent_groups.py@@ -0,0 +1,42 @@+from __future__ import annotations++from collections.abc import Mapping+++class SlackAgentGroupDirectory:+ """Agent user group id → agent name, pooled across every Slack workspace.++ A workspace bot token lists only that workspace's user groups, so each+ bridge mints and learns its own group per agent. An Enterprise Grid+ composer does not respect that boundary: it offers an agent's group from a+ sibling workspace in the same org, so a mention can arrive at one bridge+ carrying an id that only another bridge has ever seen. Slack has no call+ that resolves a user group by id, which leaves the bridge that created it+ as the only place its meaning exists.++ Contributions are kept per workspace so a bridge reloading or shutting down+ withdraws its own without disturbing anyone else's.+ """++ def __init__(self) -> None:+ self._by_workspace: dict[str, dict[str, str]] = {}++ def replace(self, workspace_id: str, agent_names: Mapping[str, str]) -> None:+ """Publish a workspace's whole set, dropping what it published before."""+ self._by_workspace[workspace_id] = dict(agent_names)++ def add(self, workspace_id: str, group_id: str, agent_name: str) -> None:+ self._by_workspace.setdefault(workspace_id, {})[group_id] = agent_name++ def discard(self, workspace_id: str, group_id: str) -> None:+ self._by_workspace.get(workspace_id, {}).pop(group_id, None)++ def forget(self, workspace_id: str) -> None:+ self._by_workspace.pop(workspace_id, None)++ def resolve(self, group_id: str) -> str | None:+ for groups in self._by_workspace.values():+ agent_name = groups.get(group_id)+ if agent_name is not None:+ return agent_name+ return Nonediff --git a/core/tests/switch_core/bridges/collaboration/test_slack_agent_usergroups.py b/core/tests/switch_core/bridges/collaboration/test_slack_agent_usergroups.pyindex 602845865..359ba1e28 100644--- a/core/tests/switch_core/bridges/collaboration/test_slack_agent_usergroups.py+++ b/core/tests/switch_core/bridges/collaboration/test_slack_agent_usergroups.py@@ -18,6 +18,19 @@ from switch_core.bridges.collaboration.slack.adapter import (SlackAdapter,SlackConnectionConfig,)+from switch_core.bridges.collaboration.slack.agent_groups import (+ SlackAgentGroupDirectory,+)++[email protected](autouse=True)+def _fresh_group_directory() -> Any:+ """Every Slack bridge in a process shares one directory, so give each test+ its own rather than letting one test's workspaces answer another's."""+ original = SlackAdapter.agent_group_directory+ SlackAdapter.agent_group_directory = SlackAgentGroupDirectory()+ yield+ SlackAdapter.agent_group_directory = originaldef _run(coro: Any) -> Any:@@ -95,7 +108,10 @@ class FakeWebClient:def _adapter(- *, enabled: bool = True, groups: list[dict[str, Any]] | None = None+ *,+ enabled: bool = True,+ groups: list[dict[str, Any]] | None = None,+ team_id: str = "T123",) -> tuple[SlackAdapter, FakeWebClient]:adapter = SlackAdapter(config=SlackConnectionConfig(@@ -105,6 +121,9 @@ def _adapter(agent_usergroups=enabled,))+ # Normally set from auth.test; the shared directory keys contributions on+ # it, so two adapters in one test must not look like the same workspace.+ adapter._team_id = team_idclient = FakeWebClient(groups)adapter._web_client = client # type: ignore[assignment]return adapter, client@@ -373,6 +392,71 @@ def test_outbound_prefers_a_real_person_over_an_agent_group() -> None:assert adapter._translate_mentions_to_slack("@ambiguous") == "<@U123>"+# ── Two workspaces in one org ────────────────────────────────────────────────+#+# A bot token lists only its own workspace's groups, so each bridge mints its+# own group per agent. An Enterprise Grid composer ignores that boundary and+# offers a sibling workspace's group, so the mention arrives naming an id the+# receiving bridge never minted — and Slack has no call to resolve one by id.+++def test_a_mention_of_a_sibling_workspaces_group_resolves() -> None:+ """CHOO-2521: tagging an agent in the org's other workspace did nothing."""+ home, _ = _adapter(groups=[_agent_group("S001", "flint-tracker")], team_id="T111")+ _run(home._load_agent_usergroups())++ sibling, _ = _adapter(+ groups=[_agent_group("S002", "flint-tracker")], team_id="T222"+ )+ _run(sibling._load_agent_usergroups())++ assert (+ sibling.translate_inbound("<!subteam^S001> please run the summary")+ == "@flint-tracker please run the summary"+ )+++def test_a_sibling_workspaces_own_group_is_still_not_an_agent() -> None:+ home, _ = _adapter(groups=[_plain_group("S900", "designers", "Designers")])+ _run(home._load_agent_usergroups())++ sibling, _ = _adapter(team_id="T222")+ _run(sibling._load_agent_usergroups())++ assert sibling.translate_inbound("<!subteam^S900> ping") == "<!subteam^S900> ping"+++def test_a_reload_withdraws_a_group_that_is_gone() -> None:+ home, client = _adapter(groups=[_agent_group("S001", "flint-tracker")])+ _run(home._load_agent_usergroups())+ sibling, _ = _adapter(team_id="T222")++ client.groups = []+ _run(home._load_agent_usergroups())++ assert sibling.translate_inbound("<!subteam^S001> hi") == "<!subteam^S001> hi"+++def test_removing_an_agent_withdraws_it_from_the_other_workspace() -> None:+ home, _ = _adapter(groups=[_agent_group("S001", "flint-tracker")])+ _run(home._load_agent_usergroups())+ sibling, _ = _adapter(team_id="T222")++ _run(home.remove_agent_identity("flint-tracker"))++ assert sibling.translate_inbound("<!subteam^S001> hi") == "<!subteam^S001> hi"+++def test_a_stopped_bridge_stops_answering_for_its_workspace() -> None:+ home, _ = _adapter(groups=[_agent_group("S001", "flint-tracker")])+ _run(home._load_agent_usergroups())+ sibling, _ = _adapter(team_id="T222")++ _run(home.stop())++ assert sibling.translate_inbound("<!subteam^S001> hi") == "<!subteam^S001> hi"++# ── Rate limiting ────────────────────────────────────────────────────────────diff --git a/docs/old/bridges/SLACK_SETUP.md b/docs/old/bridges/SLACK_SETUP.mdindex bafd563c1..f8d99c682 100644--- a/docs/old/bridges/SLACK_SETUP.md+++ b/docs/old/bridges/SLACK_SETUP.md@@ -252,6 +252,16 @@ groups. Agents stay addressable by typing their name, exactly as before — youlose the autocomplete, nothing else. It does not retry per agent or repeat thewarning on every startup.+**Several workspaces in one org.** A bot token lists only its own workspace's+user groups, so each bridge mints its own group per agent and knows only those+ids. An Enterprise Grid composer does not respect that boundary — it offers a+sibling workspace's group as well, so a mention can arrive at one bridge naming+a group only another one created. Slack has no call that resolves a user group+by id, so the bridges pool what they mint and read each other's, which is what+keeps an agent taggable from either workspace. It follows that both workspaces+must be bridged to the **same** Switch server; two servers cannot see each+other's groups, and a mention that crossed between them stays unresolved.+### Native session status (`agent_sessions`)**On by default.** A turn opens a Slack **agent session** and streams its