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): list the rooms a person takes part in

raullopez-sandbox581920a2a8b6
diff --git a/core/switch_core/db/stores/room_store.py b/core/switch_core/db/stores/room_store.py
index 16c1a288d..5796413dc 100644
--- a/core/switch_core/db/stores/room_store.py
+++ b/core/switch_core/db/stores/room_store.py
@@ -2,15 +2,18 @@ from collections.abc import Collection
from dataclasses import dataclass
from datetime import UTC, datetime
-from sqlalchemy import delete, insert, or_, select, update
+from sqlalchemy import ColumnElement, delete, exists, insert, or_, select, update
from sqlalchemy import func as sa_func
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.ext.asyncio import AsyncSession
+from switch_core.chats import MEMBER_CLIENT_TYPE
from switch_core.db.models import (
Agent,
Client,
ClientRoom,
+ ExternalUser,
+ ExternalUserClaim,
Room,
RoomGroup,
require_tenant_id,
@@ -234,18 +237,28 @@ class RoomStore:
is_admin: bool,
include_archived: bool = False,
) -> list[Room]:
- """Return rooms the user may read: owned, publicly readable, or all
- if admin. Archived rooms are excluded unless `include_archived`."""
+ """Return rooms the user may read: publicly readable, ones they take
+ part in (`involves`), or all if admin. Archived rooms are excluded
+ unless `include_archived`."""
stmt = select(Room)
if not is_admin:
- stmt = stmt.where(
- or_(Room.owner_id == user_id, Room.read_visibility == "public")
- )
+ stmt = stmt.where(or_(Room.read_visibility == "public", involves(user_id)))
if not include_archived:
stmt = stmt.where(Room.archived_at.is_(None))
result = await session.execute(stmt)
return list(result.scalars().all())
+ async def involved_room_ids(
+ self, session: AsyncSession, user_id: str, room_ids: Collection[str]
+ ) -> set[str]:
+ """Of `room_ids`, the rooms `involves(user_id)` holds for."""
+ if not room_ids:
+ return set()
+ result = await session.execute(
+ select(Room.id).where(Room.id.in_(room_ids), involves(user_id))
+ )
+ return set(result.scalars().all())
+
async def delete(self, session: AsyncSession, room_id: str) -> None:
await session.execute(delete(ClientRoom).where(ClientRoom.room_id == room_id))
room = await session.get(Room, room_id)
@@ -761,3 +774,30 @@ class RoomStore:
)
await session.flush()
return result.rowcount or 0 # type: ignore[attr-defined]
+
+
+def involves(user_id: str) -> ColumnElement[bool]:
+ """True for a `Room` row the user takes part in: they own it, their Switch
+ Console member client or a platform account they have claimed is in it,
+ or an agent they own is. For reading and listing only; it grants no
+ write or configuration access."""
+ return or_(
+ Room.owner_id == user_id,
+ exists().where(
+ ClientRoom.room_id == Room.id,
+ ClientRoom.client_id == Client.id,
+ Client.user_id == user_id,
+ Client.type == MEMBER_CLIENT_TYPE,
+ ),
+ exists().where(
+ ClientRoom.room_id == Room.id,
+ ClientRoom.client_id == ExternalUser.client_id,
+ ExternalUser.id == ExternalUserClaim.external_user_id,
+ ExternalUserClaim.user_id == user_id,
+ ),
+ exists().where(
+ room_agents.c.room_id == Room.id,
+ room_agents.c.agent_id == Agent.id,
+ Agent.owner_id == user_id,
+ ),
+ )
diff --git a/core/switch_core/gateway/rooms.py b/core/switch_core/gateway/rooms.py
index c604df9a0..ee7a69e81 100644
--- a/core/switch_core/gateway/rooms.py
+++ b/core/switch_core/gateway/rooms.py
@@ -112,7 +112,11 @@ async def _require_room(
room,
)
except PermissionError as e:
- raise HTTPException(status_code=403, detail=str(e)) from e
+ # Whoever takes part in a room may read it, as its listing shows them.
+ if action != "read" or not await room_store.involved_room_ids(
+ session, user.id, [room.id]
+ ):
+ raise HTTPException(status_code=403, detail=str(e)) from e
return room
@@ -348,6 +352,7 @@ async def list_rooms(
room_ids = [room.id for room in rooms]
agent_ids_by_room = await room_store.agent_ids_by_room(session, room_ids)
client_ids_by_room = await room_store.client_ids_by_room(session, room_ids)
+ involved = await room_store.involved_room_ids(session, user.id, room_ids)
# Not held across the deeplinks, which can ask the platform on a cache miss.
await session.commit()
@@ -385,6 +390,7 @@ async def list_rooms(
write_visibility=room.write_visibility,
created_at=str(room.created_at),
archived=room.archived_at is not None,
+ viewer_is_member=room.id in involved,
)
)
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index 4975d134c..e94eb0a7e 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -85,6 +85,9 @@ class RoomSummary(BaseModel):
created_at: str
# True when the room is archived (hidden from the default active list).
archived: bool = False
+ # The caller owns the room, is in it (in Switch Console or through a
+ # platform account they claimed), or owns an agent in it.
+ viewer_is_member: bool = False
class RoomDetail(RoomSummary):
diff --git a/core/tests/switch_core/db/stores/test_room_store_involves.py b/core/tests/switch_core/db/stores/test_room_store_involves.py
new file mode 100644
index 000000000..d778927e4
--- /dev/null
+++ b/core/tests/switch_core/db/stores/test_room_store_involves.py
@@ -0,0 +1,104 @@
+"""Rooms a person takes part in are readable to them: through their Switch
+Console member client, a platform account they claimed, or an agent they own
+— and no other private room. Real Postgres."""
+
+from __future__ import annotations
+
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.chats import MEMBER_CLIENT_TYPE
+from switch_core.db.models import (
+ Client,
+ ClientRoom,
+ CollaborationBridge,
+ ExternalUser,
+ ExternalUserClaim,
+ Room,
+ User,
+ room_agents,
+)
+from switch_core.db.stores.room_store import RoomStore
+from tests.switch_core.gateway.agent_route_harness import add_agent
+
+
+async def _room(session: AsyncSession, name: str, owner_id: str | None) -> Room:
+ room = Room(
+ transport_room_id=f"!{name}:test",
+ name=name,
+ description="",
+ owner_id=owner_id,
+ read_visibility="private",
+ write_visibility="private",
+ )
+ session.add(room)
+ await session.flush()
+ return room
+
+
+async def _client(
+ session: AsyncSession, name: str, kind: str, user_id: str | None
+) -> Client:
+ client = Client(
+ transport_user_id=f"@{name}:test", display_name=name, type=kind, user_id=user_id
+ )
+ session.add(client)
+ await session.flush()
+ return client
+
+
+async def test_a_person_reads_the_rooms_they_take_part_in_and_no_other(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ store = RoomStore()
+ async with session_factory() as session:
+ alice = User(name="alice", email="[email protected]", role="user")
+ bob = User(name="bob", email="[email protected]", role="user")
+ session.add_all([alice, bob])
+ await session.flush()
+
+ owned = await _room(session, "owned", alice.id)
+ console = await _room(session, "console", bob.id)
+ discord = await _room(session, "discord", None)
+ with_agent = await _room(session, "with-agent", bob.id)
+ unrelated = await _room(session, "unrelated", bob.id)
+
+ member = await _client(session, "alice-member", MEMBER_CLIENT_TYPE, alice.id)
+ session.add(ClientRoom(client_id=member.id, room_id=console.id))
+
+ bridge_client = await _client(session, "bridge", "bridge", None)
+ bridge = CollaborationBridge(
+ type="discord",
+ display_name="Discord",
+ client_id=bridge_client.id,
+ status="active",
+ )
+ session.add(bridge)
+ await session.flush()
+ platform = await _client(session, "alice-discord", "user", None)
+ account = ExternalUser(
+ bridge_id=bridge.id,
+ external_user_id="d-1",
+ external_username="alice#1",
+ client_id=platform.id,
+ )
+ session.add(account)
+ await session.flush()
+ session.add(ExternalUserClaim(external_user_id=account.id, user_id=alice.id))
+ session.add(ClientRoom(client_id=platform.id, room_id=discord.id))
+
+ agent = await add_agent(session, name="alices-agent", owner_id=alice.id)
+ await session.execute(
+ room_agents.insert().values(room_id=with_agent.id, agent_id=agent.id)
+ )
+ # Bob's own member client in the unrelated room does not reach Alice.
+ bob_member = await _client(session, "bob-member", MEMBER_CLIENT_TYPE, bob.id)
+ session.add(ClientRoom(client_id=bob_member.id, room_id=unrelated.id))
+ await session.commit()
+
+ readable = await store.list_readable(session, alice.id, is_admin=False)
+ expected = {owned.id, console.id, discord.id, with_agent.id}
+ assert {room.id for room in readable} == expected
+ assert (
+ await store.involved_room_ids(session, alice.id, [*expected, unrelated.id])
+ == expected
+ )