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(rooms): a bridged room follows its channel's name only when named after it

raullopez-sandboxb1d0f9dd9711
diff --git a/console/tooling-e2e/surface/exemptions.json b/console/tooling-e2e/surface/exemptions.json
index a47bb0383..53eec2ab9 100644
--- a/console/tooling-e2e/surface/exemptions.json
+++ b/console/tooling-e2e/surface/exemptions.json
@@ -19,6 +19,7 @@
"POST /gateway/chats/{room_id}/agents": "Switch Console group chats. Covered by core's test_chats_groups.py against real Postgres; no scenario drives Console chats yet (every other /gateway/chats route is still in the backlog), and the stacks the harness builds do not turn on the group_chats flag these routes need.",
"POST /gateway/hosted-controller/machines/{machine_id}/observation": "Needs a hosted controller configured (HOSTED_CONTROLLER_CONFIG_PATH), which no stack the harness builds has.",
"POST /gateway/hosted-controller/machines/{machine_id}/prepare": "Needs a hosted controller configured (HOSTED_CONTROLLER_CONFIG_PATH), which no stack the harness builds has.",
+ "POST /gateway/rooms/{room_id}/sync-name": "Needs a bridged room whose linked channel was renamed on the platform, which the fast lane's stacks cannot stage. Covered by core's test_room_sync_name.py against real Postgres.",
"PUT /gateway/chats/{room_id}/read": "Switch Console read positions. Covered by core's test_chats_groups.py against real Postgres; no scenario drives Console chats yet (every other /gateway/chats route is still in the backlog).",
"WS /gateway/changes/ws": "Console's change-notice socket. What it sends is covered by core's test_changes_socket.py, and the session probe checks it refuses a handshake without a session; no scenario drives Console's lists yet.",
"get_template_status": "Needs an agent created from an official template on a managed machine and then a newer revision of that template; no stack the harness builds has managed agents yet (create_agent is in the backlog). Covered by core's test_template_updates.py."
diff --git a/console/tooling-e2e/surface/server-surface.json b/console/tooling-e2e/surface/server-surface.json
index 9a762ac58..0baec35a0 100644
--- a/console/tooling-e2e/surface/server-surface.json
+++ b/console/tooling-e2e/surface/server-surface.json
@@ -1214,6 +1214,11 @@
"auth": "session",
"flags": []
},
+ {
+ "route": "POST /gateway/rooms/{room_id}/sync-name",
+ "auth": "session",
+ "flags": []
+ },
{
"route": "POST /gateway/rooms/{room_id}/unarchive",
"auth": "session",
diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.py
index 82044deb0..b1672b339 100644
--- a/core/switch_core/bridges/collaboration/adapter.py
+++ b/core/switch_core/bridges/collaboration/adapter.py
@@ -627,10 +627,9 @@ class PlatformAdapter(ABC):
# 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
- )
+ # new_name) when the platform reports a change to a channel (the two
+ # names are the same when it was not a rename).
+ self._on_channel_named: 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: (
@@ -1871,10 +1870,10 @@ class PlatformAdapter(ABC):
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
+ """Install the callback an adapter calls with a channel's name when the
+ platform reports a change to it, so the room linked to it can follow.
+ Used by the adapters whose platform reports it (Discord)."""
+ self._on_channel_named = handler
def set_channel_type_handler(
self, handler: Callable[[str, ChannelType], Awaitable[None]]
diff --git a/core/switch_core/bridges/collaboration/collaboration_core.py b/core/switch_core/bridges/collaboration/collaboration_core.py
index d8f82c75f..8ab3f06ec 100644
--- a/core/switch_core/bridges/collaboration/collaboration_core.py
+++ b/core/switch_core/bridges/collaboration/collaboration_core.py
@@ -53,7 +53,11 @@ from switch_core.db.stores.agent_store import AgentStore
from switch_core.db.stores.bridge_message_map_store import BridgeMessageMapStore
from switch_core.db.stores.client_store import ClientStore
from switch_core.db.stores.external_user_store import ExternalUserStore
-from switch_core.db.stores.room_store import RoomStore
+from switch_core.db.stores.room_store import (
+ LINKED_CHANNEL_NAME_KEY,
+ NAME_SOURCE_KEY,
+ RoomStore,
+)
from switch_core.db.tenant_lookup import tenant_of_room
from switch_core.logging_context import log_context
from switch_core.observability.catalogue import (
@@ -494,7 +498,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_channel_rename_handler(self._handle_channel_named)
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).
@@ -855,13 +859,17 @@ class CollaborationCore:
channel_type,
)
- async def _handle_channel_renamed(
+ async def _handle_channel_named(
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."""
+ """The platform reports this channel's name (renamed from `old_name`,
+ or unchanged). The room linked to it follows when it is named after
+ the channel (`NAME_SOURCE_KEY` "channel"), or, from before that was
+ kept, when its name is exactly the one it was made with from the old
+ channel name. Any other room keeps its name, and the channel's is
+ recorded for whoever wants to take it (`/rooms/{id}/sync-name`)."""
bridge_name = self._bridge_display_name
+ name = f"{bridge_name}: {new_name}"
with tenant_scope(self._bridge_tenant_id):
async with tenant_session(
self._session_factory, self._bridge_tenant_id
@@ -871,18 +879,17 @@ class CollaborationCore:
)
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}"
- )
+ metadata = room.metadata_ or {}
+ source = metadata.get(NAME_SOURCE_KEY)
+ follows = source == "channel" or (
+ source is None
+ and old_name != new_name
+ and room.name == f"{bridge_name}: {old_name}"
+ )
+ if follows and room.name != name:
+ await self._room_service.take_platform_name(room.id, name, new_name)
+ elif metadata.get(LINKED_CHANNEL_NAME_KEY) != new_name:
+ await self._room_service.record_channel_name(room.id, new_name)
# ── Inbound (platform → room) ───────────────────────────────────────────
@@ -1561,6 +1568,9 @@ class CollaborationCore:
# Adopted from a channel that appeared on the platform, not asked
# for by anyone in Switch.
created_by_kind="system",
+ named_after_channel=(
+ channel_name if channel_type != "direct" and channel_name else None
+ ),
)
try:
diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.py
index 2387beee8..bb7661337 100644
--- a/core/switch_core/bridges/collaboration/discord/adapter.py
+++ b/core/switch_core/bridges/collaboration/discord/adapter.py
@@ -832,12 +832,13 @@ class DiscordAdapter(PlatformAdapter):
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:
+ """A channel in this bridge's guild changed: tell the bridge what it is
+ called now, so the room linked to it follows a rename, including one
+ made before the bridge followed renames."""
+ if after.guild.id != self._guild_id:
return
- if self._on_channel_renamed is not None:
- await self._on_channel_renamed(str(after.id), before.name, after.name)
+ if self._on_channel_named is not None:
+ await self._on_channel_named(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/gateway.py b/core/switch_core/bridges/collaboration/discord/gateway.py
index 9697f54e6..9f7751091 100644
--- a/core/switch_core/bridges/collaboration/discord/gateway.py
+++ b/core/switch_core/bridges/collaboration/discord/gateway.py
@@ -319,8 +319,6 @@ class DiscordGatewayClient:
"""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(
diff --git a/core/switch_core/db/stores/room_store.py b/core/switch_core/db/stores/room_store.py
index 330ddc1c2..b51786a94 100644
--- a/core/switch_core/db/stores/room_store.py
+++ b/core/switch_core/db/stores/room_store.py
@@ -31,6 +31,13 @@ from switch_core.db.models import (
)
from switch_core.db.stores.delivery_cursor_store import DeliveryCursorStore
+# Where a room's name came from, in its `metadata`: "channel" for a bridged
+# room named after its channel (it follows the channel's renames), "custom"
+# once a person or an agent names it. Absent on rooms from before it was kept.
+NAME_SOURCE_KEY = "name_source"
+# The linked platform channel's name as the bridge last saw it.
+LINKED_CHANNEL_NAME_KEY = "linked_channel_name"
+
# Keys in a room's `metadata` for the follow-the-conversation settings. Both
# are absent by default (follow-ups on, no main agent), so rooms made before
# the settings existed need no backfill.
@@ -767,6 +774,8 @@ class RoomStore:
raise ValueError(f"Room not found: {room_id}")
if name is not None:
room.name = name
+ # Named by someone: a platform's channel name no longer replaces it.
+ room.metadata_ = {**(room.metadata_ or {}), NAME_SOURCE_KEY: "custom"}
if description is not None:
room.description = description
if instructions is not None:
@@ -779,6 +788,34 @@ class RoomStore:
room.write_visibility = write_visibility
await session.flush()
+ async def set_platform_name(
+ self, session: AsyncSession, room_id: str, name: str, channel_name: str
+ ) -> None:
+ """Name the room after its platform channel, so it follows the
+ channel's renames from now on."""
+ room = await session.get(Room, room_id)
+ if room is None:
+ raise ValueError(f"Room not found: {room_id}")
+ room.name = name
+ room.metadata_ = {
+ **(room.metadata_ or {}),
+ NAME_SOURCE_KEY: "channel",
+ LINKED_CHANNEL_NAME_KEY: channel_name,
+ }
+ await session.flush()
+
+ async def record_channel_name(
+ self, session: AsyncSession, room_id: str, channel_name: str
+ ) -> None:
+ room = await session.get(Room, room_id)
+ if room is None:
+ raise ValueError(f"Room not found: {room_id}")
+ room.metadata_ = {
+ **(room.metadata_ or {}),
+ LINKED_CHANNEL_NAME_KEY: channel_name,
+ }
+ await session.flush()
+
async def set_group(
self, session: AsyncSession, room_id: str, group_id: str | None
) -> None:
diff --git a/core/switch_core/gateway/rooms.py b/core/switch_core/gateway/rooms.py
index 8965ead77..73e19108e 100644
--- a/core/switch_core/gateway/rooms.py
+++ b/core/switch_core/gateway/rooms.py
@@ -24,7 +24,7 @@ from switch_core.db.models import Room, RoomGroup, User, require_tenant_id
from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
from switch_core.db.stores.external_user_store import ExternalUserStore
from switch_core.db.stores.room_group_store import RoomGroupStore
-from switch_core.db.stores.room_store import RoomStore
+from switch_core.db.stores.room_store import LINKED_CHANNEL_NAME_KEY, RoomStore
from switch_core.db.stores.template_store import TemplateStore
from switch_core.db.stores.user_store import UserStore
from switch_core.feature_flags import AGENT_MANAGEMENT, SWITCH_BUDDY
@@ -251,6 +251,11 @@ async def _build_room_detail(
join_event_listeners=join_event_listeners,
archived_at=str(room.archived_at) if room.archived_at else None,
channel_on_delete=_channel_on_delete(room, bridge_type),
+ linked_channel_name=(
+ (room.metadata_ or {}).get(LINKED_CHANNEL_NAME_KEY)
+ if room.external_channel_id
+ else None
+ ),
)
@@ -1248,6 +1253,39 @@ async def _set_archived(
)
[email protected]("/{room_id}/sync-name")
+async def sync_room_name(
+ room_id: str,
+ session: Annotated[AsyncSession, Depends(get_session)],
+ room_service: Annotated[RoomService, Depends(get_room_service)],
+ room_store: Annotated[RoomStore, Depends(get_room_store)],
+ bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],
+ external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],
+ protocol: Annotated[AgentCore, Depends(get_protocol)],
+ user: Annotated[User, Depends(get_current_user)],
+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
+) -> RoomDetail:
+ """Name the room after its linked channel (`linked_channel_name`), as the
+ bridge names its own rooms, so it follows the channel's renames from now
+ on. The room's owner or an admin only."""
+ room = await _require_room(session, room_store, room_id, user, "delete", is_admin)
+ channel_name = (room.metadata_ or {}).get(LINKED_CHANNEL_NAME_KEY)
+ bridge = await bridge_store.get(session, room.bridge_id) if room.bridge_id else None
+ if not room.external_channel_id or bridge is None or not channel_name:
+ raise HTTPException(
+ status_code=409,
+ detail="Switch has not seen the name of a channel linked to this room.",
+ )
+ await room_service.take_platform_name(
+ room.id, f"{bridge.display_name}: {channel_name}", channel_name
+ )
+ await session.commit()
+ await session.refresh(room)
+ return await _build_room_detail(
+ session, room, room_store, bridge_store, external_user_store, protocol
+ )
+
+
@router.post("/{room_id}/archive")
async def archive_room(
room_id: str,
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index d647f1ce0..e83e8088c 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -113,6 +113,10 @@ class RoomDetail(RoomSummary):
# What deleting the room will do to its platform channel ("archived",
# "deleted", "left", "kept"), or null when the room has no channel.
channel_on_delete: ChannelRetirement | None = None
+ # The linked platform channel's name as the bridge last saw it, or null
+ # when it has not seen one. A room not named after its channel can take
+ # it with `POST /rooms/{id}/sync-name`.
+ linked_channel_name: str | None = None
class RoomCreateRequest(BaseModel):
diff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.py
index 6ba2b9794..18cb3ef61 100644
--- a/core/switch_core/room_service.py
+++ b/core/switch_core/room_service.py
@@ -36,7 +36,11 @@ from switch_core.db.session_scope import tenant_session
from switch_core.db.stores.agent_store import AgentStore
from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
from switch_core.db.stores.room_role_store import validate_role_name
-from switch_core.db.stores.room_store import RoomStore
+from switch_core.db.stores.room_store import (
+ LINKED_CHANNEL_NAME_KEY,
+ NAME_SOURCE_KEY,
+ RoomStore,
+)
from switch_core.db.tenant_lookup import all_tenant_ids
from switch_core.provisioning import Provisioning
from switch_core.telemetry import TelemetryService, emit_safely
@@ -143,6 +147,9 @@ class RoomCreateConfig(BaseModel):
# `{agent_id, body}`: what that agent says as it joins, in place of its
# usual line. Stamped with the room, so it is there before the agent is.
agent_greeting: dict[str, str] | None = None
+ # The linked channel's name when the room is named after it (a bridge's
+ # own room), so it follows the channel's renames (`NAME_SOURCE_KEY`).
+ named_after_channel: str | None = None
class RoomCreateResult(BaseModel):
@@ -659,6 +666,14 @@ class RoomService:
if config.agent_greeting is not None
else {}
),
+ **(
+ {
+ NAME_SOURCE_KEY: "channel",
+ LINKED_CHANNEL_NAME_KEY: config.named_after_channel,
+ }
+ if config.named_after_channel is not None
+ else {}
+ ),
},
)
@@ -1168,6 +1183,28 @@ class RoomService:
await session.commit()
self._room_changed(tenant_id, room_id)
+ async def take_platform_name(
+ self, room_id: str, name: str, channel_name: str
+ ) -> None:
+ """Name a bridged room after its channel, so it follows the channel's
+ renames from now on, and tell whoever sees it."""
+ tenant_id = await self._room_tenant(room_id)
+ async with tenant_session(self._session_factory, tenant_id) as session:
+ await self._room_store.set_platform_name(
+ session, room_id, name, channel_name
+ )
+ await session.commit()
+ self._room_changed(tenant_id, room_id)
+
+ async def record_channel_name(self, room_id: str, channel_name: str) -> None:
+ """Keep the linked channel's current name on a room that does not
+ follow it, so whoever sees the room can be offered it."""
+ tenant_id = await self._room_tenant(room_id)
+ async with tenant_session(self._session_factory, tenant_id) as session:
+ await self._room_store.record_channel_name(session, room_id, channel_name)
+ await session.commit()
+ self._room_changed(tenant_id, room_id)
+
async def set_join_event_listeners(
self, room_id: str, settings: dict[str, bool]
) -> None:
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
index 2bf38bbaf..b6d297803 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_rename.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_rename.py
@@ -1,13 +1,18 @@
-"""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."""
+"""A bridged room named after its channel follows the channel's name, while a
+room someone named, or one whose origin is unknown, keeps its title and is
+told the channel's name; another channel's rename touches nothing."""
from __future__ import annotations
from types import SimpleNamespace
from typing import Any
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
from switch_core.bridges.collaboration.collaboration_core import CollaborationCore
from switch_core.bridges.collaboration.discord.adapter import DiscordAdapter
+from switch_core.db.models import Room
+from switch_core.db.stores.room_store import NAME_SOURCE_KEY, RoomStore
from switch_core.tenant_context import current_tenant_id
@@ -32,10 +37,24 @@ class _RoomStore:
class _RoomService:
def __init__(self) -> None:
- self.renamed: list[tuple[str, str, str | None]] = []
+ self.renamed: list[tuple[str, str, str, str | None]] = []
+ self.recorded: list[tuple[str, str]] = []
+
+ async def take_platform_name(
+ self, room_id: str, name: str, channel_name: str
+ ) -> None:
+ self.renamed.append((room_id, name, channel_name, current_tenant_id()))
- async def update_room(self, room_id: str, *, name: str) -> None:
- self.renamed.append((room_id, name, current_tenant_id()))
+ async def record_channel_name(self, room_id: str, channel_name: str) -> None:
+ self.recorded.append((room_id, channel_name))
+
+
+def _room(room_id: str, name: str, source: str | None) -> SimpleNamespace:
+ return SimpleNamespace(
+ id=room_id,
+ name=name,
+ metadata_={NAME_SOURCE_KEY: source} if source is not None else {},
+ )
def _bridge(rooms: dict[str, SimpleNamespace]) -> SimpleNamespace:
@@ -51,37 +70,78 @@ def _bridge(rooms: dict[str, SimpleNamespace]) -> SimpleNamespace:
)
-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 _named(bridge: SimpleNamespace, channel_id: str, old: str, new: str) -> None:
+ await CollaborationCore._handle_channel_named(bridge, channel_id, old, new) # type: ignore[arg-type]
-async def test_the_linked_room_takes_the_channels_new_name() -> None:
+async def test_a_room_named_after_its_channel_follows_it() -> None:
bridge = _bridge(
{
- "c-1": SimpleNamespace(id="room-1", name="Discord: qa-overnight-adopted"),
- "c-2": SimpleNamespace(id="room-2", name="Discord: other"),
+ "c-1": _room("room-1", "Discord: qa-overnight-adopted", "channel"),
+ "c-2": _room("room-2", "Discord: launch", None),
}
)
- await _rename(bridge, "c-1", "qa-overnight-adopted", "qa-adopted-renamed")
- await _rename(bridge, "c-9", "unlinked", "still-unlinked")
+ # Named after the channel: follows even when its name was left stale.
+ await _named(bridge, "c-1", "qa-adopted-renamed", "qa-adopted-again")
+ # From before the source was kept: follows only an exact match.
+ await _named(bridge, "c-2", "launch", "launch-2026")
+ await _named(bridge, "c-9", "unlinked", "still-unlinked")
assert bridge._room_service.renamed == [
- ("room-1", "Discord: qa-adopted-renamed", "tenant-1")
+ ("room-1", "Discord: qa-adopted-again", "qa-adopted-again", "tenant-1"),
+ ("room-2", "Discord: launch-2026", "launch-2026", "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")
+async def test_a_named_or_ambiguous_room_keeps_its_title_and_learns_the_channel() -> (
+ None
+):
+ bridge = _bridge(
+ {
+ "c-1": _room("room-1", "Discord: launch room", "custom"),
+ # Pre-provenance and not an exact match: could be someone's title.
+ "c-2": _room("room-2", "Discord: qa-overnight-adopted", None),
+ }
+ )
+ await _named(bridge, "c-1", "launch", "launch-2026")
+ await _named(bridge, "c-2", "qa-adopted-renamed", "qa-adopted-again")
assert bridge._room_service.renamed == []
+ assert bridge._room_service.recorded == [
+ ("room-1", "launch-2026"),
+ ("room-2", "qa-adopted-again"),
+ ]
-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)
+async def test_naming_a_room_marks_it_custom_and_a_platform_name_channel(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ store = RoomStore()
+ async with session_factory() as session:
+ room = await store.create(
+ session,
+ Room(
+ transport_room_id="!r:test",
+ name="Discord: general",
+ description="",
+ metadata_={"created_by_kind": "system"},
+ ),
+ )
+ await store.update_fields(session, room.id, name="Discord: our room")
+ assert room.metadata_[NAME_SOURCE_KEY] == "custom"
+ await store.set_platform_name(
+ session, room.id, "Discord: general-2", "general-2"
+ )
+ assert room.metadata_[NAME_SOURCE_KEY] == "channel"
+ assert room.metadata_["linked_channel_name"] == "general-2"
+ assert room.metadata_["created_by_kind"] == "system"
+
+
+async def test_the_adapter_reports_only_its_own_guilds_channels() -> None:
+ reported: list[tuple[str, str]] = []
+
+ async def named(channel_id: str, old: str, new: str) -> None:
+ reported.append((channel_id, new))
+
+ adapter = SimpleNamespace(_guild_id=1, _on_channel_named=named)
def channel(guild_id: int, name: str) -> SimpleNamespace:
return SimpleNamespace(id=42, name=name, guild=SimpleNamespace(id=guild_id))
@@ -89,7 +149,6 @@ async def test_the_adapter_reports_only_a_rename_in_its_own_guild() -> None:
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")]
+ assert reported == [("42", "new")]
diff --git a/core/tests/switch_core/gateway/test_room_sync_name.py b/core/tests/switch_core/gateway/test_room_sync_name.py
new file mode 100644
index 000000000..86a13d000
--- /dev/null
+++ b/core/tests/switch_core/gateway/test_room_sync_name.py
@@ -0,0 +1,89 @@
+"""`POST /gateway/rooms/{id}/sync-name` names a bridged room after its linked
+channel, so it follows the channel from then on; only the room's owner or an
+admin may. The route is called directly, as in `test_room_participant_read`."""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+from fastapi import HTTPException
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from switch_core.db.models import Client, CollaborationBridge, Room, User
+from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
+from switch_core.db.stores.room_store import NAME_SOURCE_KEY, RoomStore
+from switch_core.gateway import rooms as rooms_module
+from tests.switch_core.gateway.conftest import _Harness
+
+
+async def _sync(chats: _Harness, room_id: str, user: User) -> str:
+ async with chats.factory() as session:
+ return await rooms_module.sync_room_name( # type: ignore[return-value]
+ room_id,
+ session,
+ chats.room_service,
+ RoomStore(),
+ CollaborationBridgeStore(),
+ None, # type: ignore[arg-type]
+ None, # type: ignore[arg-type]
+ user,
+ False,
+ )
+
+
+async def test_the_owner_takes_the_channel_name_and_others_may_not(
+ chats: _Harness, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async def detail(_session: AsyncSession, room: Room, *_args: Any) -> str:
+ return room.name
+
+ monkeypatch.setattr(rooms_module, "_build_room_detail", detail)
+ async with chats.factory() as session:
+ bridge_client = Client(
+ transport_user_id="@bridge:test", display_name="bridge", type="bridge"
+ )
+ session.add(bridge_client)
+ await session.flush()
+ bridge = CollaborationBridge(
+ type="discord",
+ display_name="Discord",
+ client_id=bridge_client.id,
+ status="active",
+ )
+ session.add(bridge)
+ await session.flush()
+ linked = Room(
+ transport_room_id="!linked:test",
+ name="Discord: qa-overnight-adopted",
+ description="",
+ owner_id=chats.alice.id,
+ bridge_id=bridge.id,
+ external_channel_id="C-1",
+ read_visibility="public",
+ write_visibility="public",
+ metadata_={"linked_channel_name": "qa-adopted-renamed"},
+ )
+ unseen = Room(
+ transport_room_id="!unseen:test",
+ name="Discord: quiet",
+ description="",
+ owner_id=chats.alice.id,
+ bridge_id=bridge.id,
+ external_channel_id="C-2",
+ )
+ session.add_all([linked, unseen])
+ await session.commit()
+
+ with pytest.raises(HTTPException) as refused:
+ await _sync(chats, linked.id, chats.bob)
+ assert refused.value.status_code == 403
+ with pytest.raises(HTTPException) as unknown:
+ await _sync(chats, unseen.id, chats.alice)
+ assert unknown.value.status_code == 409
+
+ assert await _sync(chats, linked.id, chats.alice) == "Discord: qa-adopted-renamed"
+ async with chats.factory() as session:
+ row = await session.get(Room, linked.id)
+ assert row is not None
+ assert row.metadata_[NAME_SOURCE_KEY] == "channel"