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
Only a workspace admin manages room groups; hide private rooms in group counts
Petr Bauch5fba4422d670
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex de9b8348e..157a6474e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -95,6 +95,13 @@ version of their own to them without also giving them a release of their own.(an agent also sees the rooms it is in). Linking a room to another nowneeds read access to the target, whose name the link shows. An agent canlist a room's participants only from inside the room.+- **Only a workspace admin manages room groups.** Groups are shared by the+ whole workspace and have no owner, so any member could rename, move or+ delete one. Creating, changing and deleting a group, from the dashboard,+ the API or an agent's `create_room_group`, now needs a workspace admin (for+ an agent, its owner). Anyone can still file a room they can write into an+ existing group. Group room counts, and the rooms `get_room_group_detail`+ lists, now leave out private rooms the caller cannot read.#### Added- **An agent controller can send its agents' operations on its socket.**diff --git a/console/packages/plugins/src/switch-skill/SKILL.md b/console/packages/plugins/src/switch-skill/SKILL.mdindex ef0536d7c..8063c450b 100644--- a/console/packages/plugins/src/switch-skill/SKILL.md+++ b/console/packages/plugins/src/switch-skill/SKILL.md@@ -710,14 +710,18 @@ Room groups are a navigation layer: a room belongs to at most one group, andgroups nest under a parent to form a tree.- **`list_room_groups`** — every group with its room count and root-first- `path`.+ `path`. Its counts, and `get_room_group_detail`'s rooms, include only+ rooms you may see.- **`get_room_group_detail`** — one group, the rooms directly in it(`member_rooms`), and its immediate `child_groups`.-- **`create_room_group`** — provision a group. Required: `name`. Optional:- `description`, `color`, `parent_group_name` (omit it for a top-level- group). Creating a group does not move any rooms into it; file rooms under- it later by passing `group_name` to `create_room`. Missing parents are not- created for you: create each level first.+- **`create_room_group`** — provision a group. Only an agent whose owner is a+ workspace admin may: groups are shared by the whole workspace. Anyone else+ is refused, so file the room under an existing group or ask an admin.+ Required: `name`. Optional: `description`, `color`, `parent_group_name`+ (omit it for a top-level group). Creating a group does not move any rooms+ into it; file rooms under it later by passing `group_name` to+ `create_room`. Missing parents are not created for you: create each level+ first.Name a group by its **path**: the top-level group, then each child, separatedby `/`, e.g. `Fraud/Incidents`. The `path` that `list_room_groups` returns@@ -1106,7 +1110,7 @@ Every Switch tool you call in normal operation, one line each.- `unarchive_room` — reverse an archive.- `list_room_groups` — the group tree rooms are organised into.- `get_room_group_detail` — one group's rooms and child groups.-- `create_room_group` — provision a new room group.+- `create_room_group` — provision a new room group (workspace admin agents only).- `create_room_from_yaml` — provision a room or group from a YAML template.- `get_template_guide`: how to write a template, and the schema it is checked against.- `list_templates`: the saved templates you can use.diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.pyindex 9ad6f91a6..488bf592d 100644--- a/core/switch_core/bridges/agent/operations/definitions.py+++ b/core/switch_core/bridges/agent/operations/definitions.py@@ -1550,7 +1550,9 @@ async def create_room_group(A room group is a named bucket that rooms can be filed under (via`create_room`'s `group_name`), and groups can nest under a parent group toform a tree. Creating a group does not move any rooms into it, and does- not create missing parents: create each level first.+ not create missing parents: create each level first. Groups are shared by+ the whole workspace, so only an agent whose owner is a workspace admin+ may create one; anyone else gets a permission error.Args:name: The group's display name. It cannot contain "/" (the pathdiff --git a/core/switch_core/bridges/agent/protocol/agent_core.py b/core/switch_core/bridges/agent/protocol/agent_core.pyindex 2dcd9bea3..f972b8a3c 100644--- a/core/switch_core/bridges/agent/protocol/agent_core.py+++ b/core/switch_core/bridges/agent/protocol/agent_core.py@@ -7,12 +7,13 @@ import loggingimport reimport secretsimport uuid+from collections import Counterfrom collections.abc import Awaitable, Callable, Sequencefrom dataclasses import dataclassfrom datetime import UTC, datetimefrom typing import TYPE_CHECKING, Any-from sqlalchemy import func, select+from sqlalchemy import selectfrom switch_core.addressing import (AddressingPolicy,@@ -3772,22 +3773,36 @@ class AgentCore:last = rooms[-1]return rooms, _encode_room_cursor(last.created_at, last.id)+ async def _rooms_visible_to(+ self, session: AsyncSession, agent_id: str, *, include_archived: bool+ ) -> list[Room]:+ """The rooms the agent's owner may read, plus those the agent is in."""+ _agent, owner_id, owner_is_admin = await self._resolve_acting_identity(+ session, agent_id+ )+ return await self.room_store.list_visible_to_agent(+ session,+ reader_id=owner_id,+ reader_is_admin=owner_is_admin,+ member_agent_id=agent_id,+ include_archived=include_archived,+ )+async def list_room_groups(self, agent_id: str) -> list[dict[str, Any]]:"""List every room group on the instance, with room counts and paths.Returns dicts of ``{id, name, description, parent_group_id, room_count,path}`` where `path` is the root-first ancestry (e.g. "Parent / Child")- and `room_count` is the number of rooms directly in that group.+ and `room_count` is the number of rooms directly in that group that+ the agent may see."""async with self.session_factory() as session:result = await session.execute(select(RoomGroup))groups = list(result.scalars().all())- count_rows = await session.execute(- select(Room.group_id, func.count(Room.id))- .where(Room.group_id.is_not(None))- .group_by(Room.group_id)+ visible = await self._rooms_visible_to(+ session, agent_id, include_archived=True)- counts = {gid: c for gid, c in count_rows.all() if gid is not None}+ counts = Counter(r.group_id for r in visible if r.group_id is not None)by_id = {g.id: g for g in groups}@@ -3846,9 +3861,18 @@ class AgentCore:(a path, bare name or id). Returns the new group's detail dict.Raises ValueError if `parent_group_name` is unknown or ambiguous, or if- the parent already has a group with this name.+ the parent already has a group with this name, and PermissionError+ unless the agent's owner administers the workspace: groups are shared+ and have no owner of their own."""async with self.session_factory() as session:+ _agent, _owner_id, owner_is_admin = await self._resolve_acting_identity(+ session, agent_id+ )+ if not owner_is_admin:+ raise PermissionError(+ "Only a workspace admin's agent can create room groups."+ )parent_group_id = await self._resolve_group_name(session, parent_group_name)group = await self.room_group_store.create(session,@@ -3875,7 +3899,7 @@ class AgentCore:self, agent_id: str, group_id: str) -> dict[str, Any]:"""Return one room group's detail: its fields, ancestry path, the rooms- directly in it, and its immediate child groups.+ directly in it that the agent may see, and its immediate child groups.Raises ValueError if the group does not exist."""@@ -3884,11 +3908,12 @@ class AgentCore:if group is None:raise ValueError(f"Room group not found: {group_id}")- member_room_rows = await session.execute(- select(Room.id, Room.name).where(Room.group_id == group_id)- )member_rooms = [- {"id": rid, "name": rname} for rid, rname in member_room_rows.all()+ {"id": r.id, "name": r.name}+ for r in await self._rooms_visible_to(+ session, agent_id, include_archived=True+ )+ if r.group_id == group_id]child_rows = await session.execute(diff --git a/core/switch_core/db/stores/room_store.py b/core/switch_core/db/stores/room_store.pyindex 2854df78a..4561ea01a 100644--- a/core/switch_core/db/stores/room_store.py+++ b/core/switch_core/db/stores/room_store.py@@ -279,16 +279,7 @@ class RoomStore:rooms and its own."""stmt = select(Room)if not reader_is_admin:- visible = [- Room.read_visibility == "public",- exists().where(- room_agents.c.room_id == Room.id,- room_agents.c.agent_id == member_agent_id,- ),- ]- if reader_id is not None:- visible.append(involves(reader_id))- stmt = stmt.where(or_(*visible))+ stmt = stmt.where(_visible_to_agent(reader_id, member_agent_id))if not include_archived:stmt = stmt.where(Room.archived_at.is_(None))if name_contains:@@ -301,6 +292,23 @@ class RoomStore:stmt = stmt.order_by(Room.created_at, Room.id).limit(limit)return list((await session.execute(stmt)).scalars().all())+ async def list_visible_to_agent(+ self,+ session: AsyncSession,+ *,+ reader_id: str | None,+ reader_is_admin: bool,+ member_agent_id: str,+ include_archived: bool,+ ) -> list[Room]:+ """Every room an agent may see, as `page_all` filters them, unpaged."""+ stmt = select(Room)+ if not reader_is_admin:+ stmt = stmt.where(_visible_to_agent(reader_id, member_agent_id))+ if not include_archived:+ stmt = stmt.where(Room.archived_at.is_(None))+ return list((await session.execute(stmt)).scalars().all())+async def list_readable(self,session: AsyncSession,@@ -941,6 +949,22 @@ class RoomStore:return result.rowcount or 0 # type: ignore[attr-defined]+def _visible_to_agent(reader_id: str | None, agent_id: str) -> ColumnElement[bool]:+ """True for a `Room` row an agent may see when its owner is not a+ workspace admin: public, one the owner takes part in, or one the agent is+ in. An agent with no owner sees public rooms and its own."""+ visible = [+ Room.read_visibility == "public",+ exists().where(+ room_agents.c.room_id == Room.id,+ room_agents.c.agent_id == agent_id,+ ),+ ]+ if reader_id is not None:+ visible.append(involves(reader_id))+ return or_(*visible)++def involves(user_id: str) -> ColumnElement[bool]:"""True for a `Room` row the user takes part in: they own it, their SwitchConsole member client or a platform account they have claimed is in it,diff --git a/core/switch_core/gateway/room_groups.py b/core/switch_core/gateway/room_groups.pyindex e7cb8d405..c67c220f8 100644--- a/core/switch_core/gateway/room_groups.py+++ b/core/switch_core/gateway/room_groups.py@@ -1,5 +1,6 @@from __future__ import annotations+from collections import Counterfrom typing import Annotatedfrom fastapi import APIRouter, Depends, HTTPException, Response@@ -32,6 +33,26 @@ from switch_core.telemetry.ages import UNKNOWN_AGE, age_daysrouter = APIRouter()+def _require_group_admin(is_admin: bool) -> None:+ """Groups are shared by the whole workspace and have no owner, so only a+ workspace admin may create, change or delete one. Filing a room one can+ write into an existing group stays open to everyone."""+ if not is_admin:+ raise HTTPException(+ status_code=403, detail="Only a workspace admin can manage room groups."+ )+++async def _readable_room_counts(+ session: AsyncSession, room_store: RoomStore, user: User, is_admin: bool+) -> Counter[str]:+ """Rooms directly in each group, counting only rooms `user` may read."""+ rooms = await room_store.list_readable(+ session, user.id, is_admin=is_admin, include_archived=True+ )+ return Counter(r.group_id for r in rooms if r.group_id is not None)++def _to_detail(group: RoomGroup, room_count: int) -> RoomGroupDetail:return RoomGroupDetail(id=group.id,@@ -48,10 +69,12 @@ def _to_detail(group: RoomGroup, room_count: int) -> RoomGroupDetail:async def list_room_groups(session: Annotated[AsyncSession, Depends(get_session)],room_group_store: Annotated[RoomGroupStore, Depends(get_room_group_store)],- _user: Annotated[User, Depends(get_current_user)],+ room_store: Annotated[RoomStore, Depends(get_room_store)],+ user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> list[RoomGroupDetail]:groups = await room_group_store.get_all(session)- counts = await room_group_store.get_room_counts(session)+ counts = await _readable_room_counts(session, room_store, user, is_admin)return [_to_detail(g, counts.get(g.id, 0)) for g in groups]@@ -61,7 +84,9 @@ async def create_room_group(session: Annotated[AsyncSession, Depends(get_session)],room_group_store: Annotated[RoomGroupStore, Depends(get_room_group_store)],_user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomGroupDetail:+ _require_group_admin(is_admin)try:group = await room_group_store.create(session,@@ -89,8 +114,11 @@ async def patch_room_group(req: RoomGroupUpdateRequest,session: Annotated[AsyncSession, Depends(get_session)],room_group_store: Annotated[RoomGroupStore, Depends(get_room_group_store)],- _user: Annotated[User, Depends(get_current_user)],+ room_store: Annotated[RoomStore, Depends(get_room_store)],+ user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomGroupDetail:+ _require_group_admin(is_admin)# Only reparent when the client actually sent `parent_group_id` (so we can# tell "make top-level" (null) apart from "leave the parent alone" (absent)).reparent = "parent_group_id" in req.model_fields_set@@ -112,7 +140,7 @@ async def patch_room_group(raise HTTPException(status_code=404, detail=str(e)) from eraise HTTPException(status_code=400, detail=str(e)) from eawait session.commit()- counts = await room_group_store.get_room_counts(session)+ counts = await _readable_room_counts(session, room_store, user, is_admin)return _to_detail(group, counts.get(group.id, 0))@@ -162,7 +190,9 @@ async def delete_room_group(session: Annotated[AsyncSession, Depends(get_session)],room_group_store: Annotated[RoomGroupStore, Depends(get_room_group_store)],_user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> Response:+ _require_group_admin(is_admin)# Read before the delete: afterwards there is nothing left to say how much# was filed under it, which is the difference between tidying up an empty# group and dismantling a working one.diff --git a/core/tests/switch_core/bridges/agent/protocol/test_create_room_group.py b/core/tests/switch_core/bridges/agent/protocol/test_create_room_group.pyindex 116a0aa5b..b6954ccee 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_create_room_group.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_create_room_group.py@@ -1,5 +1,8 @@from __future__ import annotations+from types import SimpleNamespace+from typing import Any+import pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker@@ -9,6 +12,10 @@ from switch_core.db.stores.room_group_store import RoomGroupStorefrom switch_core.db.stores.room_store import RoomStore+async def _acting_as_admin(session: AsyncSession, agent_id: str) -> Any:+ return SimpleNamespace(id=agent_id, owner_id="owner"), "owner", True++def _bare_service() -> AgentCore:# These methods only touch the passed-in session / session_factory and the# group store, so we can exercise them on an un-__init__'d instance@@ -92,6 +99,8 @@ class TestListRoomGroups:) -> None:svc = _bare_service()svc.session_factory = session_factory # type: ignore[attr-defined]+ svc.room_store = RoomStore() # type: ignore[attr-defined]+ svc._resolve_acting_identity = _acting_as_admin # type: ignore[method-assign]store = RoomGroupStore()rooms = RoomStore()async with session_factory() as session:diff --git a/core/tests/switch_core/bridges/agent/protocol/test_room_group_mcp_tools.py b/core/tests/switch_core/bridges/agent/protocol/test_room_group_mcp_tools.pyindex f16304919..f6f9d3b32 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_room_group_mcp_tools.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_room_group_mcp_tools.py@@ -1,11 +1,14 @@from __future__ import annotations+from types import SimpleNamespace+from typing import Any+import pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistryfrom switch_core.bridges.agent.protocol.agent_core import AgentCore-from switch_core.db.models import Room+from switch_core.db.models import Room, Userfrom switch_core.db.stores.room_group_store import (RoomGroupNameTaken,RoomGroupStore,@@ -23,9 +26,22 @@ def _service(session_factory: async_sessionmaker[AsyncSession]) -> AgentCore:svc.connections = AgentConnectionRegistry()svc.session_factory = session_factory # type: ignore[attr-defined]svc.room_group_store = RoomGroupStore() # type: ignore[attr-defined]+ svc.room_store = RoomStore() # type: ignore[attr-defined]+ svc._resolve_acting_identity = _acting_as(owner_is_admin=True) # type: ignore[method-assign]return svc+def _acting_as(*, owner_is_admin: bool, owner_id: str = "owner") -> Any:+ """Stand in for the agent lookup: an agent owned by `owner_id`, whose+ workspace admin bit is `owner_is_admin`."""++ async def resolve(session: AsyncSession, agent_id: str) -> Any:+ agent = SimpleNamespace(id=agent_id, owner_id=owner_id)+ return agent, owner_id, owner_is_admin++ return resolve++class TestCreateRoomGroup:async def test_creates_top_level_group(self, session_factory: async_sessionmaker[AsyncSession]@@ -124,3 +140,64 @@ class TestGetRoomGroupDetail:svc = _service(session_factory)with pytest.raises(ValueError, match="Room group not found"):await svc.get_room_group_detail("agent-x", "does-not-exist")+++class TestRoomGroupsForNonAdmins:+ async def test_a_non_admins_agent_cannot_create_a_group(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ svc = _service(session_factory)+ svc._resolve_acting_identity = _acting_as(owner_is_admin=False) # type: ignore[method-assign]++ with pytest.raises(PermissionError):+ await svc.create_room_group("agent-x", "Eng", None, None, None)++ assert await svc.list_room_groups("agent-x") == []++ async def test_private_rooms_of_others_are_not_listed_or_counted(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ svc = _service(session_factory)+ group = await svc.create_room_group("agent-x", "Shared", None, None, None)+ rooms = RoomStore()+ async with session_factory() as session:+ mine = User(name="mine", email="[email protected]", role="user")+ theirs = User(name="theirs", email="[email protected]", role="user")+ session.add_all([mine, theirs])+ await session.flush()+ own_room = await rooms.create(+ session,+ Room(+ transport_room_id="!own:test",+ name="own",+ description="d",+ owner_id=mine.id,+ read_visibility="private",+ write_visibility="private",+ ),+ )+ hidden_room = await rooms.create(+ session,+ Room(+ transport_room_id="!hidden:test",+ name="hidden",+ description="d",+ owner_id=theirs.id,+ read_visibility="private",+ write_visibility="private",+ ),+ )+ for room in (own_room, hidden_room):+ await rooms.set_group(session, room.id, group["id"])+ await session.commit()+ own_id, mine_id = own_room.id, mine.id++ svc._resolve_acting_identity = _acting_as( # type: ignore[method-assign]+ owner_is_admin=False, owner_id=mine_id+ )++ detail = await svc.get_room_group_detail("agent-x", group["id"])+ assert detail["member_rooms"] == [{"id": own_id, "name": "own"}]+ assert detail["room_count"] == 1+ [listed] = await svc.list_room_groups("agent-x")+ assert listed["room_count"] == 1diff --git a/core/tests/switch_core/gateway/test_room_groups_authz.py b/core/tests/switch_core/gateway/test_room_groups_authz.pynew file mode 100644index 000000000..03de7edb3--- /dev/null+++ b/core/tests/switch_core/gateway/test_room_groups_authz.py@@ -0,0 +1,188 @@+"""Room groups are shared by the workspace: only an admin manages them."""++from __future__ import annotations++import pytest+from fastapi import HTTPException+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.models import Room, User+from switch_core.db.stores.room_group_store import RoomGroupStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.db.stores.user_store import UserStore+from switch_core.gateway.room_groups import (+ assign_rooms_to_group,+ create_room_group,+ delete_room_group,+ list_room_groups,+ patch_room_group,+)+from switch_core.gateway.schemas import (+ RoomGroupAssignRequest,+ RoomGroupCreateRequest,+ RoomGroupUpdateRequest,+)++_GROUPS = RoomGroupStore()+_ROOMS = RoomStore()+_USERS = UserStore()+++async def _is_admin(session: AsyncSession, user: User) -> bool:+ """The bit `get_tenant_is_admin` hands the route, resolved the same way."""+ return await _USERS.administers(session, user)+++async def _add_user(session: AsyncSession, *, name: str, role: str = "user") -> User:+ user = User(name=name, email=f"{name}@example.com", role=role)+ session.add(user)+ await session.flush()+ return user+++async def _add_room(+ session: AsyncSession, *, name: str, owner_id: str, read_visibility: str+) -> Room:+ room = Room(+ transport_room_id=f"!{name}:test",+ name=name,+ description="d",+ owner_id=owner_id,+ read_visibility=read_visibility,+ write_visibility="private",+ )+ session.add(room)+ await session.flush()+ return room+++class TestManagingGroups:+ async def test_a_member_cannot_create_edit_or_delete_a_group(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ member = await _add_user(session, name="member")+ group = await _GROUPS.create(+ session,+ name="Customers",+ description=None,+ color=None,+ parent_group_id=None,+ )+ await session.commit()+ is_admin = await _is_admin(session, member)++ with pytest.raises(HTTPException) as created:+ await create_room_group(+ RoomGroupCreateRequest(name="Mine"),+ session,+ _GROUPS,+ member,+ is_admin,+ )+ with pytest.raises(HTTPException) as patched:+ await patch_room_group(+ group.id,+ RoomGroupUpdateRequest(name="Renamed"),+ session,+ _GROUPS,+ _ROOMS,+ member,+ is_admin,+ )+ with pytest.raises(HTTPException) as deleted:+ await delete_room_group(group.id, session, _GROUPS, member, is_admin)++ assert {created.value.status_code, patched.value.status_code} == {403}+ assert deleted.value.status_code == 403+ assert [g.name for g in await _GROUPS.get_all(session)] == ["Customers"]++ async def test_an_admin_can_create_and_rename_a_group(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ admin = await _add_user(session, name="admin", role="admin")+ await session.commit()+ is_admin = await _is_admin(session, admin)++ created = await create_room_group(+ RoomGroupCreateRequest(name="Customers"),+ session,+ _GROUPS,+ admin,+ is_admin,+ )+ renamed = await patch_room_group(+ created.id,+ RoomGroupUpdateRequest(name="Clients"),+ session,+ _GROUPS,+ _ROOMS,+ admin,+ is_admin,+ )++ assert renamed.name == "Clients"++ async def test_a_member_can_still_file_their_room_into_a_group(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ member = await _add_user(session, name="member")+ room = await _add_room(+ session, name="mine", owner_id=member.id, read_visibility="private"+ )+ group = await _GROUPS.create(+ session,+ name="Customers",+ description=None,+ color=None,+ parent_group_id=None,+ )+ await session.commit()++ response = await assign_rooms_to_group(+ group.id,+ RoomGroupAssignRequest(room_ids=[room.id]),+ session,+ _GROUPS,+ _ROOMS,+ member,+ await _is_admin(session, member),+ )++ assert response.assigned == 1+++class TestRoomCounts:+ async def test_counts_leave_out_private_rooms_the_caller_cannot_read(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ member = await _add_user(session, name="member")+ other = await _add_user(session, name="other")+ group = await _GROUPS.create(+ session,+ name="Customers",+ description=None,+ color=None,+ parent_group_id=None,+ )+ public = await _add_room(+ session, name="pub", owner_id=other.id, read_visibility="public"+ )+ private = await _add_room(+ session, name="priv", owner_id=other.id, read_visibility="private"+ )+ for room in (public, private):+ await _ROOMS.set_group(session, room.id, group.id)+ await session.commit()++ async def count_for(user: User) -> int:+ [detail] = await list_room_groups(+ session, _GROUPS, _ROOMS, user, await _is_admin(session, user)+ )+ return detail.room_count++ assert await count_for(member) == 1+ assert await count_for(other) == 2diff --git a/gateway/src/pages/rooms/GroupsPage.test.tsx b/gateway/src/pages/rooms/GroupsPage.test.tsxnew file mode 100644index 000000000..277472fa5--- /dev/null+++ b/gateway/src/pages/rooms/GroupsPage.test.tsx@@ -0,0 +1,76 @@+import { cleanup, render, screen } from "@testing-library/react";+import { MemoryRouter } from "react-router";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { RoomGroupDetail } from "../../data/api";+import { useAuth } from "../../data/AuthContext";+import * as hooks from "../../data/hooks";+import type { UseQueryResult } from "../../data/hooks";+import GroupsPage from "./GroupsPage";++vi.mock("../../data/AuthContext", () => ({+ useAuth: vi.fn(),+}));++vi.mock("../../data/hooks", () => ({+ useRoomGroups: vi.fn(),+ useRooms: vi.fn(),+}));++function authState(canAdminTenant: boolean) {+ return {+ session: null,+ user: null,+ loading: false,+ loadError: null,+ isOperator: false,+ canAdminTenant,+ refresh: vi.fn(async () => {}),+ login: vi.fn(async () => {}),+ logout: vi.fn(async () => {}),+ switchTo: vi.fn(async () => {}),+ };+}++function queryResult<T>(data: T | null): UseQueryResult<T> {+ return { data, loading: false, error: null, refetch: vi.fn() };+}++const group: RoomGroupDetail = {+ id: "g1",+ name: "Customers",+ description: null,+ color: null,+ parent_group_id: null,+ room_count: 0,+ created_at: "2026-01-01",+};++function renderAs(isAdmin: boolean) {+ vi.mocked(useAuth).mockReturnValue(authState(isAdmin));+ vi.mocked(hooks.useRoomGroups).mockReturnValue(queryResult([group]));+ vi.mocked(hooks.useRooms).mockReturnValue(queryResult([]));+ render(+ <MemoryRouter>+ <GroupsPage />+ </MemoryRouter>,+ );+}++describe("GroupsPage", () => {+ afterEach(cleanup);++ it("lets an admin create, edit and delete groups", () => {+ renderAs(true);+ expect(screen.getByRole("button", { name: /new group/i })).toBeTruthy();+ expect(screen.getByLabelText("Edit Customers")).toBeTruthy();+ expect(screen.getByLabelText("Delete Customers")).toBeTruthy();+ });++ it("hides group management from anyone else", () => {+ renderAs(false);+ expect(screen.getByText("Customers")).toBeTruthy();+ expect(screen.queryByRole("button", { name: /new group/i })).toBeNull();+ expect(screen.queryByLabelText("Edit Customers")).toBeNull();+ expect(screen.queryByLabelText("Delete Customers")).toBeNull();+ });+});diff --git a/gateway/src/pages/rooms/GroupsPage.tsx b/gateway/src/pages/rooms/GroupsPage.tsxindex feeea4fcc..d7fc39724 100644--- a/gateway/src/pages/rooms/GroupsPage.tsx+++ b/gateway/src/pages/rooms/GroupsPage.tsx@@ -33,6 +33,7 @@ import {setRoomGroup,updateRoomGroup,} from "../../data/api";+import { useAuth } from "../../data/AuthContext";import { useRoomGroups, useRooms } from "../../data/hooks";import {ancestorChain,@@ -185,6 +186,7 @@ function GroupTree({byId,standaloneCount,selectedId,+ canManage,onSelect,onEdit,onDelete,@@ -193,6 +195,7 @@ function GroupTree({byId: Map<string, RoomGroupDetail>;standaloneCount: number;selectedId: string | null;+ canManage: boolean;onSelect: (id: string) => void;onEdit: (group: RoomGroupDetail) => void;onDelete: (group: RoomGroupDetail) => void;@@ -227,6 +230,7 @@ function GroupTree({<Typography variant="caption" color="text.secondary">{group.room_count}</Typography>+ {canManage && (<Stackdirection="row"className="group-actions"@@ -253,6 +257,7 @@ function GroupTree({<DeleteOutline fontSize="small" /></IconButton></Stack>+ )}</Stack>);})}@@ -454,6 +459,9 @@ function MembershipPanel({export default function GroupsPage() {const navigate = useNavigate();+ // Groups are shared by the workspace, so only an admin creates, edits or+ // deletes them; anyone may file rooms they can write into one.+ const { canAdminTenant: canManageGroups } = useAuth();const { data: groups, loading, refetch } = useRoomGroups();const { data: rooms, refetch: refetchRooms } = useRooms();@@ -507,16 +515,18 @@ export default function GroupsPage() {<Typography variant="h5" sx={{ flexGrow: 1 }}>Room groups</Typography>- <Button- variant="contained"- startIcon={<AddIcon />}- onClick={() => {- setEditGroup(null);- setFormOpen(true);- }}- >- New group- </Button>+ {canManageGroups && (+ <Button+ variant="contained"+ startIcon={<AddIcon />}+ onClick={() => {+ setEditGroup(null);+ setFormOpen(true);+ }}+ >+ New group+ </Button>+ )}</Stack>{loading ? (@@ -526,7 +536,9 @@ export default function GroupsPage() {<Paper variant="outlined" sx={{ borderRadius: 2, p: 1.5, width: 320, flexShrink: 0 }}>{groupList.length === 0 ? (<Typography variant="body2" color="text.secondary" sx={{ p: 1 }}>- No groups yet. Create one to start organizing rooms.+ {canManageGroups+ ? "No groups yet. Create one to start organizing rooms."+ : "No groups yet. A workspace admin can create them."}</Typography>) : (<GroupTree@@ -534,6 +546,7 @@ export default function GroupsPage() {byId={byId}standaloneCount={standaloneCount}selectedId={selectedId}+ canManage={canManageGroups}onSelect={setSelectedId}onEdit={(g) => {setEditGroup(g);