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 renamed room reaches everyone in it, and names are checked

raullopez-sandboxe2bae4bebe2a
diff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.py
index 918681317..e996e2831 100644
--- a/core/switch_core/chats/service.py
+++ b/core/switch_core/chats/service.py
@@ -203,6 +203,7 @@ class ChatService:
self._agent_room_listeners: tuple[
Callable[[str, str, list[str]], None], ...
] = ()
+ self._tasks: set[asyncio.Task[None]] = set()
# Where a change to people's chats made here is announced to the
# other processes, once wired (`use_signals`).
self._signals: ChatSignals | None = None
@@ -571,6 +572,38 @@ class ChatService:
whoever shows the room reads it again. It must not block."""
self._agent_room_listeners = (*self._agent_room_listeners, listener)
+ def room_changed(self, tenant_id: str, room_id: str, client_ids: list[str]) -> None:
+ """A room's own details changed (its name, say): wake the streams of
+ the people in it, from a task of its own, so they re-send its summary."""
+ task = asyncio.create_task(self._room_details_changed(tenant_id, room_id))
+ self._tasks.add(task)
+ task.add_done_callback(self._task_done)
+
+ def _task_done(self, task: asyncio.Task[None]) -> None:
+ self._tasks.discard(task)
+ if not task.cancelled() and task.exception() is not None:
+ logger.error(
+ "Could not wake the streams of a changed room's people; they "
+ "re-read it on their next recheck",
+ exc_info=task.exception(),
+ )
+
+ async def _room_details_changed(self, tenant_id: str, room_id: str) -> None:
+ async with tenant_session(self.session_factory, tenant_id) as session:
+ user_ids = (
+ await session.execute(
+ select(Client.user_id)
+ .join(ClientRoom, ClientRoom.client_id == Client.id)
+ .where(
+ ClientRoom.room_id == room_id,
+ Client.type == MEMBER_CLIENT_TYPE,
+ Client.user_id.is_not(None),
+ )
+ )
+ ).scalars()
+ members = sorted(user_id for user_id in user_ids if user_id is not None)
+ self._memberships_changed(tenant_id, members, [room_id])
+
async def agent_changed(self, tenant_id: str, agent_id: str) -> None:
"""Tell everyone who sees a room with this agent that it changed, and
with `agent_chats` on, wake the streams of everyone in a chat with it
diff --git a/core/switch_core/gateway/rooms.py b/core/switch_core/gateway/rooms.py
index c2684c55a..8965ead77 100644
--- a/core/switch_core/gateway/rooms.py
+++ b/core/switch_core/gateway/rooms.py
@@ -933,6 +933,9 @@ async def patch_room(
room = await room_store.get(session, room_id)
if room is None:
raise HTTPException(status_code=404, detail="Room not found")
+ # The update was written on another session; this one still holds the row
+ # as it was read for the access check.
+ await session.refresh(room)
return await _build_room_detail(
session, room, room_store, bridge_store, external_user_store, protocol
)
diff --git a/core/switch_core/main.py b/core/switch_core/main.py
index c446abfe8..b1c0795f3 100644
--- a/core/switch_core/main.py
+++ b/core/switch_core/main.py
@@ -1174,6 +1174,7 @@ async def run(config: SwitchConfig, process_id: str) -> None:
protocol.set_room_agents_listener(room_service.room_agents_changed)
protocol.set_agent_profile_listener(chat_service.agent_changed)
chat_service.on_agent_room_changed(room_changes.room_changed)
+ room_service.on_room_changed(chat_service.room_changed)
# ── Connector app credentials ─────────────────────────────────────────────
# Each connector's app, from configuration or a row the operator saved,
diff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.py
index a6a595371..6ba2b9794 100644
--- a/core/switch_core/room_service.py
+++ b/core/switch_core/room_service.py
@@ -158,6 +158,9 @@ class RoomCreateResult(BaseModel):
failed_attachments: list[dict[str, Any]] = []
+ROOM_NAME_MAX = 200
+
+
class RoomService:
# Class-level defaults so a caller that builds this without `__init__` —
# several tests assemble a minimal instance directly — still has the
@@ -1132,6 +1135,12 @@ class RoomService:
read_visibility: str | None = None,
write_visibility: str | None = None,
) -> None:
+ if name is not None:
+ name = name.strip()
+ if not name or len(name) > ROOM_NAME_MAX:
+ raise ValueError(
+ f"A room's name must be 1 to {ROOM_NAME_MAX} characters."
+ )
tenant_id = await self._room_tenant(room_id)
async with tenant_session(self._session_factory, tenant_id) as session:
if read_visibility is not None or write_visibility is not None:
@@ -1157,6 +1166,7 @@ class RoomService:
write_visibility=write_visibility,
)
await session.commit()
+ self._room_changed(tenant_id, room_id)
async def set_join_event_listeners(
self, room_id: str, settings: dict[str, bool]
diff --git a/core/tests/switch_core/gateway/test_chats_groups.py b/core/tests/switch_core/gateway/test_chats_groups.py
index 962110ad4..de5331cee 100644
--- a/core/tests/switch_core/gateway/test_chats_groups.py
+++ b/core/tests/switch_core/gateway/test_chats_groups.py
@@ -10,6 +10,7 @@ from typing import Any
import httpx
import pytest
+from fastapi import HTTPException
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -19,7 +20,10 @@ from switch_core.bridges.agent.registration_bootstrap import (
)
from switch_core.chats.service import ChatError, ChatService
from switch_core.db.models import Agent, Client, Message, Room, User, room_agents
+from switch_core.db.stores.room_store import RoomStore
from switch_core.gateway import chats as chats_module
+from switch_core.gateway import rooms as rooms_module
+from switch_core.gateway.schemas import RoomUpdateRequest
from switch_core.room_changes import RoomChanges
from switch_core.user_changes import ROOM
from tests.switch_core.gateway.conftest import (
@@ -1314,3 +1318,53 @@ async def test_renaming_an_agent_tells_everyone_who_sees_its_rooms(
assert (name, summary["roomId"]) == ("chat", room_id)
assert summary["agents"][0]["displayName"] == "QA Blair"
await events.stream.aclose() # type: ignore[attr-defined]
+
+
+async def test_only_a_manager_renames_a_group_and_everyone_sees_it(
+ 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)
+ chats.room_service.on_room_changed(chats.service.room_changed)
+ created = await chats.client.post(
+ "/chats",
+ json={"agentIds": [], "memberUserIds": [chats.bob.id], "requestId": "c1"},
+ headers=chats.as_user(chats.alice),
+ )
+ room_id = created.json()["chat"]["roomId"]
+ events = _stream(chats, chats.bob, {}, recheck=60.0)
+ assert await events.until("ready") == {}
+
+ async def rename(user: User, name: str) -> Any:
+ async with chats.factory() as session:
+ return await rooms_module.patch_room(
+ room_id,
+ RoomUpdateRequest(name=name),
+ session,
+ chats.room_service,
+ RoomStore(),
+ None, # type: ignore[arg-type]
+ None, # type: ignore[arg-type]
+ None, # type: ignore[arg-type]
+ user,
+ False,
+ )
+
+ with pytest.raises(HTTPException) as refused:
+ await rename(chats.bob, "Bob's name")
+ assert refused.value.status_code == 403
+ for bad in (" ", "x" * 201):
+ with pytest.raises(HTTPException) as invalid:
+ await rename(chats.alice, bad)
+ assert invalid.value.status_code == 400
+
+ assert await rename(chats.alice, " Launch crew ") == "Launch crew"
+ name, summary = await events.next()
+ assert (name, summary["roomId"], summary["name"]) == (
+ "chat",
+ room_id,
+ "Launch crew",
+ )
+ await events.stream.aclose() # type: ignore[attr-defined]