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
Read a room's settings in Console and add the calls to change them
Simon Flacka8144df009bc
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.rooms.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.rooms.test.tsnew file mode 100644index 000000000..743a5d1e3--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.rooms.test.ts@@ -0,0 +1,245 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const getSessionCookie = vi.hoisted(() => vi.fn());++vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({+ managedServerHostBlocked: () => null,+ managedServerStoppedPhase: () => null,+ noteManagedServerUnanswered: () => undefined,+}));+vi.mock('./servers-store', () => ({ getSessionCookie, setSessionCookie: vi.fn() }));+vi.mock('./auth', () => ({+ refreshSession: vi.fn(),+ reauthenticateManagedServer: vi.fn(),+ extractAuthCookie: () => null,+}));+vi.mock('./console-identity', () => ({ consoleIdentityHeaders: async () => ({}) }));++const {+ addRoomUsers,+ createRoomRole,+ deleteRoomRole,+ fetchArchivedRooms,+ fetchBridgeUserNames,+ fetchRoomDetail,+ setRoomAgentJoinEvents,+ setRoomArchived,+ setRoomGroup,+ updateRoom,+ updateRoomRole,+} = await import('./gateway-client');++const SERVER = {+ id: 'srv-1',+ name: 'S',+ url: 'https://switch.example.com',+ dashboardUrl: null,+ managed: false,+} as never;++function makeJwt(secondsFromNow: number): string {+ const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url');+ const exp = Math.floor(Date.now() / 1000) + secondsFromNow;+ const payload = Buffer.from(JSON.stringify({ sub: 'u1', exp })).toString('base64url');+ return `${header}.${payload}.sig`;+}++function jsonResponse(body: unknown): Response {+ return {+ status: 200,+ ok: true,+ json: async () => body,+ headers: { get: () => null, getSetCookie: () => [] },+ text: async () => JSON.stringify(body),+ } as unknown as Response;+}++/** A gateway `RoomDetail` with every field this client reads. */+const ROOM = {+ id: 'room-1',+ name: 'design-review',+ description: 'Where we review designs',+ channel_type: 'channel_public',+ agent_count: 2,+ bridge_display_name: 'Acme Slack',+ bridge_type: 'slack',+ bridge_id: 'bridge-1',+ owner_id: 'u1',+ owner_name: 'Ada',+ read_visibility: 'public',+ write_visibility: 'private',+ group_id: 'g-1',+ group_name: 'Design',+ archived: false,+ archived_at: null,+ created_at: '2026-10-01T09:00:00+00:00',+ instructions: 'Be kind',+ agent_ids: ['a-1', 'a-2'],+ agent_statuses: { 'a-1': 'live', 'a-2': 'no_session' },+ roles: [{ name: 'reviewer', instructions: 'Review', exclusive: true, held_by: ['bot-a'] }],+ join_event_listeners: ['a-1'],+ connected_user_names: ['ada', 'bob'],+ external_channel_id: 'C123',+ transport_room_id: '!abc:switch.local',+ linked_channel_name: 'design-review',+};++const fetchMock = vi.fn(async (_url: string, _init?: RequestInit) => jsonResponse(ROOM));++function lastCall(): { url: string; method: string; body: unknown } {+ const [url, init] = fetchMock.mock.calls.at(-1) as [string, RequestInit | undefined];+ return {+ url,+ method: init?.method ?? 'GET',+ body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,+ };+}++beforeEach(() => {+ vi.clearAllMocks();+ getSessionCookie.mockResolvedValue(makeJwt(2 * 60 * 60));+ vi.stubGlobal('fetch', fetchMock);+ fetchMock.mockImplementation(async () => jsonResponse(ROOM));+});++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('fetchRoomDetail', () => {+ it('maps the settings the room page shows', async () => {+ const room = await fetchRoomDetail(SERVER, 'room-1');+ expect(room).toMatchObject({+ readVisibility: 'public',+ writeVisibility: 'private',+ groupId: 'g-1',+ groupName: 'Design',+ ownerName: 'Ada',+ bridgeId: 'bridge-1',+ agentStatuses: { 'a-1': 'live', 'a-2': 'no_session' },+ roles: [{ name: 'reviewer', instructions: 'Review', exclusive: true, heldBy: ['bot-a'] }],+ joinEventListeners: ['a-1'],+ externalChannelId: 'C123',+ transportRoomId: '!abc:switch.local',+ archivedAt: null,+ });+ });++ it('reads a server that predates the settings as an open, ungrouped room', async () => {+ const {+ read_visibility: _r,+ write_visibility: _w,+ group_id: _g,+ roles: _roles,+ agent_statuses: _s,+ ...old+ } = ROOM;+ fetchMock.mockImplementation(async () => jsonResponse(old));+ const room = await fetchRoomDetail(SERVER, 'room-1');+ expect(room).toMatchObject({+ readVisibility: 'public',+ writeVisibility: 'public',+ groupId: null,+ roles: [],+ agentStatuses: {},+ });+ });+});++describe('room writes', () => {+ it('sends a visibility change in the server’s field names', async () => {+ await updateRoom(SERVER, 'room-1', { readVisibility: 'private', writeVisibility: 'private' });+ expect(lastCall()).toMatchObject({+ method: 'PATCH',+ body: { read_visibility: 'private', write_visibility: 'private' },+ });+ expect(lastCall().url).toMatch(/\/rooms\/room-1$/);+ });++ it('leaves visibility out of a plain description change', async () => {+ await updateRoom(SERVER, 'room-1', { description: 'x' });+ expect(lastCall().body).toEqual({ description: 'x' });+ });++ it('files a room under a group, and takes it out with null', async () => {+ await setRoomGroup(SERVER, 'room-1', 'g-2');+ expect(lastCall()).toMatchObject({ method: 'PUT', body: { group_id: 'g-2' } });+ expect(lastCall().url).toMatch(/\/rooms\/room-1\/group$/);+ await setRoomGroup(SERVER, 'room-1', null);+ expect(lastCall().body).toEqual({ group_id: null });+ });++ it('toggles one agent’s join events', async () => {+ await setRoomAgentJoinEvents(SERVER, 'room-1', 'a-2', true);+ expect(lastCall()).toMatchObject({ method: 'PATCH', body: { receives_join_events: true } });+ expect(lastCall().url).toMatch(/\/rooms\/room-1\/agents\/a-2$/);+ });++ it('invites people by username', async () => {+ await addRoomUsers(SERVER, 'room-1', ['carol']);+ expect(lastCall()).toMatchObject({ method: 'POST', body: { user_names: ['carol'] } });+ expect(lastCall().url).toMatch(/\/rooms\/room-1\/users$/);+ });++ it('archives and unarchives through their own routes', async () => {+ await setRoomArchived(SERVER, 'room-1', true);+ expect(lastCall()).toMatchObject({ method: 'POST' });+ expect(lastCall().url).toMatch(/\/rooms\/room-1\/archive$/);+ await setRoomArchived(SERVER, 'room-1', false);+ expect(lastCall().url).toMatch(/\/rooms\/room-1\/unarchive$/);+ });+});++describe('room roles', () => {+ const ROLES = [{ name: 'reviewer', instructions: 'Review', exclusive: false, held_by: [] }];++ it('creates, edits and deletes a role, reading back the room’s roles each time', async () => {+ fetchMock.mockImplementation(async () => jsonResponse(ROLES));+ await expect(+ createRoomRole(SERVER, 'room-1', {+ name: 'reviewer',+ instructions: 'Review',+ exclusive: false,+ })+ ).resolves.toEqual([+ { name: 'reviewer', instructions: 'Review', exclusive: false, heldBy: [] },+ ]);+ expect(lastCall()).toMatchObject({+ method: 'POST',+ body: { name: 'reviewer', instructions: 'Review', exclusive: false },+ });++ await updateRoomRole(SERVER, 'room-1', 'code reviewer', { exclusive: true });+ expect(lastCall()).toMatchObject({ method: 'PATCH', body: { exclusive: true } });+ expect(lastCall().url).toMatch(/\/rooms\/room-1\/roles\/code%20reviewer$/);++ await deleteRoomRole(SERVER, 'room-1', 'reviewer');+ expect(lastCall()).toMatchObject({ method: 'DELETE' });+ });+});++describe('room lists', () => {+ it('asks for archived rooms and keeps only those', async () => {+ fetchMock.mockImplementation(async () =>+ jsonResponse([+ { ...ROOM, id: 'live', archived: false },+ { ...ROOM, id: 'old', archived: true },+ ])+ );+ const rooms = await fetchArchivedRooms(SERVER);+ expect(lastCall().url).toMatch(/\/rooms\?include_archived=true$/);+ expect(rooms.map((room) => room.id)).toEqual(['old']);+ });++ it('lists a bridge’s usernames once each, sorted', async () => {+ fetchMock.mockImplementation(async () =>+ jsonResponse([+ { id: '1', external_username: 'carol' },+ { id: '2', external_username: 'ada' },+ { id: '3', external_username: 'carol' },+ ])+ );+ await expect(fetchBridgeUserNames(SERVER, 'bridge-1')).resolves.toEqual(['ada', 'carol']);+ expect(lastCall().url).toMatch(/\/collaborations\/bridge-1\/users$/);+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.tsindex ff49a030f..f538c2764 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts@@ -96,6 +96,8 @@ import {type RemoteRoomRole,type RemoteRoomSummary,type RemoveTeamsTeamResult,+ type RoomRoleInput,+ type RoomVisibility,type RetireOutcome,type SwitchApiKey,type CreatedRegistrationKey,@@ -3209,18 +3211,75 @@ export async function fetchRoomRoles(const res = await gatewayFetch(server, `/rooms/${encodeURIComponent(roomId)}/roles`, {authenticated: true,});- const json = (await res.json()) as Array<{- name: string;- instructions: string;- exclusive: boolean;- held_by?: string[];- }>;- return json.map((r) => ({+ return ((await res.json()) as RoomRoleJson[]).map(mapRoomRole);+}++/** The gateway `RoomRoleDetail` wire shape. */+type RoomRoleJson = {+ name: string;+ instructions: string;+ exclusive: boolean;+ held_by?: string[];+};++function mapRoomRole(r: RoomRoleJson): RemoteRoomRole {+ return {name: r.name,instructions: r.instructions,exclusive: r.exclusive,heldBy: r.held_by ?? [],- }));+ };+}++/**+ * Define a role in a room (`POST /rooms/{id}/roles`). Requires write access;+ * a name already taken in the room is refused. Resolves to the room's roles as+ * they now stand.+ */+export async function createRoomRole(+ server: SwitchServer,+ roomId: string,+ role: RoomRoleInput+): Promise<RemoteRoomRole[]> {+ const res = await gatewayFetch(server, `/rooms/${encodeURIComponent(roomId)}/roles`, {+ authenticated: true,+ method: 'POST',+ body: role,+ });+ return ((await res.json()) as RoomRoleJson[]).map(mapRoomRole);+}++/**+ * Change a role's instructions or exclusivity (`PATCH /rooms/{id}/roles/{name}`).+ * The name cannot change. An agent already holding the role keeps the+ * instructions it was given until it takes the role again.+ */+export async function updateRoomRole(+ server: SwitchServer,+ roomId: string,+ name: string,+ changes: { instructions?: string; exclusive?: boolean }+): Promise<RemoteRoomRole[]> {+ const res = await gatewayFetch(+ server,+ `/rooms/${encodeURIComponent(roomId)}/roles/${encodeURIComponent(name)}`,+ { authenticated: true, method: 'PATCH', body: changes }+ );+ return ((await res.json()) as RoomRoleJson[]).map(mapRoomRole);+}++/** Remove a role from a room, and any agent's hold on it (`DELETE /rooms/{id}/roles/{name}`). */+export async function deleteRoomRole(+ server: SwitchServer,+ roomId: string,+ name: string+): Promise<RemoteRoomRole[]> {+ const res = await gatewayFetch(+ server,+ `/rooms/${encodeURIComponent(roomId)}/roles/${encodeURIComponent(name)}`,+ { authenticated: true, method: 'DELETE' }+ );+ return ((await res.json()) as RoomRoleJson[]).map(mapRoomRole);}/** The gateway `RoomSummary` wire shape. `RoomDetail` (returned by create) is a@@ -3275,8 +3334,27 @@ type RoomDetailJson = RoomSummaryJson & {* "no channel", so the delete dialog can say it does not know. */channel_on_delete?: ChannelRetirement | null;linked_channel_name?: string | null;+ read_visibility?: string;+ write_visibility?: string;+ group_id?: string | null;+ group_name?: string | null;+ owner_name?: string | null;+ bridge_id?: string | null;+ agent_statuses?: Record<string, string>;+ roles?: RoomRoleJson[];+ join_event_listeners?: string[];+ external_channel_id?: string | null;+ transport_room_id?: string | null;+ archived_at?: string | null;};+/** The server's visibility words; anything else reads as private, the narrower of the two. */+function visibilityOf(value: string | undefined): RoomVisibility {+ // Absent only from a server that predates the setting, where every room was open.+ if (value === undefined) return 'public';+ return value === 'public' ? 'public' : 'private';+}+function mapRoomDetail(r: RoomDetailJson): RemoteRoomDetail {return {...mapRoomSummary(r),@@ -3285,6 +3363,18 @@ function mapRoomDetail(r: RoomDetailJson): RemoteRoomDetail {connectedUserNames: r.connected_user_names ?? [],channelOnDelete: r.channel_on_delete,linkedChannelName: r.linked_channel_name ?? null,+ readVisibility: visibilityOf(r.read_visibility),+ writeVisibility: visibilityOf(r.write_visibility),+ groupId: r.group_id ?? null,+ groupName: r.group_name ?? null,+ ownerName: r.owner_name ?? null,+ bridgeId: r.bridge_id ?? null,+ agentStatuses: r.agent_statuses ?? {},+ roles: (r.roles ?? []).map(mapRoomRole),+ joinEventListeners: r.join_event_listeners ?? [],+ externalChannelId: r.external_channel_id ?? null,+ transportRoomId: r.transport_room_id ?? null,+ archivedAt: r.archived_at ?? null,};}@@ -3336,16 +3426,125 @@ export async function fetchRoomAgentIds(server: SwitchServer, roomId: string): Pexport async function updateRoom(server: SwitchServer,roomId: string,- changes: { name?: string; description?: string; instructions?: string }+ changes: {+ name?: string;+ description?: string;+ instructions?: string;+ readVisibility?: RoomVisibility;+ writeVisibility?: RoomVisibility;+ }): Promise<RemoteRoomDetail> {+ const { readVisibility, writeVisibility, ...fields } = changes;const res = await gatewayFetch(server, `/rooms/${encodeURIComponent(roomId)}`, {authenticated: true,method: 'PATCH',- body: changes,+ body: {+ ...fields,+ ...(readVisibility !== undefined ? { read_visibility: readVisibility } : {}),+ ...(writeVisibility !== undefined ? { write_visibility: writeVisibility } : {}),+ },});return mapRoomDetail((await res.json()) as RoomDetailJson);}+/**+ * File a room under a group, or take it out of one with null+ * (`PUT /rooms/{id}/group`). Requires write access; a group that does not exist+ * is refused.+ */+export async function setRoomGroup(+ server: SwitchServer,+ roomId: string,+ groupId: string | null+): Promise<RemoteRoomDetail> {+ const res = await gatewayFetch(server, `/rooms/${encodeURIComponent(roomId)}/group`, {+ authenticated: true,+ method: 'PUT',+ body: { group_id: groupId },+ });+ return mapRoomDetail((await res.json()) as RoomDetailJson);+}++/**+ * Whether one member agent is told when someone joins the room+ * (`PATCH /rooms/{id}/agents/{agentId}`). Requires write access; an agent not+ * in the room is refused.+ */+export async function setRoomAgentJoinEvents(+ server: SwitchServer,+ roomId: string,+ agentId: string,+ receivesJoinEvents: boolean+): Promise<RemoteRoomDetail> {+ const res = await gatewayFetch(+ server,+ `/rooms/${encodeURIComponent(roomId)}/agents/${encodeURIComponent(agentId)}`,+ { authenticated: true, method: 'PATCH', body: { receives_join_events: receivesJoinEvents } }+ );+ return mapRoomDetail((await res.json()) as RoomDetailJson);+}++/**+ * Invite people to a bridged room by their messaging-app usernames+ * (`POST /rooms/{id}/users`). Requires write access, and a room whose bridge is+ * running. The server does not say who it could not add, so the caller compares+ * the names it asked for with the room's people afterwards.+ */+export async function addRoomUsers(+ server: SwitchServer,+ roomId: string,+ userNames: string[]+): Promise<RemoteRoomDetail> {+ const res = await gatewayFetch(server, `/rooms/${encodeURIComponent(roomId)}/users`, {+ authenticated: true,+ method: 'POST',+ body: { user_names: userNames },+ });+ return mapRoomDetail((await res.json()) as RoomDetailJson);+}++/**+ * Archive a room, or bring it back (`POST /rooms/{id}/archive|unarchive`).+ * Requires write access. An archived room drops out of room lists and agents+ * can no longer join it; nothing in it is deleted.+ */+export async function setRoomArchived(+ server: SwitchServer,+ roomId: string,+ archived: boolean+): Promise<RemoteRoomDetail> {+ const res = await gatewayFetch(+ server,+ `/rooms/${encodeURIComponent(roomId)}/${archived ? 'archive' : 'unarchive'}`,+ { authenticated: true, method: 'POST' }+ );+ return mapRoomDetail((await res.json()) as RoomDetailJson);+}++/** The archived rooms the signed-in user can see (`GET /rooms?include_archived=true`, archived only). */+export async function fetchArchivedRooms(server: SwitchServer): Promise<RemoteRoomSummary[]> {+ const res = await gatewayFetch(server, '/rooms?include_archived=true', { authenticated: true });+ const json = (await res.json()) as RoomSummaryJson[];+ return json.filter((room) => room.archived).map(mapRoomSummary);+}++/**+ * The messaging-app usernames Switch knows on one bridge+ * (`GET /collaborations/{id}/users`) — the people a bridged room can be given.+ */+export async function fetchBridgeUserNames(+ server: SwitchServer,+ bridgeId: string+): Promise<string[]> {+ const res = await gatewayFetch(server, `/collaborations/${encodeURIComponent(bridgeId)}/users`, {+ authenticated: true,+ });+ const users = (await res.json()) as ExternalUserSummaryJson[];+ return [...new Set(users.map((user) => user.external_username))].sort((a, b) =>+ a.localeCompare(b)+ );+}+/*** Add agents to an existing room (`POST /rooms/{id}/agents`). Requires write* access to the room. Agents already in the room are ignored server-side, sodiff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.tsindex 5fd5abe29..6d80a723a 100644--- a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts@@ -11,6 +11,15 @@ import {import {addBridgeTeam,addRoomAgents,+ addRoomUsers,+ createRoomRole,+ deleteRoomRole,+ fetchArchivedRooms,+ fetchBridgeUserNames,+ setRoomAgentJoinEvents,+ setRoomArchived,+ setRoomGroup,+ updateRoomRole,agentExistsOnServer,checkSlackTokens,fetchSlackOwnAppSetup,@@ -157,6 +166,7 @@ import type {RemoteRoomSummary,RemoveTeamsTeamResult,RetireOutcome,+ RoomRoleInput,SwitchServer,TeamsTeamsResult,UpdateBridgeParams,@@ -917,9 +927,96 @@ export const workspacesController = createRPCController({name: params.name,description: params.description,instructions: params.instructions,+ readVisibility: params.readVisibility,+ writeVisibility: params.writeVisibility,})),+ /** File a room under a group, or take it out of one (null). */+ setRoomGroup: (params: {+ workspaceId: string;+ roomId: string;+ groupId: string | null;+ }): Promise<RemoteRoomDetail> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ setRoomGroup(server, params.roomId, params.groupId)+ ),++ /** Define a role in a room; resolves to the room's roles as they now stand. */+ createRoomRole: (params: {+ workspaceId: string;+ roomId: string;+ role: RoomRoleInput;+ }): Promise<RemoteRoomRole[]> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ createRoomRole(server, params.roomId, params.role)+ ),++ /** Change a role's instructions or exclusivity; its name is fixed. */+ updateRoomRole: (params: {+ workspaceId: string;+ roomId: string;+ name: string;+ instructions?: string;+ exclusive?: boolean;+ }): Promise<RemoteRoomRole[]> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ updateRoomRole(server, params.roomId, params.name, {+ instructions: params.instructions,+ exclusive: params.exclusive,+ })+ ),++ deleteRoomRole: (params: {+ workspaceId: string;+ roomId: string;+ name: string;+ }): Promise<RemoteRoomRole[]> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ deleteRoomRole(server, params.roomId, params.name)+ ),++ /** Whether one member agent is told when someone joins the room. */+ setRoomAgentJoinEvents: (params: {+ workspaceId: string;+ roomId: string;+ agentId: string;+ receivesJoinEvents: boolean;+ }): Promise<RemoteRoomDetail> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ setRoomAgentJoinEvents(server, params.roomId, params.agentId, params.receivesJoinEvents)+ ),++ /** Invite people to a bridged room by their messaging-app usernames. */+ addRoomUsers: (params: {+ workspaceId: string;+ roomId: string;+ userNames: string[];+ }): Promise<RemoteRoomDetail> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ addRoomUsers(server, params.roomId, params.userNames)+ ),++ /** Archive a room, or bring it back. */+ setRoomArchived: (params: {+ workspaceId: string;+ roomId: string;+ archived: boolean;+ }): Promise<RemoteRoomDetail> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ setRoomArchived(server, params.roomId, params.archived)+ ),++ /** The archived rooms the signed-in user can see. */+ listArchivedRooms: (params: { workspaceId: string }): Promise<RemoteRoomSummary[]> =>+ withWorkspaceSession(params.workspaceId, (server) => fetchArchivedRooms(server)),++ /** The messaging-app usernames Switch knows on one bridge, for inviting people to a room. */+ listBridgeUserNames: (params: { workspaceId: string; bridgeId: string }): Promise<string[]> =>+ withWorkspaceSession(params.workspaceId, (server) =>+ fetchBridgeUserNames(server, params.bridgeId)+ ),+/*** Add agents to a room. Failures propagate as-is: the caller shows the* gateway's own words (e.g. an agent whose server-side client is not running,diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-permissions.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-permissions.test.tsnew file mode 100644index 000000000..f75c30932--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-permissions.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from 'vitest';+import { roomPermissionsFor } from './room-permissions';++const ME = { userId: 'u-1', isAdmin: false };++describe('roomPermissionsFor', () => {+ it('lets the owner manage and write', () => {+ expect(roomPermissionsFor({ ownerId: 'u-1', writeVisibility: 'private' }, ME)).toEqual({+ canWrite: true,+ canManage: true,+ });+ });++ it('lets an admin manage someone else’s private room', () => {+ expect(+ roomPermissionsFor(+ { ownerId: 'u-2', writeVisibility: 'private' },+ { userId: 'u-1', isAdmin: true }+ )+ ).toEqual({ canWrite: true, canManage: true });+ });++ it('lets anyone write to a publicly writable room, but not manage it', () => {+ expect(roomPermissionsFor({ ownerId: 'u-2', writeVisibility: 'public' }, ME)).toEqual({+ canWrite: true,+ canManage: false,+ });+ });++ it('gives a non-owner nothing on a privately writable room', () => {+ expect(roomPermissionsFor({ ownerId: 'u-2', writeVisibility: 'private' }, ME)).toEqual({+ canWrite: false,+ canManage: false,+ });+ });++ it('treats a room with no owner as nobody’s to manage', () => {+ expect(roomPermissionsFor({ ownerId: null, writeVisibility: 'private' }, ME).canManage).toBe(+ false+ );+ });++ it('reads an unknown write access as public, as rooms were before the setting', () => {+ expect(roomPermissionsFor({ ownerId: 'u-2' }, ME).canWrite).toBe(true);+ });++ it('gives an unknown viewer nothing', () => {+ expect(+ roomPermissionsFor(+ { ownerId: 'u-1', writeVisibility: 'public' },+ { userId: null, isAdmin: true }+ )+ ).toEqual({ canWrite: false, canManage: false });+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-permissions.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-permissions.tsnew file mode 100644index 000000000..659864da1--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-permissions.ts@@ -0,0 +1,25 @@+import type { RoomVisibility } from '@shared/core/switch-servers/switch-servers';++/**+ * What someone may do with a room. `canManage` is the owner's and the+ * workspace admins' alone: deleting the room, changing who may see it, naming+ * it after its channel. `canWrite` also covers anyone at all when the room's+ * write access is public: its description and instructions, who is in it, its+ * roles, its group, archiving it.+ */+export type RoomPermissions = { canWrite: boolean; canManage: boolean };++/**+ * The gateway's room rule (`authz.can`), worked out for one viewer. A room+ * whose write access is not known — a server that predates the setting — is+ * treated as public, which is what every room was before it existed.+ */+export function roomPermissionsFor(+ room: { ownerId: string | null; writeVisibility?: RoomVisibility },+ viewer: { userId: string | null; isAdmin: boolean }+): RoomPermissions {+ if (viewer.userId === null) return { canWrite: false, canManage: false };+ const canManage = viewer.isAdmin || (room.ownerId !== null && room.ownerId === viewer.userId);+ const canWrite = canManage || (room.writeVisibility ?? 'public') === 'public';+ return { canWrite, canManage };+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.tsindex 78c69d2d8..18c6ff949 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts@@ -7,8 +7,11 @@ import {type RemoteAgentRoom,type RemoteRoomSummary,type RetireOutcome,+ type RoomVisibility,} from '@shared/core/switch-servers/switch-servers';+import { administersWorkspace } from '@shared/core/workspaces/workspaces';import { UNBRIDGED_FILTER_VALUE } from '@shared/view-state';+import { type RoomPermissions, roomPermissionsFor } from './room-permissions';import { serverAvailability } from './server-availability';import { switchServersStore } from './switch-servers-store';@@ -231,20 +234,32 @@ export class SwitchRoomsStore {}/**- * Whether the signed-in user may delete a room: they own it, or they are an- * admin on the server hosting its workspace.+ * What the signed-in user may do with a room, by the gateway's own rules:+ * its owner and the workspace's admins manage it — delete it, change who may+ * see it, name it after its channel — and anyone may also write to a room+ * whose write access is public.*- * This mirrors the gateway's own rule so the action is not offered where it- * would only be refused. It is not the check that protects anything — the- * server's is — and where ownership is unknown the answer is no, since- * showing a delete that fails is worse than not showing one.+ * This mirrors the server so actions are not offered where they would only be+ * refused. It is not the check that protects anything — the server's is — and+ * where the viewer is unknown the answer is no, since showing an action that+ * fails is worse than not showing one.*/- canDeleteRoom(workspaceId: string, room: RemoteRoomSummary): boolean {+ roomPermissions(+ workspaceId: string,+ room: { ownerId: string | null; writeVisibility?: RoomVisibility }+ ): RoomPermissions {const serverId = workspacesStore.serverIdFor(workspaceId);- if (!serverId) return false;- const user = switchServersStore.statusFor(serverId)?.user ?? null;- if (!user) return false;- return room.ownerId === user.id || user.role === 'admin';+ const user = serverId ? (switchServersStore.statusFor(serverId)?.user ?? null) : null;+ const workspace = workspacesStore.workspaces.find((each) => each.id === workspaceId) ?? null;+ return roomPermissionsFor(room, {+ userId: user?.id ?? null,+ isAdmin: user?.role === 'admin' || (workspace !== null && administersWorkspace(workspace)),+ });+ }++ /** Whether the signed-in user may delete a room (see `roomPermissions`). */+ canDeleteRoom(workspaceId: string, room: RemoteRoomSummary): boolean {+ return this.roomPermissions(workspaceId, room).canManage;}/**diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.tsindex d7e5f8bd0..3c0bc8509 100644--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts@@ -385,8 +385,62 @@ export type RemoteRoomDetail = RemoteRoomSummary & {channelOnDelete?: ChannelRetirement | null;/** The name of the platform channel the room is linked to, as Switch last saw it; null when it has not. */linkedChannelName: string | null;+ /** Who may read the room and who may write to it (see `roomAccessOf`). */+ readVisibility: RoomVisibility;+ writeVisibility: RoomVisibility;+ /** The group the room is filed under, or null for a standalone room. */+ groupId: string | null;+ groupName: string | null;+ /** The owner's display name, or null when the room has no owner. */+ ownerName: string | null;+ /** The bridge the room is linked through; null for a room with no messaging app. */+ bridgeId: string | null;+ /** Each member agent's presence in this room, by agent id: `live`,+ * `awaiting_manual_poll`, `disconnected` or `no_session`. An agent the server+ * says nothing about is missing rather than guessed at. */+ agentStatuses: Record<string, string>;+ /** The room's assumable roles, with who holds each. */+ roles: RemoteRoomRole[];+ /** Ids of the member agents told when someone joins the room. */+ joinEventListeners: string[];+ /** The platform's own id for the linked channel; null when unbridged. */+ externalChannelId: string | null;+ /** The room's id on Switch's internal message bus. */+ transportRoomId: string | null;+ /** When the room was archived, or null while it is in use. */+ archivedAt: string | null;};+/** `public` lets every member of the workspace in; `private` only the owner and admins. */+export type RoomVisibility = 'public' | 'private';++/**+ * A room's access, as the two visibility settings it is made of combine. The+ * gateway offers the same three: anyone may post, anyone may read but only the+ * owner posts, or the room is the owner's alone. A private room that is+ * publicly writable is refused by the server, so it has no name here.+ */+export type RoomAccess = 'public' | 'read_only' | 'private';++export function roomAccessOf(read: RoomVisibility, write: RoomVisibility): RoomAccess {+ if (read === 'private') return 'private';+ return write === 'public' ? 'public' : 'read_only';+}++export function visibilityForAccess(access: RoomAccess): {+ readVisibility: RoomVisibility;+ writeVisibility: RoomVisibility;+} {+ switch (access) {+ case 'public':+ return { readVisibility: 'public', writeVisibility: 'public' };+ case 'read_only':+ return { readVisibility: 'public', writeVisibility: 'private' };+ case 'private':+ return { readVisibility: 'private', writeVisibility: 'private' };+ }+}+/** What deleting a room does to its platform channel when asked to retire it* and all goes to plan (mirrors the gateway's `ChannelRetirement`): archived on Slack and* Mattermost, deleted on Discord, left by the bot on Telegram, and kept on@@ -412,8 +466,14 @@ export type UpdateRoomParams = {name?: string;description?: string;instructions?: string;+ /** Changing either is for the room's owner or an admin; the server refuses anyone else. */+ readVisibility?: RoomVisibility;+ writeVisibility?: RoomVisibility;};+/** A role's own fields, as a room defines it. The name is fixed once made. */+export type RoomRoleInput = { name: string; instructions: string; exclusive: boolean };+/*** A room a specific agent belongs to, with that agent's presence there (mirrors* the gateway `AgentRoomMembership`). Drives the "connect to room" picker at