Skip to content

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

Have the server say what the caller may do, instead of the Gateway working it out

Abel Dantasbbd0934d09ef
diff --git a/core/switch_core/bridges/agent/protocol/agent_detail.py b/core/switch_core/bridges/agent/protocol/agent_detail.py
index 887f17d31..3a455540f 100644
--- a/core/switch_core/bridges/agent/protocol/agent_detail.py
+++ b/core/switch_core/bridges/agent/protocol/agent_detail.py
@@ -343,7 +343,7 @@ def agent_facing_summary(summary: AgentSummary) -> dict[str, Any]:
"""`summary` as an agent may read it: without the raw addressing policy,
whose rules name the users, agents and rooms the owner let in. An agent
learns who may address it from `describe_addressing` instead."""
- return summary.model_dump(exclude={"addressing_policy"})
+ return summary.model_dump(exclude={"addressing_policy", "can_manage"})
def agent_facing_detail(detail: AgentDetail) -> dict[str, Any]:
@@ -352,7 +352,8 @@ def agent_facing_detail(detail: AgentDetail) -> dict[str, Any]:
return detail.model_dump(
exclude={
"addressing_policy": True,
- "children": {"__all__": {"addressing_policy"}},
+ "can_manage": True,
+ "children": {"__all__": {"addressing_policy", "can_manage"}},
}
)
diff --git a/core/switch_core/gateway/agents.py b/core/switch_core/gateway/agents.py
index 5ae1bc87a..e357f099c 100644
--- a/core/switch_core/gateway/agents.py
+++ b/core/switch_core/gateway/agents.py
@@ -14,7 +14,7 @@ from switch_core.agent_icon import (
normalise_icon_url,
refuse_third_party_avatar,
)
-from switch_core.authz import Principal, require_manage
+from switch_core.authz import Principal, can_manage, require_manage
from switch_core.bridges.agent.protocol.agent_core import (
AgentCore,
AgentExistsError,
@@ -77,14 +77,26 @@ logger = logging.getLogger(__name__)
router = APIRouter()
+def _for_caller[Summary: AgentSummary](
+ summary: Summary, user: User, is_admin: bool
+) -> Summary:
+ """`summary` with what `user` may do with the agent filled in."""
+ principal = Principal(user.id, is_admin)
+ return summary.model_copy(
+ update={"can_manage": can_manage(principal, summary.owner_id)}
+ )
+
+
@router.get("")
async def list_agents(
session: Annotated[AsyncSession, Depends(get_session)],
agent_store: Annotated[AgentStore, Depends(get_agent_store)],
user_store: Annotated[UserStore, Depends(get_user_store)],
- _user: Annotated[User, Depends(get_current_user)],
+ user: Annotated[User, Depends(get_current_user)],
+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> list[AgentSummary]:
- return await list_agent_summaries(session, agent_store, user_store)
+ summaries = await list_agent_summaries(session, agent_store, user_store)
+ return [_for_caller(summary, user, is_admin) for summary in summaries]
@router.delete("/by-name/{agent_name}")
@@ -418,7 +430,8 @@ async def update_agent_options(
)
owner_name = user.name if agent.owner_id == user.id else None
- return await build_agent_summary(session, agent_store, agent, owner_name)
+ summary = await build_agent_summary(session, agent_store, agent, owner_name)
+ return _for_caller(summary, user, is_admin)
@router.put("/{agent_id}/icon")
@@ -483,7 +496,8 @@ async def update_agent_icon(
)
owner_name = user.name if agent.owner_id == user.id else None
- return await build_agent_summary(session, agent_store, agent, owner_name)
+ summary = await build_agent_summary(session, agent_store, agent, owner_name)
+ return _for_caller(summary, user, is_admin)
@router.put("/{agent_id}/name")
@@ -538,7 +552,11 @@ async def rename_agent(
await session.refresh(renamed)
owner_name = user.name if renamed.owner_id == user.id else None
return RenameAgentResponse(
- agent=await build_agent_summary(session, agent_store, renamed, owner_name),
+ agent=_for_caller(
+ await build_agent_summary(session, agent_store, renamed, owner_name),
+ user,
+ is_admin,
+ ),
old_name=result.old_name,
bridge_failures=result.bridge_failures,
templates_mentioning_old_name=result.templates_mentioning_old_name,
@@ -600,7 +618,8 @@ async def update_agent_display_name(
)
owner_name = user.name if agent.owner_id == user.id else None
- return await build_agent_summary(session, agent_store, agent, owner_name)
+ summary = await build_agent_summary(session, agent_store, agent, owner_name)
+ return _for_caller(summary, user, is_admin)
@router.put("/{agent_id}/description")
@@ -639,7 +658,8 @@ async def update_agent_description(
logger.info("Set agent %s description by user %s", agent.name, user.name)
owner_name = user.name if agent.owner_id == user.id else None
- return await build_agent_summary(session, agent_store, agent, owner_name)
+ summary = await build_agent_summary(session, agent_store, agent, owner_name)
+ return _for_caller(summary, user, is_admin)
@router.post("/register-other")
@@ -726,7 +746,7 @@ async def update_addressing_policy(
user.name,
)
- return await assemble_agent_detail(
+ detail = await assemble_agent_detail(
session,
agent=agent,
agent_store=agent_store,
@@ -736,6 +756,7 @@ async def update_addressing_policy(
room_role_store=protocol.room_role_store,
connections=protocol.connections,
)
+ return _for_caller(detail, user, is_admin)
@router.put("/{agent_id}/can-manage-agents")
@@ -748,6 +769,7 @@ async def update_can_manage_agents(
user_store: Annotated[UserStore, Depends(get_user_store)],
protocol: Annotated[AgentCore, Depends(get_protocol)],
user: Annotated[User, Depends(get_current_user)],
+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> AgentDetail:
"""Turn the agent's "can manage agents" capability on or off.
@@ -777,7 +799,7 @@ async def update_can_manage_agents(
user.name,
)
- return await assemble_agent_detail(
+ detail = await assemble_agent_detail(
session,
agent=agent,
agent_store=agent_store,
@@ -787,6 +809,7 @@ async def update_can_manage_agents(
room_role_store=protocol.room_role_store,
connections=protocol.connections,
)
+ return _for_caller(detail, user, is_admin)
# Declared after the literal GET routes (e.g. /known-types) so those are matched
@@ -799,13 +822,14 @@ async def get_agent_detail(
room_store: Annotated[RoomStore, Depends(get_room_store)],
user_store: Annotated[UserStore, Depends(get_user_store)],
protocol: Annotated[AgentCore, Depends(get_protocol)],
- _user: Annotated[User, Depends(get_current_user)],
+ user: Annotated[User, Depends(get_current_user)],
+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> AgentDetail:
agent = await agent_store.get(session, agent_id)
if agent is None:
raise HTTPException(status_code=404, detail=f"Agent not found: {agent_id}")
- return await assemble_agent_detail(
+ detail = await assemble_agent_detail(
session,
agent=agent,
agent_store=agent_store,
@@ -815,3 +839,4 @@ async def get_agent_detail(
room_role_store=protocol.room_role_store,
connections=protocol.connections,
)
+ return _for_caller(detail, user, is_admin)
diff --git a/core/switch_core/gateway/packages.py b/core/switch_core/gateway/packages.py
index 4521f6d71..d74ac6792 100644
--- a/core/switch_core/gateway/packages.py
+++ b/core/switch_core/gateway/packages.py
@@ -5,6 +5,7 @@ from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
+from switch_core.authz import Principal, can
from switch_core.bridges.resource.service import ResourceService
from switch_core.db.models import Package, User
from switch_core.db.stores.agent_store import AgentStore
@@ -413,7 +414,10 @@ async def list_room_packages(
) -> list[PackageDetail]:
await require_room_access(session, room_store, room_id, user, "read", is_admin)
pkgs = await resource_service.list_room_packages(session, room_id)
- return await _enrich(session, pkgs, resource_service, user_store)
+ principal = Principal(user.id, is_admin)
+ readable = {p.id for p in pkgs if can(principal, "read", p)}
+ details = await _enrich(session, pkgs, resource_service, user_store)
+ return [d.model_copy(update={"can_read": d.id in readable}) for d in details]
@router.post("/rooms/{room_id}/packages/{package_id}", status_code=201)
diff --git a/core/switch_core/gateway/rooms.py b/core/switch_core/gateway/rooms.py
index 1da7a6391..8556752ef 100644
--- a/core/switch_core/gateway/rooms.py
+++ b/core/switch_core/gateway/rooms.py
@@ -10,7 +10,14 @@ from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy.ext.asyncio import AsyncSession
from switch_core.agent_templates import plan_template
-from switch_core.authz import Action, Principal, can, require, require_manage
+from switch_core.authz import (
+ Action,
+ Principal,
+ can,
+ can_manage,
+ require,
+ require_manage,
+)
from switch_core.bridges.agent.operations.agent_management import management_port
from switch_core.bridges.agent.protocol.agent_core import AgentCore
from switch_core.bridges.collaboration.models import (
@@ -177,6 +184,7 @@ async def _build_room_detail(
bridge_store: CollaborationBridgeStore,
external_user_store: ExternalUserStore,
protocol: AgentCore,
+ principal: Principal,
) -> RoomDetail:
agent_ids = await room_store.get_agent_ids(session, room.id)
client_ids = await room_store.get_client_ids(session, room.id)
@@ -210,8 +218,6 @@ async def _build_room_detail(
roles = await _list_room_role_details(session, room.id, protocol)
join_event_listeners = await room_store.get_join_event_listeners(session, room.id)
- # The Gateway decides from the owner which controls to offer (only the
- # owner or an admin may change access or delete the room).
owner = await session.get(User, room.owner_id) if room.owner_id else None
# Not held across the deeplink, which can ask the platform on a cache miss.
await session.commit()
@@ -252,6 +258,8 @@ 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),
+ can_write=can(principal, "write", room),
+ can_manage=can_manage(principal, room.owner_id),
)
@@ -332,6 +340,7 @@ async def list_rooms(
include_archived=include_archived,
)
+ principal = Principal(user.id, is_admin)
group_names = {g.id: g.name for g in await room_group_store.get_all(session)}
bridge_ids = {r.bridge_id for r in rooms if r.bridge_id}
@@ -390,6 +399,8 @@ async def list_rooms(
write_visibility=room.write_visibility,
created_at=str(room.created_at),
archived=room.archived_at is not None,
+ can_write=can(principal, "write", room),
+ can_manage=can_manage(principal, room.owner_id),
)
)
@@ -406,6 +417,7 @@ async def create_room(
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:
_validate_create(req)
config = RoomCreateConfig(
@@ -442,7 +454,13 @@ async def create_room(
if fresh is None:
raise HTTPException(status_code=500, detail="Room missing after create")
return await _build_room_detail(
- session, fresh, room_store, bridge_store, external_user_store, protocol
+ session,
+ fresh,
+ room_store,
+ bridge_store,
+ external_user_store,
+ protocol,
+ principal=Principal(user.id, is_admin),
)
@@ -886,7 +904,13 @@ async def get_room(
) -> RoomDetail:
room = await _require_room(session, room_store, room_id, user, "read", is_admin)
return await _build_room_detail(
- session, room, room_store, bridge_store, external_user_store, protocol
+ session,
+ room,
+ room_store,
+ bridge_store,
+ external_user_store,
+ protocol,
+ principal=Principal(user.id, is_admin),
)
@@ -932,7 +956,13 @@ async def patch_room(
if room is None:
raise HTTPException(status_code=404, detail="Room not found")
return await _build_room_detail(
- session, room, room_store, bridge_store, external_user_store, protocol
+ session,
+ room,
+ room_store,
+ bridge_store,
+ external_user_store,
+ protocol,
+ principal=Principal(user.id, is_admin),
)
@@ -1045,7 +1075,13 @@ async def put_room_group(
if room is None:
raise HTTPException(status_code=404, detail="Room not found")
return await _build_room_detail(
- session, room, room_store, bridge_store, external_user_store, protocol
+ session,
+ room,
+ room_store,
+ bridge_store,
+ external_user_store,
+ protocol,
+ principal=Principal(user.id, is_admin),
)
@@ -1072,7 +1108,13 @@ async def put_protection(
if room is None:
raise HTTPException(status_code=404, detail="Room not found")
return await _build_room_detail(
- session, room, room_store, bridge_store, external_user_store, protocol
+ session,
+ room,
+ room_store,
+ bridge_store,
+ external_user_store,
+ protocol,
+ principal=Principal(user.id, is_admin),
)
@@ -1099,7 +1141,13 @@ async def put_observe(
if room is None:
raise HTTPException(status_code=404, detail="Room not found")
return await _build_room_detail(
- session, room, room_store, bridge_store, external_user_store, protocol
+ session,
+ room,
+ room_store,
+ bridge_store,
+ external_user_store,
+ protocol,
+ principal=Principal(user.id, is_admin),
)
@@ -1131,7 +1179,13 @@ async def post_room_agents(
if room is None:
raise HTTPException(status_code=404, detail="Room not found")
return await _build_room_detail(
- session, room, room_store, bridge_store, external_user_store, protocol
+ session,
+ room,
+ room_store,
+ bridge_store,
+ external_user_store,
+ protocol,
+ principal=Principal(user.id, is_admin),
)
@@ -1160,7 +1214,13 @@ async def patch_room_agent(
if room is None:
raise HTTPException(status_code=404, detail="Room not found")
return await _build_room_detail(
- session, room, room_store, bridge_store, external_user_store, protocol
+ session,
+ room,
+ room_store,
+ bridge_store,
+ external_user_store,
+ protocol,
+ principal=Principal(user.id, is_admin),
)
@@ -1187,7 +1247,13 @@ async def delete_room_agent(
if room is None:
raise HTTPException(status_code=404, detail="Room not found")
return await _build_room_detail(
- session, room, room_store, bridge_store, external_user_store, protocol
+ session,
+ room,
+ room_store,
+ bridge_store,
+ external_user_store,
+ protocol,
+ principal=Principal(user.id, is_admin),
)
@@ -1214,7 +1280,13 @@ async def post_room_users(
if room is None:
raise HTTPException(status_code=404, detail="Room not found")
return await _build_room_detail(
- session, room, room_store, bridge_store, external_user_store, protocol
+ session,
+ room,
+ room_store,
+ bridge_store,
+ external_user_store,
+ protocol,
+ principal=Principal(user.id, is_admin),
)
@@ -1239,7 +1311,13 @@ async def _set_archived(
if room is None:
raise HTTPException(status_code=404, detail="Room not found")
return await _build_room_detail(
- session, room, room_store, bridge_store, external_user_store, protocol
+ session,
+ room,
+ room_store,
+ bridge_store,
+ external_user_store,
+ protocol,
+ principal=Principal(user.id, is_admin),
)
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index 416a129c0..e91d8b118 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -85,6 +85,12 @@ class RoomSummary(BaseModel):
created_at: str
# True when the room is archived (hidden from the default active list).
archived: bool = False
+ # What the caller may do with the room, decided here by `switch_core.authz`
+ # so the Gateway shows the right controls without repeating the rules.
+ # Write: edit its fields, add agents and people, attach resources. Manage:
+ # also change who may see or write to it, and delete it.
+ can_write: bool = False
+ can_manage: bool = False
class RoomDetail(RoomSummary):
@@ -287,6 +293,11 @@ class AgentSummary(BaseModel):
# owner-restricted without fetching each one — the console warns about
# exactly that, and per-agent reads would make it a request storm.
addressing_policy: AddressingPolicy | None = None
+ # Whether the caller may manage the agent (rename it, edit its options and
+ # who may address it): its owner or a workspace admin. Decided here by
+ # `switch_core.authz` so the Gateway does not repeat the rule; set by the
+ # Gateway routes, and left out of what agents read.
+ can_manage: bool = False
class AgentToolSummary(BaseModel):
@@ -1449,6 +1460,11 @@ class PackageDetail(BaseModel):
documents_count: int = 0
attached_rooms_count: int = 0
created_at: str
+ # Whether the caller may open the package. Every route returns only
+ # packages the caller may read, except a room's package list: a private
+ # package its owner attached is listed to every reader of the room, and the
+ # Gateway shows that one without a link.
+ can_read: bool = True
class PackageCreateRequest(BaseModel):
diff --git a/core/tests/switch_core/gateway/test_agent_can_manage_agents_route.py b/core/tests/switch_core/gateway/test_agent_can_manage_agents_route.py
index 163e9f7fb..fac973f5b 100644
--- a/core/tests/switch_core/gateway/test_agent_can_manage_agents_route.py
+++ b/core/tests/switch_core/gateway/test_agent_can_manage_agents_route.py
@@ -23,7 +23,7 @@ from switch_core.db.stores.room_store import RoomStore
from switch_core.db.stores.user_store import UserStore
from switch_core.gateway.agents import update_can_manage_agents
from switch_core.gateway.schemas import AgentDetail, UpdateAgentCanManageAgentsRequest
-from tests.switch_core.gateway.agent_route_harness import add_agent, add_user
+from tests.switch_core.gateway.agent_route_harness import add_agent, add_user, is_admin
async def _set(
@@ -42,6 +42,7 @@ async def _set(
connections=AgentConnectionRegistry(),
),
user,
+ await is_admin(session, user),
)
diff --git a/core/tests/switch_core/gateway/test_caller_permissions.py b/core/tests/switch_core/gateway/test_caller_permissions.py
new file mode 100644
index 000000000..b862a319e
--- /dev/null
+++ b/core/tests/switch_core/gateway/test_caller_permissions.py
@@ -0,0 +1,159 @@
+"""What the server tells the Gateway the caller may do.
+
+The Gateway offers a room's, an agent's and a package's controls from flags the
+server works out with `switch_core.authz`, so the rules live in one place. These
+pin the flags against those rules: owner, workspace admin, and a member who
+only has what the resource's visibility gives everyone.
+"""
+
+from __future__ import annotations
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.bridges.agent.protocol.agent_detail import agent_facing_summary
+from switch_core.db.models import Package, User
+from switch_core.db.stores.agent_store import AgentStore
+from switch_core.db.stores.user_store import UserStore
+from switch_core.gateway.agents import list_agents
+from switch_core.gateway.packages import list_room_packages
+from switch_core.gateway.rooms import get_room
+from tests.switch_core.gateway.agent_route_harness import add_agent, add_user
+from tests.switch_core.gateway.test_room_detail_access import (
+ _ROOM_STORE,
+ _USER_STORE,
+ _add_room,
+ _protocol,
+ _svc,
+)
+
+
+class TestRoomPermissions:
+ @pytest.mark.parametrize(
+ ("caller", "write_visibility", "can_write", "can_manage"),
+ [
+ ("owner", "private", True, True),
+ ("admin", "private", True, True),
+ ("member", "public", True, False),
+ ("member", "private", False, False),
+ ],
+ )
+ async def test_the_room_detail_says_what_the_caller_may_do(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ caller: str,
+ write_visibility: str,
+ can_write: bool,
+ can_manage: bool,
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ member = await add_user(session, name="member")
+ room = await _add_room(
+ session,
+ name="r1",
+ owner_id=owner.id,
+ read_visibility="public",
+ write_visibility=write_visibility,
+ )
+ user = owner if caller == "owner" else member
+
+ detail = await get_room(
+ room.id,
+ session,
+ _ROOM_STORE,
+ None, # type: ignore[arg-type] # bridge_store: the room has no bridge
+ None, # type: ignore[arg-type] # external_user_store
+ _protocol(),
+ user,
+ caller == "admin",
+ )
+
+ assert (detail.can_write, detail.can_manage) == (can_write, can_manage)
+
+
+class TestAgentPermissions:
+ async def test_each_listed_agent_says_whether_the_caller_may_manage_it(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ member = await add_user(session, name="member")
+ await add_agent(session, name="mine", owner_id=owner.id)
+ await add_agent(session, name="theirs", owner_id=member.id)
+
+ async def manageable(user: User, admin: bool) -> dict[str, bool]:
+ summaries = await list_agents(
+ session, AgentStore(), UserStore(), user, admin
+ )
+ return {s.name: s.can_manage for s in summaries}
+
+ assert await manageable(owner, False) == {"mine": True, "theirs": False}
+ assert await manageable(owner, True) == {"mine": True, "theirs": True}
+
+ async def test_an_agent_reading_a_summary_is_not_told_the_flag(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """The flag is about the Gateway's caller, not the agent reading it."""
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ await add_agent(session, name="mine", owner_id=owner.id)
+ [summary] = await list_agents(
+ session, AgentStore(), UserStore(), owner, False
+ )
+
+ assert "can_manage" not in agent_facing_summary(summary)
+
+
+class TestRoomPackagePermissions:
+ async def test_each_package_in_a_room_says_whether_the_caller_may_open_it(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ member = await add_user(session, name="member")
+ room = await _add_room(
+ session, name="r1", owner_id=owner.id, read_visibility="public"
+ )
+ shared = Package(
+ owner_id=owner.id,
+ name="shared",
+ description="",
+ instructions="",
+ read_visibility="public",
+ write_visibility="private",
+ )
+ private = Package(
+ owner_id=owner.id,
+ name="private",
+ description="",
+ instructions="",
+ read_visibility="private",
+ write_visibility="private",
+ )
+ session.add_all([shared, private])
+ await session.flush()
+ svc = _svc(session_factory)
+ for package in (shared, private):
+ await svc.attach_package_to_room(
+ session,
+ room.id,
+ package.id,
+ user_id=owner.id,
+ is_admin=False,
+ )
+
+ async def readable(user: User) -> dict[str, bool]:
+ packages = await list_room_packages(
+ room.id,
+ session,
+ svc,
+ _ROOM_STORE,
+ _USER_STORE,
+ user,
+ False,
+ )
+ return {p.name: p.can_read for p in packages}
+
+ assert await readable(member) == {"shared": True, "private": False}
+ assert await readable(owner) == {"shared": True, "private": True}
diff --git a/core/tests/switch_core/gateway/test_room_create_platform_error.py b/core/tests/switch_core/gateway/test_room_create_platform_error.py
index 2f12c9064..4a1374506 100644
--- a/core/tests/switch_core/gateway/test_room_create_platform_error.py
+++ b/core/tests/switch_core/gateway/test_room_create_platform_error.py
@@ -61,6 +61,7 @@ async def _call(exc: Exception) -> HTTPException:
external_user_store=None, # type: ignore[arg-type]
protocol=None, # type: ignore[arg-type]
user=type("U", (), {"id": "u1"})(), # type: ignore[arg-type]
+ is_admin=False,
)
return excinfo.value
@@ -98,4 +99,5 @@ async def test_an_ordinary_bug_is_not_dressed_up_as_a_platform_refusal() -> None
external_user_store=None, # type: ignore[arg-type]
protocol=None, # type: ignore[arg-type]
user=type("U", (), {"id": "u1"})(), # type: ignore[arg-type]
+ is_admin=False,
)
diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.ts
index 4cb24c01a..780cfbe8f 100644
--- a/gateway/src/data/api.ts
+++ b/gateway/src/data/api.ts
@@ -35,6 +35,11 @@ export interface RoomSummary {
write_visibility: "public" | "private";
created_at: string;
archived: boolean;
+ // What the caller may do with the room, as the server decides it. Write:
+ // edit its fields, add agents and people, attach resources. Manage: also
+ // change who may see or write to it, and delete it.
+ can_write: boolean;
+ can_manage: boolean;
}
export interface AgentSummary {
@@ -55,6 +60,9 @@ export interface AgentSummary {
parent_agent_id: string | null;
known_agent_type: string | null;
known_agent_options: Record<string, unknown> | null;
+ // Whether the caller may rename the agent and edit its options and who may
+ // address it, as the server decides it: its owner or a workspace admin.
+ can_manage: boolean;
}
export interface AgentToolSummary {
@@ -1740,6 +1748,9 @@ export interface PackageDetail {
documents_count: number;
attached_rooms_count: number;
created_at: string;
+ // Whether the caller may open the package. Only a room's package list
+ // includes packages the caller cannot read.
+ can_read: boolean;
}
export interface PackageCreateInput {
diff --git a/gateway/src/pages/agents/AgentDetailPage.tsx b/gateway/src/pages/agents/AgentDetailPage.tsx
index c90928e4d..13b137583 100644
--- a/gateway/src/pages/agents/AgentDetailPage.tsx
+++ b/gateway/src/pages/agents/AgentDetailPage.tsx
@@ -78,7 +78,7 @@ function StatusDot({ color, title }: { color: string; title?: string }) {
export default function AgentDetailPage() {
const { agentId } = useParams<{ agentId: string }>();
const navigate = useNavigate();
- const { user, canAdminTenant } = useAuth();
+ const { user } = useAuth();
const { data: agent, loading, error, refetch } = useAgent(agentId);
const [renameOpen, setRenameOpen] = useState(false);
const [renameNotice, setRenameNotice] = useState<{
@@ -108,10 +108,11 @@ export default function AgentDetailPage() {
}
const isOwner = !!user && user.id === agent.owner_id;
- // Renaming and editing options are open to the owner or an admin; agent
- // management and service access stay with the owner alone, because the
- // agent then acts on the owner's own machines and credentials.
- const canManage = isOwner || canAdminTenant;
+ // Renaming and editing options are open to whoever the server says may
+ // manage the agent (its owner or an admin); agent management and service
+ // access stay with the owner alone, because the agent then acts on the
+ // owner's own machines and credentials.
+ const canManage = agent.can_manage;
return (
<Box>
diff --git a/gateway/src/pages/agents/AgentManagementSection.test.tsx b/gateway/src/pages/agents/AgentManagementSection.test.tsx
index 9810cfa2d..3cb67ab17 100644
--- a/gateway/src/pages/agents/AgentManagementSection.test.tsx
+++ b/gateway/src/pages/agents/AgentManagementSection.test.tsx
@@ -28,6 +28,7 @@ const agent: AgentDetail = {
children: [],
addressing_policy: null,
can_manage_agents: false,
+ can_manage: true,
};
type Call = { path: string; method: string; body: unknown };
diff --git a/gateway/src/pages/agents/AgentRenameDialog.test.tsx b/gateway/src/pages/agents/AgentRenameDialog.test.tsx
index 0cda7cbd6..0b239ac4a 100644
--- a/gateway/src/pages/agents/AgentRenameDialog.test.tsx
+++ b/gateway/src/pages/agents/AgentRenameDialog.test.tsx
@@ -66,6 +66,7 @@ const agent: AgentDetail = {
children: [],
addressing_policy: null,
can_manage_agents: false,
+ can_manage: true,
};
function showPage(detail: AgentDetail) {
diff --git a/gateway/src/pages/agents/AgentsPage.test.tsx b/gateway/src/pages/agents/AgentsPage.test.tsx
index 8c6f228b9..dd0a243e7 100644
--- a/gateway/src/pages/agents/AgentsPage.test.tsx
+++ b/gateway/src/pages/agents/AgentsPage.test.tsx
@@ -3,7 +3,6 @@ import type { GridColDef } from "@mui/x-data-grid";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { AgentSummary } from "../../data/api";
import * as api from "../../data/api";
-import { useAuth } from "../../data/AuthContext";
import * as hooks from "../../data/hooks";
import AgentsPage from "./AgentsPage";
@@ -11,10 +10,6 @@ vi.mock("react-router", () => ({
useNavigate: () => vi.fn(),
}));
-vi.mock("../../data/AuthContext", () => ({
- useAuth: vi.fn(),
-}));
-
vi.mock("../../data/hooks", () => ({
useAgents: vi.fn(),
}));
@@ -57,6 +52,7 @@ const agent = {
owner_name: "ada",
created_at: "2026-10-01T00:00:00Z",
parent_agent_id: null,
+ can_manage: true,
} as unknown as AgentSummary;
async function deleteTheAgent() {
@@ -68,10 +64,6 @@ async function deleteTheAgent() {
describe("AgentsPage delete", () => {
beforeEach(() => {
- vi.mocked(useAuth).mockReturnValue({
- user: { id: "u1" },
- canAdminTenant: false,
- } as unknown as ReturnType<typeof useAuth>);
vi.mocked(hooks.useAgents).mockReturnValue({
data: [agent],
loading: false,
diff --git a/gateway/src/pages/agents/AgentsPage.tsx b/gateway/src/pages/agents/AgentsPage.tsx
index 3809bfd3b..d09aaf48f 100644
--- a/gateway/src/pages/agents/AgentsPage.tsx
+++ b/gateway/src/pages/agents/AgentsPage.tsx
@@ -25,7 +25,6 @@ import { useCallback, useMemo, useState } from "react";
import { useNavigate } from "react-router";
import DataTable from "../../components/DataTable";
import { type AgentSummary, deleteAgent } from "../../data/api";
-import { useAuth } from "../../data/AuthContext";
import { useAgents } from "../../data/hooks";
import { EM_DASH, formatDate, titleCase } from "../../theme/hootFormat";
import RegisterAgentDialog from "./RegisterAgentDialog";
@@ -36,7 +35,6 @@ import RegisterAgentDialog from "./RegisterAgentDialog";
export default function AgentsPage() {
const navigate = useNavigate();
- const { user, canAdminTenant: isAdmin } = useAuth();
const { data: agents, loading, refetch } = useAgents();
const [deleteTarget, setDeleteTarget] = useState<AgentSummary | null>(null);
const [deleteNotice, setDeleteNotice] = useState<{
@@ -206,8 +204,7 @@ export default function AgentsPage() {
sortable: false,
filterable: false,
renderCell: ({ row }) => {
- const canModify = isAdmin || row.owner_id === user?.id;
- if (!canModify) return null;
+ if (!row.can_manage) return null;
return (
<>
<IconButton
@@ -224,7 +221,7 @@ export default function AgentsPage() {
},
},
],
- [isAdmin, user?.id, parentNameById],
+ [parentNameById],
);
return (
diff --git a/gateway/src/pages/agents/ServiceAccessSection.test.tsx b/gateway/src/pages/agents/ServiceAccessSection.test.tsx
index 6c6db0207..41058ec9e 100644
--- a/gateway/src/pages/agents/ServiceAccessSection.test.tsx
+++ b/gateway/src/pages/agents/ServiceAccessSection.test.tsx
@@ -39,6 +39,7 @@ const agent: AgentDetail = {
children: [],
addressing_policy: null,
can_manage_agents: false,
+ can_manage: true,
};
const GITHUB = {
diff --git a/gateway/src/pages/agents/agentManageControls.test.tsx b/gateway/src/pages/agents/agentManageControls.test.tsx
index d65e04816..2d0feee32 100644
--- a/gateway/src/pages/agents/agentManageControls.test.tsx
+++ b/gateway/src/pages/agents/agentManageControls.test.tsx
@@ -5,8 +5,9 @@ import { useAuth } from "../../data/AuthContext";
import * as hooks from "../../data/hooks";
import AgentDetailPage from "./AgentDetailPage";
-// The server lets an agent's owner or an admin rename it and edit its options,
-// so both see those controls; anyone else sees neither.
+// The server says whether the caller may manage the agent (its owner or an
+// admin): those who may see the rename and options controls, anyone else sees
+// neither.
vi.mock("react-router", () => ({
useNavigate: () => vi.fn(),
@@ -47,13 +48,12 @@ const agent = {
children: [],
} as unknown as AgentDetail;
-function showPageAs(userId: string, canAdminTenant: boolean) {
+function showPageAs(userId: string, canManage: boolean) {
vi.mocked(useAuth).mockReturnValue({
user: { id: userId },
- canAdminTenant,
} as unknown as ReturnType<typeof useAuth>);
vi.mocked(hooks.useAgent).mockReturnValue({
- data: agent,
+ data: { ...agent, can_manage: canManage },
loading: false,
error: null,
refetch: vi.fn(),
@@ -77,7 +77,7 @@ function showPageAs(userId: string, canAdminTenant: boolean) {
afterEach(cleanup);
describe("agent rename and options", () => {
- it("are offered to an admin viewing someone else's agent", () => {
+ it("are offered to someone else the server says may manage it, such as an admin", () => {
showPageAs("u2", true);
expect(screen.getByRole("button", { name: "Rename agent" })).toBeTruthy();
@@ -86,7 +86,7 @@ describe("agent rename and options", () => {
});
it("are offered to the owner", () => {
- showPageAs("u1", false);
+ showPageAs("u1", true);
expect(screen.getByRole("button", { name: "Rename agent" })).toBeTruthy();
expect(screen.getByRole("button", { name: "Save" })).toBeTruthy();
diff --git a/gateway/src/pages/rooms/RoomDetailPage.tsx b/gateway/src/pages/rooms/RoomDetailPage.tsx
index 86689bfd4..ffee64d6d 100644
--- a/gateway/src/pages/rooms/RoomDetailPage.tsx
+++ b/gateway/src/pages/rooms/RoomDetailPage.tsx
@@ -48,7 +48,6 @@ import {
updateRoomRole,
} from "../../data/api";
import { useAgents, useBridgeUsers, useRoom, useRoomGroups } from "../../data/hooks";
-import { useAuth } from "../../data/AuthContext";
import { AccessChip, AccessSelect } from "../../components/AccessControls";
import { type AccessLevel, fromAccessLevel, toAccessLevel } from "../../data/visibility";
import {
@@ -67,7 +66,6 @@ import ExportRoomYamlDialog from "./ExportRoomYamlDialog";
export default function RoomDetailPage() {
const { roomId } = useParams<{ roomId: string }>();
const navigate = useNavigate();
- const { user, canAdminTenant } = useAuth();
const { data: room, loading, error, refetch } = useRoom(roomId);
const [exportOpen, setExportOpen] = useState(false);
@@ -92,16 +90,11 @@ export default function RoomDetailPage() {
);
}
- // Room write access: owner, admin, or a publicly-writable room.
- const canWrite =
- !!user &&
- (user.id === room.owner_id ||
- canAdminTenant ||
- room.write_visibility === "public");
- // Delete and access changes are stricter: owner or admin only, never via
- // public write (the server's `require_manage` / `delete` checks).
- const canManage =
- !!user && (user.id === room.owner_id || canAdminTenant);
+ // The server says what the caller may do: write covers the room's fields,
+ // agents, people and resources; deleting it and changing its access need
+ // manage, which public write never gives.
+ const canWrite = room.can_write;
+ const canManage = room.can_manage;
const canDelete = canManage;
return (
diff --git a/gateway/src/pages/rooms/RoomResourcesSection.tsx b/gateway/src/pages/rooms/RoomResourcesSection.tsx
index 2d0e43c68..8aaee225e 100644
--- a/gateway/src/pages/rooms/RoomResourcesSection.tsx
+++ b/gateway/src/pages/rooms/RoomResourcesSection.tsx
@@ -22,7 +22,6 @@ import {
detachPackageFromRoom,
detachReferenceFromRoom,
} from "../../data/api";
-import { useAuth } from "../../data/AuthContext";
import {
useDocuments,
usePackages,
@@ -31,7 +30,6 @@ import {
useRoomPackages,
useRoomReferences,
} from "../../data/hooks";
-import { canReadResource } from "./roomAccess";
interface Props {
roomId: string;
@@ -50,16 +48,11 @@ export default function RoomResourcesSection({ roomId, canWrite }: Props) {
return m;
}, [roomPackages]);
// A private package attached by its owner is listed to every reader of the
- // room, but only those who may read it get a link to it.
- const { user, canAdminTenant } = useAuth();
+ // room, but only those the server says may read it get a link to it.
const readablePackageIds = useMemo(
() =>
- new Set(
- (roomPackages ?? [])
- .filter((p) => canReadResource(p, user?.id, canAdminTenant))
- .map((p) => p.id),
- ),
- [roomPackages, user, canAdminTenant],
+ new Set((roomPackages ?? []).filter((p) => p.can_read).map((p) => p.id)),
+ [roomPackages],
);
return (
diff --git a/gateway/src/pages/rooms/RoomScopedDocumentView.test.tsx b/gateway/src/pages/rooms/RoomScopedDocumentView.test.tsx
index bf08e281c..af1137772 100644
--- a/gateway/src/pages/rooms/RoomScopedDocumentView.test.tsx
+++ b/gateway/src/pages/rooms/RoomScopedDocumentView.test.tsx
@@ -1,22 +1,17 @@
import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { DocumentDetail, RoomDetail } from "../../data/api";
-import { useAuth } from "../../data/AuthContext";
import * as hooks from "../../data/hooks";
import RoomScopedDocumentView from "./RoomScopedDocumentView";
-// Deleting a room's document is a write to the room: its owner, an admin, or
-// anyone in a publicly writable room. A reader sees the document only.
+// Deleting a room's document is a write to the room, offered only when the
+// server says the caller may write to it. A reader sees the document only.
vi.mock("react-router", () => ({
useNavigate: () => vi.fn(),
useParams: () => ({ roomId: "r1", documentId: "d1" }),
}));
-vi.mock("../../data/AuthContext", () => ({
- useAuth: vi.fn(),
-}));
-
vi.mock("../../data/hooks", () => ({
useRoom: vi.fn(),
useRoomDocument: vi.fn(),
@@ -38,22 +33,10 @@ const query = <T,>(data: T | null) => ({
refetch: vi.fn(),
});
-function showDocument(room: Partial<RoomDetail> | null, canAdminTenant = false) {
- vi.mocked(useAuth).mockReturnValue({
- user: { id: "u1" },
- canAdminTenant,
- } as unknown as ReturnType<typeof useAuth>);
+function showDocument(room: { can_write: boolean } | null) {
vi.mocked(hooks.useRoomDocument).mockReturnValue(query(doc));
vi.mocked(hooks.useRoom).mockReturnValue(
- query(
- room && ({
- id: "r1",
- owner_id: "someone",
- read_visibility: "public",
- write_visibility: "private",
- ...room,
- } as RoomDetail),
- ),
+ query(room && ({ id: "r1", ...room } as RoomDetail)),
);
render(<RoomScopedDocumentView />);
}
@@ -61,8 +44,8 @@ function showDocument(room: Partial<RoomDetail> | null, canAdminTenant = false)
afterEach(cleanup);
describe("room document delete", () => {
- it("is not offered to a reader of the room", () => {
- showDocument({});
+ it("is not offered to someone who may only read the room", () => {
+ showDocument({ can_write: false });
expect(screen.getByText("hello")).toBeTruthy();
expect(screen.queryByRole("button", { name: "Delete" })).toBeNull();
@@ -74,20 +57,8 @@ describe("room document delete", () => {
expect(screen.queryByRole("button", { name: "Delete" })).toBeNull();
});
- it("is offered to the room's owner", () => {
- showDocument({ owner_id: "u1" });
-
- expect(screen.getByRole("button", { name: "Delete" })).toBeTruthy();
- });
-
- it("is offered in a publicly writable room", () => {
- showDocument({ write_visibility: "public" });
-
- expect(screen.getByRole("button", { name: "Delete" })).toBeTruthy();
- });
-
- it("is offered to an admin", () => {
- showDocument({}, true);
+ it("is offered to someone who may write to the room", () => {
+ showDocument({ can_write: true });
expect(screen.getByRole("button", { name: "Delete" })).toBeTruthy();
});
diff --git a/gateway/src/pages/rooms/RoomScopedDocumentView.tsx b/gateway/src/pages/rooms/RoomScopedDocumentView.tsx
index ab0be1c81..4edb3f116 100644
--- a/gateway/src/pages/rooms/RoomScopedDocumentView.tsx
+++ b/gateway/src/pages/rooms/RoomScopedDocumentView.tsx
@@ -15,9 +15,7 @@ import {
import { useState } from "react";
import { useNavigate, useParams } from "react-router";
import { detachDocumentFromRoom } from "../../data/api";
-import { useAuth } from "../../data/AuthContext";
import { useRoom, useRoomDocument } from "../../data/hooks";
-import { canWriteRoom } from "./roomAccess";
export default function RoomScopedDocumentView() {
const { roomId, documentId } = useParams<{
@@ -29,8 +27,7 @@ export default function RoomScopedDocumentView() {
// Deleting a room document (or detaching a shared one) is a write to the
// room, so it is offered only to those who may write to it.
const { data: room } = useRoom(roomId);
- const { user, canAdminTenant } = useAuth();
- const canWrite = !!room && canWriteRoom(room, user?.id, canAdminTenant);
+ const canWrite = !!room && room.can_write;
const [deleting, setDeleting] = useState(false);
const [deleteError, setDeleteError] = useState<string | null>(null);
diff --git a/gateway/src/pages/rooms/RoomsPage.test.tsx b/gateway/src/pages/rooms/RoomsPage.test.tsx
index 9f7c1ffc6..18371bb2d 100644
--- a/gateway/src/pages/rooms/RoomsPage.test.tsx
+++ b/gateway/src/pages/rooms/RoomsPage.test.tsx
@@ -1,24 +1,19 @@
import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import type { GridColDef, GridRowId, GridRowParams } from "@mui/x-data-grid";
import { useState } from "react";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import type { RoomSummary } from "../../data/api";
import * as api from "../../data/api";
-import { useAuth } from "../../data/AuthContext";
import RoomsPage from "./RoomsPage";
-// Archiving a room is a write: its owner, an admin, or anyone in a publicly
-// writable room. The page offers it only there, and says when the server
-// changed fewer rooms than were asked for.
+// Archiving a room is a write. The page offers it only on rooms the server says
+// the caller may write to, and says when the server changed fewer rooms than
+// were asked for.
vi.mock("react-router", () => ({
useNavigate: () => vi.fn(),
}));
-vi.mock("../../data/AuthContext", () => ({
- useAuth: vi.fn(),
-}));
-
const room = (id: string, overrides: Partial<RoomSummary>) =>
({
id,
@@ -38,12 +33,14 @@ const room = (id: string, overrides: Partial<RoomSummary>) =>
write_visibility: "private",
created_at: "2026-10-01T00:00:00Z",
archived: false,
+ can_write: false,
+ can_manage: false,
...overrides,
}) as RoomSummary;
const ROOMS = [
- room("mine", { owner_id: "u1" }),
- room("open", { write_visibility: "public" }),
+ room("mine", { owner_id: "u1", can_write: true, can_manage: true }),
+ room("open", { write_visibility: "public", can_write: true }),
room("readonly", {}),
];
@@ -103,20 +100,13 @@ vi.mock("../../components/DataTable", () => ({
},
}));
-beforeEach(() => {
- vi.mocked(useAuth).mockReturnValue({
- user: { id: "u1" },
- canAdminTenant: false,
- } as unknown as ReturnType<typeof useAuth>);
-});
-
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
describe("RoomsPage archive", () => {
- it("offers archive only on rooms the user can write", () => {
+ it("offers archive only on rooms the server says the user can write", () => {
render(<RoomsPage />);
for (const name of ["mine", "open"]) {
@@ -129,16 +119,6 @@ describe("RoomsPage archive", () => {
expect(within(readonly).queryByRole("checkbox")).toBeNull();
});
- it("offers archive on every room to an admin", () => {
- vi.mocked(useAuth).mockReturnValue({
- user: { id: "u1" },
- canAdminTenant: true,
- } as unknown as ReturnType<typeof useAuth>);
- render(<RoomsPage />);
-
- expect(screen.getAllByRole("button", { name: "Archive" })).toHaveLength(3);
- });
-
it("says when a bulk archive changed only some rooms", async () => {
vi.mocked(api.bulkArchiveRooms).mockResolvedValue({ updated: 1 });
render(<RoomsPage />);
diff --git a/gateway/src/pages/rooms/RoomsPage.tsx b/gateway/src/pages/rooms/RoomsPage.tsx
index e7f061fc0..ce3abd121 100644
--- a/gateway/src/pages/rooms/RoomsPage.tsx
+++ b/gateway/src/pages/rooms/RoomsPage.tsx
@@ -15,11 +15,9 @@ import {
bulkArchiveRooms,
unarchiveRoom,
} from "../../data/api";
-import { useAuth } from "../../data/AuthContext";
import { useRoomGroups, useRooms } from "../../data/hooks";
import { EM_DASH, MONO_SX, channelTypeLabel, formatDate } from "../../theme/hootFormat";
import { buildGroupIndex, effectiveColor, groupPathName } from "./groupTree";
-import { canWriteRoom } from "./roomAccess";
import { RoomFilters, filterRooms, useRoomFilterState } from "./roomFilters";
function Missing() {
@@ -53,7 +51,6 @@ export default function RoomsPage() {
severity: "error" | "warning";
text: string;
} | null>(null);
- const { user, canAdminTenant } = useAuth();
const { data: rooms, loading, refetch } = useRooms(
filters.debouncedSearch || undefined,
@@ -79,12 +76,9 @@ export default function RoomsPage() {
],
);
- // Archiving is a write: the owner, an admin, or anyone in a publicly
- // writable room. Other rooms get no archive action and can't be selected.
- const canWrite = useCallback(
- (room: RoomSummary) => canWriteRoom(room, user?.id, canAdminTenant),
- [user, canAdminTenant],
- );
+ // Archiving is a write, as the server reports it for each room. Other rooms
+ // get no archive action and can't be selected.
+ const canWrite = useCallback((room: RoomSummary) => room.can_write, []);
const handleToggleArchive = useCallback(
async (roomId: string, archived: boolean) => {
diff --git a/gateway/src/pages/rooms/roomAccess.ts b/gateway/src/pages/rooms/roomAccess.ts
deleted file mode 100644
index 79734e016..000000000
--- a/gateway/src/pages/rooms/roomAccess.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import type { VisibilityPair } from "../../data/visibility";
-
-/** Whether a user may write to a room, as the server decides it (`can(...,
- * "write", room)` in `switch_core.authz`): its owner, a tenant admin, or
- * anyone when the room is publicly writable. */
-export function canWriteRoom(
- room: VisibilityPair & { owner_id: string | null },
- userId: string | null | undefined,
- canAdminTenant: boolean,
-): boolean {
- if (!userId) return false;
- return (
- canAdminTenant ||
- (room.owner_id !== null && room.owner_id === userId) ||
- room.write_visibility === "public"
- );
-}
-
-/** Whether a user may open an owned resource (a room, a package), as the
- * server decides it (`can(..., "read", ...)`): its owner, a tenant admin, or
- * anyone when it is publicly readable. */
-export function canReadResource(
- resource: Pick<VisibilityPair, "read_visibility"> & { owner_id: string | null },
- userId: string | null | undefined,
- canAdminTenant: boolean,
-): boolean {
- if (!userId) return false;
- return (
- canAdminTenant ||
- (resource.owner_id !== null && resource.owner_id === userId) ||
- resource.read_visibility === "public"
- );
-}
diff --git a/gateway/src/pages/rooms/roomWriteControls.test.tsx b/gateway/src/pages/rooms/roomWriteControls.test.tsx
index b626e61ff..d19f95785 100644
--- a/gateway/src/pages/rooms/roomWriteControls.test.tsx
+++ b/gateway/src/pages/rooms/roomWriteControls.test.tsx
@@ -1,22 +1,17 @@
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { useAuth } from "../../data/AuthContext";
+import { afterEach, describe, expect, it, vi } from "vitest";
import RoomLinkedRoomsSection from "./RoomLinkedRoomsSection";
import RoomResourcesSection from "./RoomResourcesSection";
// The room's linked rooms and resources change only for someone with write
// access to the room, so their controls show only to them. A linked room or
-// package opens only for someone who may read it.
+// package opens only for someone the server says may read it.
const navigate = vi.fn();
vi.mock("react-router", () => ({
useNavigate: () => navigate,
}));
-vi.mock("../../data/AuthContext", () => ({
- useAuth: vi.fn(),
-}));
-
const result = <T,>(data: T) => ({
data,
loading: false,
@@ -68,6 +63,7 @@ vi.mock("../../data/hooks", () => ({
description: "",
owner_id: "someone",
read_visibility: "public",
+ can_read: true,
},
{
id: "pkg2",
@@ -75,6 +71,7 @@ vi.mock("../../data/hooks", () => ({
description: "",
owner_id: "someone",
read_visibility: "private",
+ can_read: false,
},
{
id: "pkg3",
@@ -82,18 +79,12 @@ vi.mock("../../data/hooks", () => ({
description: "",
owner_id: "u1",
read_visibility: "private",
+ can_read: true,
},
]),
usePackages: () => result([]),
}));
-beforeEach(() => {
- vi.mocked(useAuth).mockReturnValue({
- user: { id: "u1" },
- canAdminTenant: false,
- } as unknown as ReturnType<typeof useAuth>);
-});
-
afterEach(() => {
cleanup();
navigate.mockReset();
@@ -157,14 +148,4 @@ describe("linked rooms and attached packages", () => {
expect(screen.getByText("secret-kit")).toBeTruthy();
});
- it("all open for an admin", () => {
- vi.mocked(useAuth).mockReturnValue({
- user: { id: "u2" },
- canAdminTenant: true,
- } as unknown as ReturnType<typeof useAuth>);
- renderSections(false);
-
- fireEvent.click(screen.getByTestId("room-package-pkg2"));
- expect(navigate).toHaveBeenLastCalledWith("/resources/packages/pkg2");
- });
});