Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

fix(discord): a renamed channel renames the room linked to it

raullopez-sandbox1ac057911be1
diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.py
index c70d98b08..82044deb0 100644
--- a/core/switch_core/bridges/collaboration/adapter.py
+++ b/core/switch_core/bridges/collaboration/adapter.py
@@ -626,6 +626,11 @@ class PlatformAdapter(ABC):
# Set by set_channel_migration_handler. Called with (old_id, new_id)
# when the platform reissues a channel's id.
self._on_channel_migrated: Callable[[str, str], Awaitable[None]] | None = None
+ # Set by set_channel_rename_handler. Called with (channel_id, old_name,
+ # new_name) when the platform reports a channel renamed.
+ self._on_channel_renamed: Callable[[str, str, str], Awaitable[None]] | None = (
+ None
+ )
# Set by set_channel_type_handler. Called with (channel_id, type) when
# the adapter learns a channel's type from the platform.
self._on_channel_type_learned: (
@@ -1863,6 +1868,14 @@ class PlatformAdapter(ABC):
the platform forwards them, while nothing inbound matches a room again."""
self._on_channel_migrated = handler
+ def set_channel_rename_handler(
+ self, handler: Callable[[str, str, str], Awaitable[None]]
+ ) -> None:
+ """Install the callback an adapter calls when a channel is renamed on
+ the platform, so the room linked to it can take the new name. Used by
+ the adapters whose platform reports it (Discord)."""
+ self._on_channel_renamed = handler
+
def set_channel_type_handler(
self, handler: Callable[[str, ChannelType], Awaitable[None]]
) -> None:
diff --git a/core/switch_core/bridges/collaboration/collaboration_core.py b/core/switch_core/bridges/collaboration/collaboration_core.py
index e5625c15a..d8f82c75f 100644
--- a/core/switch_core/bridges/collaboration/collaboration_core.py
+++ b/core/switch_core/bridges/collaboration/collaboration_core.py
@@ -494,6 +494,7 @@ class CollaborationCore:
await self._load_existing_human_actors()
self._adapter.set_channel_migration_handler(self._handle_channel_migrated)
self._adapter.set_channel_type_handler(self._record_channel_type)
+ self._adapter.set_channel_rename_handler(self._handle_channel_renamed)
self._adapter.set_agent_presentation_resolver(self._agent_presentation)
# A bridge on a shared connection that started before the connection
# was up is attached later (when it comes up, or on its first event).
@@ -854,6 +855,35 @@ class CollaborationCore:
channel_type,
)
+ async def _handle_channel_renamed(
+ self, channel_id: str, old_name: str, new_name: str
+ ) -> None:
+ """Give the room linked to this channel the channel's new name. A room
+ whose name is not the one it was made with from the old channel name
+ was given a title of its own, which is kept."""
+ bridge_name = self._bridge_display_name
+ with tenant_scope(self._bridge_tenant_id):
+ async with tenant_session(
+ self._session_factory, self._bridge_tenant_id
+ ) as session:
+ room = await self._room_store.get_by_external_channel(
+ session, bridge_id=self._bridge_id, external_channel_id=channel_id
+ )
+ if room is None:
+ return
+ if room.name not in (f"{bridge_name}: {old_name}", old_name):
+ logger.info(
+ "Room %s keeps its own title though its %s channel was "
+ "renamed to %s",
+ room.id,
+ self._bridge_type,
+ new_name,
+ )
+ return
+ await self._room_service.update_room(
+ room.id, name=f"{bridge_name}: {new_name}"
+ )
+
# ── Inbound (platform → room) ───────────────────────────────────────────
async def _agent_presentation(self, agent_name: str) -> AgentPresentation | None:
diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.py
index 10d706c12..537dee42f 100644
--- a/core/switch_core/bridges/collaboration/discord/adapter.py
+++ b/core/switch_core/bridges/collaboration/discord/adapter.py
@@ -734,6 +734,7 @@ class DiscordAdapter(PlatformAdapter):
conn.register_message_handler(self._guild_id, self._handle_message)
conn.set_dm_handler(self._handle_message)
conn.set_interaction_handler(self._make_on_interaction())
+ conn.set_channel_update_handler(self.dispatch_channel_update)
await conn.connect(
commands=build_app_commands(self._handle_slash_command),
)
@@ -828,6 +829,16 @@ class DiscordAdapter(PlatformAdapter):
"""
await self._handle_slash_command(interaction, command, values)
+ async def dispatch_channel_update(
+ self, before: discord.abc.GuildChannel, after: discord.abc.GuildChannel
+ ) -> None:
+ """A channel in this bridge's guild was renamed: tell the bridge, so
+ the room linked to it follows. Other settings changes are not news."""
+ if after.guild.id != self._guild_id or before.name == after.name:
+ return
+ if self._on_channel_renamed is not None:
+ await self._on_channel_renamed(str(after.id), before.name, after.name)
+
async def dispatch_interaction(self, interaction: discord.Interaction) -> None:
"""Handle one press on a card's button the shared client routed here.
diff --git a/core/switch_core/bridges/collaboration/discord/connection.py b/core/switch_core/bridges/collaboration/discord/connection.py
index 384ae4b77..896ccd496 100644
--- a/core/switch_core/bridges/collaboration/discord/connection.py
+++ b/core/switch_core/bridges/collaboration/discord/connection.py
@@ -105,12 +105,29 @@ class DiscordConnection:
self._guild_join_handler: Callable[[discord.Guild], Awaitable[None]] | None = (
None
)
+ # A guild channel's settings changed (its name, say). One handler for
+ # the whole socket, as for presses; unset means the change is dropped.
+ self._channel_update_handler: (
+ Callable[
+ [discord.abc.GuildChannel, discord.abc.GuildChannel], Awaitable[None]
+ ]
+ | None
+ ) = None
def set_interaction_handler(
self, handler: Callable[[discord.Interaction], Awaitable[None]] | None
) -> None:
self._interaction_handler = handler
+ def set_channel_update_handler(
+ self,
+ handler: Callable[
+ [discord.abc.GuildChannel, discord.abc.GuildChannel], Awaitable[None]
+ ]
+ | None,
+ ) -> None:
+ self._channel_update_handler = handler
+
def register_message_handler(
self, guild_id: int, handler: Callable[[discord.Message], Awaitable[None]]
) -> None:
@@ -222,6 +239,7 @@ class DiscordConnection:
# through the handler set via `set_interaction_handler`, or dropped when
# none is set.
client.event(self._make_on_interaction())
+ client.event(self._make_on_guild_channel_update())
if self._guild_remove_handler is not None:
client.event(self._make_on_guild_remove())
if self._guild_join_handler is not None:
@@ -366,6 +384,25 @@ class DiscordConnection:
return on_guild_remove
+ def _make_on_guild_channel_update(
+ self,
+ ) -> Callable[
+ [discord.abc.GuildChannel, discord.abc.GuildChannel],
+ Coroutine[Any, Any, None],
+ ]:
+ async def on_guild_channel_update(
+ before: discord.abc.GuildChannel, after: discord.abc.GuildChannel
+ ) -> None:
+ handler = self._channel_update_handler
+ if handler is None:
+ return
+ try:
+ await handler(before, after)
+ except Exception:
+ logger.exception("Failed to handle a Discord channel update")
+
+ return on_guild_channel_update
+
def _make_on_guild_join(
self,
) -> Callable[[discord.Guild], Coroutine[Any, Any, None]]:
diff --git a/core/switch_core/bridges/collaboration/discord/gateway.py b/core/switch_core/bridges/collaboration/discord/gateway.py
index 78584f5a5..9697f54e6 100644
--- a/core/switch_core/bridges/collaboration/discord/gateway.py
+++ b/core/switch_core/bridges/collaboration/discord/gateway.py
@@ -144,6 +144,7 @@ class DiscordGatewayClient:
# (guard G4).
self._connection.set_guild_message_handler(self._on_guild_message)
self._connection.set_interaction_handler(self._on_interaction)
+ self._connection.set_channel_update_handler(self._on_channel_update)
self._connection.set_guild_lifecycle_handlers(
on_remove=self._on_guild_remove,
on_join=self._on_guild_join,
@@ -312,6 +313,27 @@ class DiscordGatewayClient:
adapter.attach_shared_connection(self._connection)
await adapter.dispatch_inbound(message)
+ async def _on_channel_update(
+ self, before: discord.abc.GuildChannel, after: discord.abc.GuildChannel
+ ) -> None:
+ """Route a guild channel's change to the bridge its guild resolves to,
+ fresh and with no tenant bound, as a message is (G1). A guild with no
+ install is dropped."""
+ if before.name == after.name:
+ return
+ with no_tenant():
+ try:
+ target = await self._install_service.resolve_by_workspace(
+ platform=_PLATFORM, workspace_id=str(after.guild.id)
+ )
+ except (WebhookWorkspaceUnknown, WebhookBridgeUnavailable):
+ return
+ adapter = target.adapter
+ if not isinstance(adapter, DiscordAdapter):
+ return
+ adapter.attach_shared_connection(self._connection)
+ await adapter.dispatch_channel_update(before, after)
+
async def _on_slash(
self,
interaction: discord.Interaction,
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py
index 9f5e5a568..8aecf9fd5 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py
@@ -264,6 +264,9 @@ def test_the_resolver_is_installed_before_the_adapter_starts() -> None:
def set_channel_type_handler(self, handler: Any) -> None:
return None
+ def set_channel_rename_handler(self, handler: Any) -> None:
+ pass
+
def set_agent_presentation_resolver(self, resolver: Any) -> None:
installed.append(resolver)
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py
index 8836b716a..5652fd9db 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py
@@ -91,6 +91,9 @@ def test_the_handler_is_installed_before_the_adapter_starts() -> None:
def set_channel_type_handler(self, handler: Any) -> None:
return None
+ def set_channel_rename_handler(self, handler: Any) -> None:
+ pass
+
def set_agent_presentation_resolver(self, resolver: Any) -> None:
# Not what this test is about; present so the stub satisfies what
# `start` installs on its adapter.
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_rename.py b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_rename.py
new file mode 100644
index 000000000..2bf38bbaf
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_rename.py
@@ -0,0 +1,95 @@
+"""A channel renamed on the platform renames the room linked to it, unless the
+room was given a title of its own; another channel's rename touches nothing."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+from switch_core.bridges.collaboration.collaboration_core import CollaborationCore
+from switch_core.bridges.collaboration.discord.adapter import DiscordAdapter
+from switch_core.tenant_context import current_tenant_id
+
+
+class _FakeSession:
+ async def __aenter__(self) -> _FakeSession:
+ return self
+
+ async def __aexit__(self, *exc: Any) -> None:
+ return None
+
+
+class _RoomStore:
+ def __init__(self, rooms: dict[str, SimpleNamespace]) -> None:
+ self._rooms = rooms
+
+ async def get_by_external_channel(
+ self, session: Any, bridge_id: str, external_channel_id: str
+ ) -> SimpleNamespace | None:
+ assert bridge_id == "bridge-1"
+ return self._rooms.get(external_channel_id)
+
+
+class _RoomService:
+ def __init__(self) -> None:
+ self.renamed: list[tuple[str, str, str | None]] = []
+
+ async def update_room(self, room_id: str, *, name: str) -> None:
+ self.renamed.append((room_id, name, current_tenant_id()))
+
+
+def _bridge(rooms: dict[str, SimpleNamespace]) -> SimpleNamespace:
+ session = _FakeSession()
+ return SimpleNamespace(
+ _session_factory=lambda: session,
+ _room_store=_RoomStore(rooms),
+ _room_service=_RoomService(),
+ _bridge_id="bridge-1",
+ _bridge_tenant_id="tenant-1",
+ _bridge_type="discord",
+ _bridge_display_name="Discord",
+ )
+
+
+async def _rename(bridge: SimpleNamespace, channel_id: str, old: str, new: str) -> None:
+ await CollaborationCore._handle_channel_renamed(bridge, channel_id, old, new) # type: ignore[arg-type]
+
+
+async def test_the_linked_room_takes_the_channels_new_name() -> None:
+ bridge = _bridge(
+ {
+ "c-1": SimpleNamespace(id="room-1", name="Discord: qa-overnight-adopted"),
+ "c-2": SimpleNamespace(id="room-2", name="Discord: other"),
+ }
+ )
+ await _rename(bridge, "c-1", "qa-overnight-adopted", "qa-adopted-renamed")
+ await _rename(bridge, "c-9", "unlinked", "still-unlinked")
+ assert bridge._room_service.renamed == [
+ ("room-1", "Discord: qa-adopted-renamed", "tenant-1")
+ ]
+
+
+async def test_a_room_with_its_own_title_keeps_it() -> None:
+ bridge = _bridge({"c-1": SimpleNamespace(id="room-1", name="Launch planning")})
+ await _rename(bridge, "c-1", "launch", "launch-2026")
+ assert bridge._room_service.renamed == []
+
+
+async def test_the_adapter_reports_only_a_rename_in_its_own_guild() -> None:
+ reported: list[tuple[str, str, str]] = []
+
+ async def renamed(channel_id: str, old: str, new: str) -> None:
+ reported.append((channel_id, old, new))
+
+ adapter = SimpleNamespace(_guild_id=1, _on_channel_renamed=renamed)
+
+ def channel(guild_id: int, name: str) -> SimpleNamespace:
+ return SimpleNamespace(id=42, name=name, guild=SimpleNamespace(id=guild_id))
+
+ for before, after in (
+ (channel(1, "old"), channel(1, "new")),
+ (channel(2, "old"), channel(2, "new")),
+ (channel(1, "same"), channel(1, "same")),
+ ):
+ await DiscordAdapter.dispatch_channel_update(adapter, before, after) # type: ignore[arg-type]
+ assert reported == [("42", "old", "new")]
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_type_correction.py b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_type_correction.py
index 2168150b9..fb0730665 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_type_correction.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_type_correction.py
@@ -174,6 +174,9 @@ class _StartableAdapter:
def set_channel_type_handler(self, handler: Any) -> None:
self.channel_type_handler = handler
+ def set_channel_rename_handler(self, handler: Any) -> None:
+ pass
+
def set_channel_migration_handler(self, handler: Any) -> None:
return None
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.py b/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.py
index 34334b753..de071f676 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.py
@@ -26,6 +26,9 @@ class _FakeAdapter:
def set_channel_type_handler(self, handler: Any) -> None:
pass
+ def set_channel_rename_handler(self, handler: Any) -> None:
+ pass
+
def set_agent_presentation_resolver(self, resolver: Any) -> None:
pass
diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_gateway_ownership.py b/core/tests/switch_core/bridges/collaboration/test_discord_gateway_ownership.py
index 3f88ccce5..524aa0c2d 100644
--- a/core/tests/switch_core/bridges/collaboration/test_discord_gateway_ownership.py
+++ b/core/tests/switch_core/bridges/collaboration/test_discord_gateway_ownership.py
@@ -70,6 +70,9 @@ class _Connection:
def set_interaction_handler(self, handler: Any) -> None:
pass
+ def set_channel_update_handler(self, handler: Any) -> None:
+ pass
+
def set_guild_lifecycle_handlers(self, **handlers: Any) -> None:
pass