Skip to content

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

Room page: participants down the side, Chat · Resources · Configuration on top

Simon Flack6767e15d99cc
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.ts
index d9065e7e7..093638667 100644
--- 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.ts
@@ -16,7 +16,14 @@ vi.mock('./auth', () => ({
vi.mock('./console-identity', () => ({ consoleIdentityHeaders: async () => ({}) }));
const {
+ addLinkedRoom,
addRoomUsers,
+ fetchLibrary,
+ fetchLinkedRooms,
+ fetchRoomDocument,
+ fetchRoomResources,
+ removeLinkedRoom,
+ setRoomResourceAttached,
createRoomRole,
deleteRoomRole,
fetchArchivedRooms,
@@ -258,3 +265,107 @@ describe('room lists', () => {
expect(lastCall().url).toMatch(/\/collaborations\/bridge-1\/users$/);
});
});
+
+describe('room resources', () => {
+ it('lists a room’s references with their type, links and the packages that brought them', async () => {
+ fetchMock.mockImplementation(async () =>
+ jsonResponse([
+ {
+ id: 'ref-1',
+ name: 'Repo',
+ description: 'The code',
+ type: 'github',
+ type_display_name: 'GitHub',
+ value: { urls: ['https://github.com/acme/repo', 7] },
+ packages: ['pkg-1'],
+ },
+ ])
+ );
+ const [ref] = await fetchRoomResources(SERVER, 'room-1', 'references');
+ expect(lastCall().url).toMatch(/\/gateway\/rooms\/room-1\/references$/);
+ expect(ref).toEqual({
+ id: 'ref-1',
+ kind: 'references',
+ name: 'Repo',
+ description: 'The code',
+ typeLabel: 'GitHub',
+ urls: ['https://github.com/acme/repo'],
+ roomScoped: false,
+ createdByAgentName: null,
+ packageIds: ['pkg-1'],
+ });
+ });
+
+ it('tells a document an agent wrote in the room from one in the library', async () => {
+ fetchMock.mockImplementation(async () =>
+ jsonResponse([
+ { id: 'd-1', name: 'Notes', description: '', scope: 'room', created_by_agent_name: 'bot' },
+ { id: 'd-2', name: 'Guide', description: '', scope: 'global' },
+ ])
+ );
+ const docs = await fetchRoomResources(SERVER, 'room-1', 'documents');
+ expect(docs.map((d) => [d.id, d.roomScoped, d.createdByAgentName])).toEqual([
+ ['d-1', true, 'bot'],
+ ['d-2', false, null],
+ ]);
+ });
+
+ it('offers only the library’s own documents for attaching', async () => {
+ fetchMock.mockImplementation(async () =>
+ jsonResponse([
+ { id: 'd-1', name: 'Notes', description: '', scope: 'room' },
+ { id: 'd-2', name: 'Guide', description: '', scope: 'global' },
+ ])
+ );
+ const library = await fetchLibrary(SERVER, 'documents');
+ expect(lastCall().url).toMatch(/\/gateway\/documents$/);
+ expect(library.map((d) => d.id)).toEqual(['d-2']);
+ });
+
+ it('attaches with a POST and detaches with a DELETE on the item’s room path', async () => {
+ fetchMock.mockImplementation(async () => jsonResponse({}));
+ await setRoomResourceAttached(SERVER, 'room-1', 'packages', 'pkg-1', true);
+ expect(lastCall()).toMatchObject({ method: 'POST' });
+ expect(lastCall().url).toMatch(/\/rooms\/room-1\/packages\/pkg-1$/);
+ await setRoomResourceAttached(SERVER, 'room-1', 'packages', 'pkg-1', false);
+ expect(lastCall()).toMatchObject({ method: 'DELETE' });
+ });
+
+ it('reads a document in full through the room', async () => {
+ fetchMock.mockImplementation(async () =>
+ jsonResponse({ id: 'd-1', name: 'Notes', description: 'Ours', content: '# Hi' })
+ );
+ expect(await fetchRoomDocument(SERVER, 'room-1', 'd-1')).toEqual({
+ id: 'd-1',
+ name: 'Notes',
+ description: 'Ours',
+ content: '# Hi',
+ });
+ expect(lastCall().url).toMatch(/\/rooms\/room-1\/documents\/d-1$/);
+ });
+});
+
+describe('linked rooms', () => {
+ const LINK = {
+ target_room_id: 'room-2',
+ target_room_name: 'support',
+ target_room_description: 'Help desk',
+ label: 'escalate to',
+ };
+
+ it('lists, adds and removes the rooms a room points at', async () => {
+ fetchMock.mockImplementation(async () => jsonResponse([LINK]));
+ expect(await fetchLinkedRooms(SERVER, 'room-1')).toEqual([
+ { roomId: 'room-2', name: 'support', description: 'Help desk', label: 'escalate to' },
+ ]);
+ fetchMock.mockImplementation(async () => jsonResponse(LINK));
+ await addLinkedRoom(SERVER, 'room-1', 'room-2', 'escalate to');
+ expect(lastCall()).toMatchObject({
+ method: 'POST',
+ body: { target_room_id: 'room-2', label: 'escalate to' },
+ });
+ await removeLinkedRoom(SERVER, 'room-1', 'room-2');
+ expect(lastCall()).toMatchObject({ method: 'DELETE' });
+ expect(lastCall().url).toMatch(/\/rooms\/room-1\/linked-rooms\/room-2$/);
+ });
+});
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.ts
index 31080b75c..dcfb27913 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
@@ -110,6 +110,10 @@ import {
type TrustSettings,
type UnconfirmedLink,
type UpdateTrustSettingsParams,
+ type LinkedRoom,
+ type RoomDocumentContent,
+ type RoomResource,
+ type RoomResourceKind,
} from '@shared/core/switch-servers/switch-servers';
import type {
Invitation,
@@ -5085,3 +5089,147 @@ export async function revokeManagementController(
method: 'DELETE',
});
}
+
+// ── Room resources ──────────────────────────────────────────────────────────
+
+type ResourceJson = {
+ id: string;
+ name: string;
+ description: string;
+ type?: string;
+ type_display_name?: string | null;
+ value?: { urls?: unknown };
+ packages?: string[];
+ scope?: 'global' | 'room';
+ created_by_agent_name?: string | null;
+};
+
+function mapResource(kind: RoomResourceKind, r: ResourceJson): RoomResource {
+ const urls = Array.isArray(r.value?.urls)
+ ? r.value.urls.filter((url): url is string => typeof url === 'string')
+ : [];
+ return {
+ id: r.id,
+ kind,
+ name: r.name,
+ description: r.description,
+ typeLabel: kind === 'references' ? (r.type_display_name ?? r.type ?? null) : null,
+ urls,
+ roomScoped: r.scope === 'room',
+ createdByAgentName: r.created_by_agent_name ?? null,
+ packageIds: r.packages ?? [],
+ };
+}
+
+/** What is attached to a room, of one kind (`GET /rooms/{id}/{kind}`). */
+export async function fetchRoomResources(
+ server: SwitchServer,
+ roomId: string,
+ kind: RoomResourceKind
+): Promise<RoomResource[]> {
+ const res = await gatewayFetch(server, `/rooms/${encodeURIComponent(roomId)}/${kind}`, {
+ authenticated: true,
+ });
+ return ((await res.json()) as ResourceJson[]).map((r) => mapResource(kind, r));
+}
+
+/** The library items of one kind the signed-in person may read, for attaching (`GET /{kind}`). */
+export async function fetchLibrary(
+ server: SwitchServer,
+ kind: RoomResourceKind
+): Promise<RoomResource[]> {
+ const res = await gatewayFetch(server, `/${kind}`, { authenticated: true });
+ return ((await res.json()) as ResourceJson[])
+ .map((r) => mapResource(kind, r))
+ .filter((r) => !r.roomScoped);
+}
+
+/** Attach a library item to a room, or detach it; detaching a room-scoped document deletes it. */
+export async function setRoomResourceAttached(
+ server: SwitchServer,
+ roomId: string,
+ kind: RoomResourceKind,
+ resourceId: string,
+ attached: boolean
+): Promise<void> {
+ await gatewayFetch(
+ server,
+ `/rooms/${encodeURIComponent(roomId)}/${kind}/${encodeURIComponent(resourceId)}`,
+ { authenticated: true, method: attached ? 'POST' : 'DELETE' }
+ );
+}
+
+/** A document read in full through the room it is attached to. */
+export async function fetchRoomDocument(
+ server: SwitchServer,
+ roomId: string,
+ documentId: string
+): Promise<RoomDocumentContent> {
+ const res = await gatewayFetch(
+ server,
+ `/rooms/${encodeURIComponent(roomId)}/documents/${encodeURIComponent(documentId)}`,
+ { authenticated: true }
+ );
+ const json = (await res.json()) as {
+ id: string;
+ name: string;
+ description: string;
+ content: string;
+ };
+ return { id: json.id, name: json.name, description: json.description, content: json.content };
+}
+
+type LinkedRoomJson = {
+ target_room_id: string;
+ target_room_name: string;
+ target_room_description: string;
+ label: string;
+};
+
+function mapLinkedRoom(r: LinkedRoomJson): LinkedRoom {
+ return {
+ roomId: r.target_room_id,
+ name: r.target_room_name,
+ description: r.target_room_description,
+ label: r.label,
+ };
+}
+
+/** The rooms this room points at (`GET /rooms/{id}/linked-rooms`). */
+export async function fetchLinkedRooms(
+ server: SwitchServer,
+ roomId: string
+): Promise<LinkedRoom[]> {
+ const res = await gatewayFetch(server, `/rooms/${encodeURIComponent(roomId)}/linked-rooms`, {
+ authenticated: true,
+ });
+ return ((await res.json()) as LinkedRoomJson[]).map(mapLinkedRoom);
+}
+
+/** Point this room at another, saying why. */
+export async function addLinkedRoom(
+ server: SwitchServer,
+ roomId: string,
+ targetRoomId: string,
+ label: string
+): Promise<LinkedRoom> {
+ const res = await gatewayFetch(server, `/rooms/${encodeURIComponent(roomId)}/linked-rooms`, {
+ authenticated: true,
+ method: 'POST',
+ body: { target_room_id: targetRoomId, label },
+ });
+ return mapLinkedRoom((await res.json()) as LinkedRoomJson);
+}
+
+/** Stop this room pointing at another. */
+export async function removeLinkedRoom(
+ server: SwitchServer,
+ roomId: string,
+ targetRoomId: string
+): Promise<void> {
+ await gatewayFetch(
+ server,
+ `/rooms/${encodeURIComponent(roomId)}/linked-rooms/${encodeURIComponent(targetRoomId)}`,
+ { authenticated: true, method: 'DELETE' }
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts
index 6d80a723a..2f65a38ba 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
@@ -89,6 +89,13 @@ import {
syncRoomName,
updateRoom,
updateTemplate,
+ addLinkedRoom,
+ fetchLibrary,
+ fetchLinkedRooms,
+ fetchRoomDocument,
+ fetchRoomResources,
+ removeLinkedRoom,
+ setRoomResourceAttached,
} from '@main/core/switch-servers/gateway-client';
import {
cancelLinkRequestOnServer,
@@ -173,6 +180,10 @@ import type {
UpdateBridgeResult,
SyncRoomNameParams,
UpdateRoomParams,
+ LinkedRoom,
+ RoomDocumentContent,
+ RoomResource,
+ RoomResourceKind,
} from '@shared/core/switch-servers/switch-servers';
import type { UiEntryPoint } from '@shared/core/telemetry/reporting';
import type { Workspace } from '@shared/core/workspaces/workspaces';
@@ -1012,6 +1023,73 @@ export const workspacesController = createRPCController({
withWorkspaceSession(params.workspaceId, (server) => fetchArchivedRooms(server)),
/** The messaging-app usernames Switch knows on one bridge, for inviting people to a room. */
+ /** What is attached to a room, of one kind. */
+ listRoomResources: (params: {
+ workspaceId: string;
+ roomId: string;
+ kind: RoomResourceKind;
+ }): Promise<RoomResource[]> =>
+ withWorkspaceSession(params.workspaceId, (server) =>
+ fetchRoomResources(server, params.roomId, params.kind)
+ ),
+
+ /** The library items of one kind the signed-in person may attach. */
+ listLibrary: (params: { workspaceId: string; kind: RoomResourceKind }): Promise<RoomResource[]> =>
+ withWorkspaceSession(params.workspaceId, (server) => fetchLibrary(server, params.kind)),
+
+ /** Attach a library item to a room or detach it. Refusals propagate in the gateway's words. */
+ setRoomResourceAttached: (params: {
+ workspaceId: string;
+ roomId: string;
+ kind: RoomResourceKind;
+ resourceId: string;
+ attached: boolean;
+ }): Promise<void> =>
+ withReachableWorkspaceSession(params.workspaceId, (server) =>
+ setRoomResourceAttached(
+ server,
+ params.roomId,
+ params.kind,
+ params.resourceId,
+ params.attached
+ )
+ ),
+
+ /** A document attached to a room, read in full. */
+ getRoomDocument: (params: {
+ workspaceId: string;
+ roomId: string;
+ documentId: string;
+ }): Promise<RoomDocumentContent> =>
+ withWorkspaceSession(params.workspaceId, (server) =>
+ fetchRoomDocument(server, params.roomId, params.documentId)
+ ),
+
+ /** The rooms a room points at. */
+ listLinkedRooms: (params: { workspaceId: string; roomId: string }): Promise<LinkedRoom[]> =>
+ withWorkspaceSession(params.workspaceId, (server) => fetchLinkedRooms(server, params.roomId)),
+
+ /** Point a room at another. */
+ addLinkedRoom: (params: {
+ workspaceId: string;
+ roomId: string;
+ targetRoomId: string;
+ label: string;
+ }): Promise<LinkedRoom> =>
+ withReachableWorkspaceSession(params.workspaceId, (server) =>
+ addLinkedRoom(server, params.roomId, params.targetRoomId, params.label)
+ ),
+
+ /** Stop a room pointing at another. */
+ removeLinkedRoom: (params: {
+ workspaceId: string;
+ roomId: string;
+ targetRoomId: string;
+ }): Promise<void> =>
+ withReachableWorkspaceSession(params.workspaceId, (server) =>
+ removeLinkedRoom(server, params.roomId, params.targetRoomId)
+ ),
+
listBridgeUserNames: (params: { workspaceId: string; bridgeId: string }): Promise<string[]> =>
withWorkspaceSession(params.workspaceId, (server) =>
fetchBridgeUserNames(server, params.bridgeId)
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-add-participants.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-add-participants.tsx
new file mode 100644
index 000000000..8e0e7e3b9
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-add-participants.tsx
@@ -0,0 +1,482 @@
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { Search, X } from 'lucide-react';
+import { observer } from 'mobx-react-lite';
+import { useState } from 'react';
+import { workspaceRosterQuery } from '@renderer/features/chats/chat-people';
+import { chatFailure } from '@renderer/features/chats/stores/chat-errors';
+import { chatsStore } from '@renderer/features/chats/stores/chats';
+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
+import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
+import { ParticipantPicker } from '@renderer/lib/components/participant-picker';
+import {
+ agentParticipant,
+ type Participant,
+ personParticipant,
+} from '@renderer/lib/components/participant-search';
+import { failureText } from '@renderer/lib/errors/describe-failure';
+import { rpc } from '@renderer/lib/ipc';
+import { useShowModal } from '@renderer/lib/modal/modal-provider';
+import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';
+import { ConfirmButton } from '@renderer/lib/ui/confirm-button';
+import {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupButton,
+ InputGroupInput,
+} from '@renderer/lib/ui/input-group';
+import { cn } from '@renderer/utils/utils';
+import { type ChatSummary } from '@shared/core/chats/chats';
+import { knownAgentTypeDisplayName } from '@shared/core/providers/agent-provider-registry';
+import { runsOnThisComputer } from '@shared/core/switch-servers/switch-servers';
+import type { RemoteRoomDetail } from '@shared/core/switch-servers/switch-servers';
+import { administersWorkspace } from '@shared/core/workspaces/workspaces';
+import { addableAgents, addablePeople } from './room-labels';
+import { agentKindFor, localAgentFor, PersonMark, roomDetailKey } from './room-participants';
+
+/*
+ * Adding agents and people to a room, as the room's participant column offers
+ * it: through the chats API for a Console chat, through the room for anything
+ * else.
+ */
+
+/** Adds a picked participant through the chats API: an agent to the chat, a person as a member. */
+export async function addToChat(
+ api: Pick<typeof rpc.chats, 'addAgent' | 'addMember'>,
+ serverId: string,
+ roomId: string,
+ participant: Participant
+): Promise<
+ | { kind: 'agent'; chat: ChatSummary }
+ | { kind: 'person'; members: Awaited<ReturnType<typeof rpc.chats.addMember>> }
+> {
+ if (participant.kind === 'agent')
+ return {
+ kind: 'agent',
+ chat: await api.addAgent({ serverId, roomId, agentId: participant.id }),
+ };
+ return {
+ kind: 'person',
+ members: await api.addMember({ serverId, roomId, userId: participant.id }),
+ };
+}
+
+const ADD_PARTICIPANT_INPUT = 'chat-add-participant';
+
+/** The Add button's label: how many it adds once there is more than one. */
+export function addLabel(count: number): string {
+ return count > 1 ? `Add ${count}` : 'Add';
+}
+
+/**
+ * Adds each pick in turn through the chats API, telling `onAdded` of each
+ * success; resolves to the picks the server refused, each with its reason.
+ * One at a time, so each add sees the chat as the one before left it.
+ */
+export async function addAllToChat(
+ api: Pick<typeof rpc.chats, 'addAgent' | 'addMember'>,
+ serverId: string,
+ roomId: string,
+ picks: Participant[],
+ onAdded: (added: Awaited<ReturnType<typeof addToChat>>) => void
+): Promise<{ participant: Participant; reason: string }[]> {
+ const failures: { participant: Participant; reason: string }[] = [];
+ for (const participant of picks) {
+ try {
+ onAdded(await addToChat(api, serverId, roomId, participant));
+ } catch (cause) {
+ failures.push({ participant, reason: chatFailure(cause).message });
+ }
+ }
+ return failures;
+}
+
+/**
+ * The New room dialog's participant field: picks gather as chips, and Add
+ * puts them all in the chat. It offers the agents the viewer may add and the
+ * people on the roster, never someone already in the chat.
+ */
+export const ChatAddParticipantPanel = observer(function ChatAddParticipantPanel({
+ serverId,
+ workspaceId,
+ chat,
+ memberIds,
+ onAddedPeople,
+}: {
+ serverId: string;
+ workspaceId: string | null;
+ chat: ChatSummary;
+ /** The people in the chat, the viewer included. */
+ memberIds: Set<string>;
+ onAddedPeople: (members: Awaited<ReturnType<typeof rpc.chats.addMember>>) => void;
+}) {
+ const tenantId = chatsStore.tenantId;
+ const agents = useWorkspaceAgents(workspaceId);
+ const roster = useQuery(workspaceRosterQuery(serverId, tenantId));
+ const allowed = useQuery({
+ // Keyed by the chat's agents, so adding or removing one asks again.
+ queryKey: [
+ 'chat-agent-candidates',
+ serverId,
+ workspaceId,
+ chat.roomId,
+ chat.agents.map((agent) => agent.id).join(','),
+ ],
+ queryFn: () => rpc.chats.agentCandidates({ serverId, roomId: chat.roomId }),
+ });
+ const [picked, setPicked] = useState<Participant[]>([]);
+ const [adding, setAdding] = useState(false);
+ const [refused, setRefused] = useState<string[]>([]);
+ const candidates = [
+ ...addableAgents(agents.data ?? [], allowed.data ?? []).map((agent) =>
+ agentParticipant(agent, knownAgentTypeDisplayName(agent.knownAgentType) ?? 'Agent')
+ ),
+ ...addablePeople(roster.data ?? [], memberIds).map(personParticipant),
+ ];
+
+ async function addAll() {
+ if (adding || picked.length === 0) return;
+ setAdding(true);
+ setRefused([]);
+ const failures = await addAllToChat(rpc.chats, serverId, chat.roomId, picked, (added) => {
+ if (added.kind === 'agent') chatsStore.add(serverId, added.chat);
+ else onAddedPeople(added.members);
+ });
+ setPicked(failures.map((failure) => failure.participant));
+ setRefused(
+ failures.map(({ participant, reason }) => `${participant.name} was not added — ${reason}`)
+ );
+ setAdding(false);
+ }
+
+ return (
+ <div className="flex flex-col gap-2 pt-1">
+ <div className="flex items-start gap-2">
+ <div className="min-w-0 flex-1">
+ <ParticipantPicker
+ inputId={ADD_PARTICIPANT_INPUT}
+ autoFocus={false}
+ busy={adding}
+ overlay
+ candidates={candidates}
+ picked={picked}
+ onChange={setPicked}
+ serverId={serverId}
+ loading={
+ agents.isPending || allowed.isPending || (tenantId !== null && roster.isPending)
+ }
+ />
+ </div>
+ <ConfirmButton
+ size="sm"
+ className="h-8 shrink-0"
+ disabled={picked.length === 0 || adding}
+ onClick={() => void addAll()}
+ >
+ {addLabel(picked.length)}
+ </ConfirmButton>
+ </div>
+ {refused.map((line) => (
+ <p key={line} className="text-xs text-destructive">
+ {line}
+ </p>
+ ))}
+ {(agents.isError || allowed.isError) && (
+ <p className="text-xs text-destructive">
+ {failureText(agents.error ?? allowed.error, 'Could not list the agents.')}
+ </p>
+ )}
+ {tenantId === null ? (
+ <p className="text-xs text-destructive">
+ This workspace has no tenant to list people from.
+ </p>
+ ) : (
+ roster.isError && (
+ <p className="text-xs text-destructive">
+ {failureText(roster.error, 'Could not list the people.')}
+ </p>
+ )
+ )}
+ <InviteHint workspaceId={workspaceId} canInvite={canInvite(serverId, workspaceId)} />
+ </div>
+ );
+});
+
+/** Whether the viewer may invite people to the workspace, as the workspace menu decides it. */
+function canInvite(serverId: string, workspaceId: string | null): boolean {
+ const workspace = workspacesStore.workspaces.find((each) => each.id === workspaceId) ?? null;
+ const server = switchServersStore.servers.find((each) => each.id === serverId) ?? null;
+ return (
+ workspace !== null &&
+ server !== null &&
+ administersWorkspace(workspace) &&
+ !runsOnThisComputer(server)
+ );
+}
+
+/** Where to go for someone the roster does not have yet. */
+export function InviteHint({
+ workspaceId,
+ canInvite,
+}: {
+ workspaceId: string | null;
+ canInvite: boolean;
+}) {
+ const showInvitePeopleModal = useShowModal('invitePeopleModal');
+ return (
+ <p className="px-1 text-xs text-foreground-muted">
+ Don&apos;t see someone?{' '}
+ {canInvite && workspaceId !== null ? (
+ <button
+ type="button"
+ className="cursor-pointer underline hover:text-foreground"
+ onClick={() => showInvitePeopleModal({ workspaceId })}
+ >
+ Invite them to the workspace
+ </button>
+ ) : (
+ 'Ask a workspace admin to invite them.'
+ )}
+ </p>
+ );
+}
+
+/**
+ * Invite people to a bridged room from the messaging app's users Switch knows.
+ * The server does not say who it could not add, so the names asked for are
+ * compared with the room's people afterwards and any missing are named.
+ */
+export const AddPeoplePanel = observer(function AddPeoplePanel({
+ workspaceId,
+ room,
+ bridgeId,
+}: {
+ workspaceId: string;
+ room: RemoteRoomDetail;
+ bridgeId: string;
+}) {
+ const queryClient = useQueryClient();
+ const [notAdded, setNotAdded] = useState<string | null>(null);
+ const users = useQuery({
+ queryKey: ['bridge-user-names', workspaceId, bridgeId],
+ queryFn: () => rpc.workspaces.listBridgeUserNames({ workspaceId, bridgeId }),
+ });
+ const present = new Set(room.connectedUserNames);
+ return (
+ <>
+ <AddParticipantPanel
+ noun="person"
+ searchPlaceholder={`Search people on ${room.bridgeDisplayName ?? 'the messaging app'}…`}
+ allInText="Everyone Switch knows on this messaging app is already in the room."
+ loading={users.isPending}
+ loadError={users.isError ? failureText(users.error, 'Could not list the people.') : null}
+ candidates={(users.data ?? [])
+ .filter((name) => !present.has(name))
+ .map((name) => ({
+ id: name,
+ name,
+ mark: <PersonMark name={name} size="sm" />,
+ detail: 'person',
+ }))}
+ footer={
+ <p className="px-1 text-xs text-foreground-muted">
+ Only people Switch has seen on this messaging app are listed.
+ </p>
+ }
+ onAdd={async (name) => {
+ setNotAdded(null);
+ const updated = await rpc.workspaces.addRoomUsers({
+ workspaceId,
+ roomId: room.id,
+ userNames: [name],
+ });
+ queryClient.setQueryData(roomDetailKey(workspaceId, room.id), updated);
+ if (!updated.connectedUserNames.includes(name))
+ setNotAdded(
+ `${name} was not added. The messaging app may not have let Switch invite them.`
+ );
+ }}
+ />
+ {notAdded !== null && <p className="text-xs text-destructive">{notAdded}</p>}
+ </>
+ );
+});
+
+type Candidate = { id: string; name: string; mark: React.ReactNode; detail: string };
+
+/**
+ * A searchable list of who could join, each row adding one. A refusal is shown
+ * in the words `onAdd` threw with.
+ */
+function AddParticipantPanel({
+ noun,
+ searchPlaceholder,
+ allInText,
+ loading,
+ loadError,
+ candidates,
+ footer,
+ onAdd,
+}: {
+ noun: string;
+ searchPlaceholder: string;
+ allInText: string;
+ loading: boolean;
+ loadError: string | null;
+ candidates: Candidate[];
+ /** Under the list, such as where to go for someone who is not in it. */
+ footer: React.ReactNode;
+ onAdd: (id: string) => Promise<void>;
+}) {
+ const [filter, setFilter] = useState('');
+ const [busyId, setBusyId] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const query = filter.trim().toLowerCase();
+ const shown = candidates.filter(
+ (candidate) =>
+ query === '' || `${candidate.name}\n${candidate.detail}`.toLowerCase().includes(query)
+ );
+
+ async function add(id: string) {
+ setBusyId(id);
+ setError(null);
+ try {
+ await onAdd(id);
+ } catch (cause) {
+ setError(failureText(cause, `Could not add the ${noun}.`));
+ } finally {
+ setBusyId(null);
+ }
+ }
+
+ return (
+ <div className="flex flex-col gap-2 pt-1">
+ <InputGroup>
+ <InputGroupAddon>
+ <Search className="size-3.5 text-foreground-muted" />
+ </InputGroupAddon>
+ <InputGroupInput
+ autoFocus
+ placeholder={searchPlaceholder}
+ aria-label={`Search for a ${noun} to add`}
+ value={filter}
+ onChange={(e) => setFilter(e.target.value)}
+ />
+ {filter !== '' && (
+ <InputGroupAddon align="inline-end">
+ <InputGroupButton
+ size="icon-xs"
+ aria-label="Clear the search"
+ onClick={() => setFilter('')}
+ >
+ <X className="size-3.5" />
+ </InputGroupButton>
+ </InputGroupAddon>
+ )}
+ </InputGroup>
+
+ {error !== null && <p className="text-xs text-destructive">Not added — {error}</p>}
+ {loadError !== null && <p className="text-xs text-destructive">{loadError}</p>}
+
+ {loading ? (
+ <p className="px-1 py-2 text-sm text-foreground-muted">Loading…</p>
+ ) : shown.length === 0 ? (
+ loadError === null && (
+ <p className="px-1 py-2 text-sm text-foreground-muted">
+ {query === '' ? allInText : `No ${noun} here matches “${filter.trim()}”.`}
+ </p>
+ )
+ ) : (
+ <div className="divide-y divide-border overflow-hidden rounded-[10px] border border-border">
+ {shown.map((candidate) => (
+ <button
+ key={candidate.id}
+ type="button"
+ disabled={busyId !== null}
+ onClick={() => void add(candidate.id)}
+ className={cn(
+ 'flex w-full cursor-pointer items-center gap-3 bg-background px-3.5 py-2.5 text-left transition-colors hover:bg-[var(--fill)]',
+ busyId !== null && 'cursor-wait'
+ )}
+ >
+ {candidate.mark}
+ <span className="min-w-0 flex-1 truncate text-sm text-foreground">
+ {candidate.name}
+ </span>
+ <span className="shrink-0 text-xs text-foreground-muted">{candidate.detail}</span>
+ <span className="shrink-0 text-xs font-medium text-foreground">
+ {busyId === candidate.id ? 'Adding…' : 'Add'}
+ </span>
+ </button>
+ ))}
+ </div>
+ )}
+ {footer}
+ </div>
+ );
+}
+
+/**
+ * Search the server's agents and put one in the room — any agent the viewer can
+ * see, as the gateway offers. Whether an agent then answers anyone in the room
+ * is still up to its own addressing rules.
+ */
+export const AddAgentPanel = observer(function AddAgentPanel({
+ workspaceId,
+ room,
+ onAdded,
+}: {
+ workspaceId: string;
+ room: RemoteRoomDetail;
+ onAdded: () => Promise<void>;
+}) {
+ const members = new Set(room.agentIds);
+ const remoteAgents = useWorkspaceAgents(workspaceId);
+ const serverId = workspacesStore.serverIdFor(workspaceId);
+ const viewerId = serverId ? (switchServersStore.statusFor(serverId)?.user?.id ?? null) : null;
+ return (
+ <AddParticipantPanel
+ noun="agent"
+ footer={null}
+ searchPlaceholder="Search agents…"
+ allInText={
+ (remoteAgents.data ?? []).length === 0
+ ? 'There are no agents on this server yet.'
+ : 'Every agent on this server is already in this room.'
+ }
+ loading={remoteAgents.isPending}
+ loadError={
+ remoteAgents.isError ? failureText(remoteAgents.error, 'Could not list the agents.') : null
+ }
+ candidates={(remoteAgents.data ?? [])
+ .filter((agent) => !members.has(agent.id))
+ .map((agent) => ({
+ id: agent.id,
+ name: agent.name,
+ mark: (
+ <AgentAvatar name={agent.name} iconUrl={agent.iconUrl} serverId={serverId} size={22} />
+ ),
+ detail: [
+ localAgentFor(agent.id, workspaceId) ||
+ (viewerId !== null && agent.ownerId === viewerId)
+ ? 'yours'
+ : agent.ownerName
+ ? `${agent.ownerName}’s`
+ : null,
+ agentKindFor(agent.id, workspaceId, new Map([[agent.id, agent]])),
+ ]
+ .filter(Boolean)
+ .join(' · '),
+ }))}
+ onAdd={async (agentId) => {
+ await rpc.workspaces.addRoomAgents({
+ workspaceId,
+ roomId: room.id,
+ agentIds: [agentId],
+ direction: 'agents_to_room',
+ });
+ await onAdded();
+ }}
+ />
+ );
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
index 9b4a3efa9..248fc4d83 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
@@ -1,72 +1,29 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
-import {
- Archive,
- ExternalLink,
- FileText,
- Loader2,
- Lock,
- Plus,
- RefreshCw,
- Search,
- X,
-} from 'lucide-react';
+import { Archive, ExternalLink, FileText, Loader2, Lock, RefreshCw } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useState } from 'react';
-import { chatMembersQueryKey, workspaceRosterQuery } from '@renderer/features/chats/chat-people';
import { confirmLeaveChat } from '@renderer/features/chats/components/chat-actions';
import { opensAsConsoleChat } from '@renderer/features/chats/console-chat-redirect';
-import { chatFailure } from '@renderer/features/chats/stores/chat-errors';
import { chatsStore } from '@renderer/features/chats/stores/chats';
import { refreshSidebarRoomState } from '@renderer/features/sidebar/sidebar-tree-data';
import { isConsoleGroupChatSummary } from '@renderer/features/switch-servers/room-filters';
-import type { RoomPermissions } from '@renderer/features/switch-servers/room-permissions';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
-import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
-import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
-import { ParticipantPicker } from '@renderer/lib/components/participant-picker';
-import {
- agentParticipant,
- type Participant,
- personParticipant,
-} from '@renderer/lib/components/participant-search';
import { describeFailure, failureText } from '@renderer/lib/errors/describe-failure';
-import { useFeatureFlags } from '@renderer/lib/hooks/useFeatureFlags';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
-import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';
import { Button } from '@renderer/lib/ui/button';
-import { ConfirmButton } from '@renderer/lib/ui/confirm-button';
import { Input } from '@renderer/lib/ui/input';
-import {
- InputGroup,
- InputGroupAddon,
- InputGroupButton,
- InputGroupInput,
-} from '@renderer/lib/ui/input-group';
-import { Switch } from '@renderer/lib/ui/switch';
import { Textarea } from '@renderer/lib/ui/textarea';
import { cn } from '@renderer/utils/utils';
-import { type ChatSummary, chatAgentLabel } from '@shared/core/chats/chats';
-import { knownAgentTypeDisplayName } from '@shared/core/providers/agent-provider-registry';
-import { runsOnThisComputer } from '@shared/core/switch-servers/switch-servers';
+import { type ChatSummary } from '@shared/core/chats/chats';
import type { RemoteRoomDetail } from '@shared/core/switch-servers/switch-servers';
-import { administersWorkspace } from '@shared/core/workspaces/workspaces';
-import { roomAgentPresence } from './room-agent-presence';
import { channelOnDeleteSummary } from './room-delete-wording';
-import { addableAgents, addablePeople, membershipSummary, roomTitle } from './room-labels';
+import { roomTitle } from './room-labels';
import { openRoomChannel } from './room-links';
-import { roomInviteability } from './room-membership';
-import {
- AgentMark,
- agentKindFor,
- agentNameFor,
- localAgentFor,
- PersonMark,
- roomDetailKey,
-} from './room-participants';
+import { roomDetailKey } from './room-participants';
import {
AccessAndGroupFields,
ArchiveRoomSection,
@@ -119,7 +76,6 @@ const ChatConfiguration = observer(function ChatConfiguration({
{failureText(detail.error, 'Could not read this chat’s description and instructions.')}
</p>
)}
- <ChatParticipantsSection serverId={serverId} workspaceId={workspaceId} chat={chat} />
{workspaceId !== null && detail.data && (
<>
<RolesSection
@@ -153,316 +109,6 @@ const ChatConfiguration = observer(function ChatConfiguration({
);
});
-/** Who is in a group chat; a manager adds and removes agents and people through the chat. */
-const ChatParticipantsSection = observer(function ChatParticipantsSection({
- serverId,
- workspaceId,
- chat,
-}: {
- serverId: string;
- workspaceId: string | null;
- chat: ChatSummary;
-}) {
- const queryClient = useQueryClient();
- const roomId = chat.roomId;
- const membersKey = chatMembersQueryKey(serverId, chat);
- // Adding to a chat makes it a group, which the server offers only with its group_chats flag.
- const groupChats = useFeatureFlags(serverId).group_chats;
- const canAdd = chat.canManage && groupChats;
- const members = useQuery({
- queryKey: membersKey,
- queryFn: () => rpc.chats.members(serverId, roomId),
- });
- const [removing, setRemoving] = useState<string | null>(null);
- const [error, setError] = useState<string | null>(null);
- const people = members.data ?? [];
- const agentIds = chat.agents.map((agent) => agent.id);
-
- async function remove(id: string, action: () => Promise<void>) {
- setRemoving(id);
- setError(null);
- try {
- await action();
- } catch (cause) {
- setError(`Not removed — ${chatFailure(cause).message}`);
- } finally {
- setRemoving(null);
- }
- }
- const manage: ManageParticipants | null = chat.canManage
- ? {
- removing,
- removeAgent: (agentId) =>
- void remove(agentId, async () => {
- await rpc.chats.removeAgent({ serverId, roomId, agentId });
- chatsStore.dropAgent(roomId, agentId);
- }),
- // The owner stays: there is no one to hand the chat to.
- removePerson: (userId) =>
- people.find((person) => person.userId === userId)?.isOwner
- ? null
- : () =>
- void remove(userId, async () => {
- await rpc.chats.removeMember({ serverId, roomId, userId });
- await queryClient.invalidateQueries({ queryKey: membersKey });
- }),
- }
- : null;
-
- return (
- <section className="flex flex-col gap-3">
- <div className="flex items-center justify-between gap-3">
- <div className="flex items-baseline gap-2">
- <h2 className="text-sm font-semibold text-foreground">Participants</h2>
- <span className="text-xs text-foreground-muted">
- {membershipSummary(agentIds.length, people.length)}
- </span>
- </div>
- {canAdd && (
- <Button
- variant="outline"
- size="sm"
- aria-controls={ADD_PARTICIPANT_INPUT}
- // Focusing the field opens its results.
- onClick={() => document.getElementById(ADD_PARTICIPANT_INPUT)?.focus()}
- >
- <Plus className="size-3.5" />
- Add participants
- </Button>
- )}
- </div>
-
- {canAdd && (
- <ChatAddParticipantPanel
- serverId={serverId}
- workspaceId={workspaceId}
- chat={chat}
- memberIds={new Set(people.map((person) => person.userId))}
- onAddedPeople={(next) => queryClient.setQueryData(membersKey, next)}
- />
- )}
-
- {members.isError && (
- <p className="text-xs text-destructive">{chatFailure(members.error).message}</p>
- )}
- {error !== null && <p className="text-xs text-destructive">{error}</p>}
-
- <ParticipantList
- workspaceId={workspaceId}
- agentIds={agentIds}
- agentNames={new Map(chat.agents.map((agent) => [agent.id, chatAgentLabel(agent)]))}
- people={people.map((person) => ({
- id: person.userId,
- name: person.name,
- detail: person.isOwner ? 'owner' : 'member',
- }))}
- manage={manage}
- />
- </section>
- );
-});
-
-/** Adds a picked participant through the chats API: an agent to the chat, a person as a member. */
-export async function addToChat(
- api: Pick<typeof rpc.chats, 'addAgent' | 'addMember'>,
- serverId: string,
- roomId: string,
- participant: Participant
-): Promise<
- | { kind: 'agent'; chat: ChatSummary }
- | { kind: 'person'; members: Awaited<ReturnType<typeof rpc.chats.addMember>> }
-> {
- if (participant.kind === 'agent')
- return {
- kind: 'agent',
- chat: await api.addAgent({ serverId, roomId, agentId: participant.id }),
- };
- return {
- kind: 'person',
- members: await api.addMember({ serverId, roomId, userId: participant.id }),
- };
-}
-
-const ADD_PARTICIPANT_INPUT = 'chat-add-participant';
-
-/** The Add button's label: how many it adds once there is more than one. */
-export function addLabel(count: number): string {
- return count > 1 ? `Add ${count}` : 'Add';
-}
-
-/**
- * Adds each pick in turn through the chats API, telling `onAdded` of each
- * success; resolves to the picks the server refused, each with its reason.
- * One at a time, so each add sees the chat as the one before left it.
- */
-export async function addAllToChat(
- api: Pick<typeof rpc.chats, 'addAgent' | 'addMember'>,
- serverId: string,
- roomId: string,
- picks: Participant[],
- onAdded: (added: Awaited<ReturnType<typeof addToChat>>) => void
-): Promise<{ participant: Participant; reason: string }[]> {
- const failures: { participant: Participant; reason: string }[] = [];
- for (const participant of picks) {
- try {
- onAdded(await addToChat(api, serverId, roomId, participant));
- } catch (cause) {
- failures.push({ participant, reason: chatFailure(cause).message });
- }
- }
- return failures;
-}
-
-/**
- * The New room dialog's participant field: picks gather as chips, and Add
- * puts them all in the chat. It offers the agents the viewer may add and the
- * people on the roster, never someone already in the chat.
- */
-const ChatAddParticipantPanel = observer(function ChatAddParticipantPanel({
- serverId,
- workspaceId,
- chat,
- memberIds,
- onAddedPeople,
-}: {
- serverId: string;
- workspaceId: string | null;
- chat: ChatSummary;
- /** The people in the chat, the viewer included. */
- memberIds: Set<string>;
- onAddedPeople: (members: Awaited<ReturnType<typeof rpc.chats.addMember>>) => void;
-}) {
- const tenantId = chatsStore.tenantId;
- const agents = useWorkspaceAgents(workspaceId);
- const roster = useQuery(workspaceRosterQuery(serverId, tenantId));
- const allowed = useQuery({
- // Keyed by the chat's agents, so adding or removing one asks again.
- queryKey: [
- 'chat-agent-candidates',
- serverId,
- workspaceId,
- chat.roomId,
- chat.agents.map((agent) => agent.id).join(','),
- ],
- queryFn: () => rpc.chats.agentCandidates({ serverId, roomId: chat.roomId }),
- });
- const [picked, setPicked] = useState<Participant[]>([]);
- const [adding, setAdding] = useState(false);
- const [refused, setRefused] = useState<string[]>([]);
- const candidates = [
- ...addableAgents(agents.data ?? [], allowed.data ?? []).map((agent) =>
- agentParticipant(agent, knownAgentTypeDisplayName(agent.knownAgentType) ?? 'Agent')
- ),
- ...addablePeople(roster.data ?? [], memberIds).map(personParticipant),
- ];
-
- async function addAll() {
- if (adding || picked.length === 0) return;
- setAdding(true);
- setRefused([]);
- const failures = await addAllToChat(rpc.chats, serverId, chat.roomId, picked, (added) => {
- if (added.kind === 'agent') chatsStore.add(serverId, added.chat);
- else onAddedPeople(added.members);
- });
- setPicked(failures.map((failure) => failure.participant));
- setRefused(
- failures.map(({ participant, reason }) => `${participant.name} was not added — ${reason}`)
- );
- setAdding(false);
- }
-
- return (
- <div className="flex flex-col gap-2 pt-1">
- <div className="flex items-start gap-2">
- <div className="min-w-0 flex-1">
- <ParticipantPicker
- inputId={ADD_PARTICIPANT_INPUT}
- autoFocus={false}
- busy={adding}
- overlay
- candidates={candidates}
- picked={picked}
- onChange={setPicked}
- serverId={serverId}
- loading={
- agents.isPending || allowed.isPending || (tenantId !== null && roster.isPending)
- }
- />
- </div>
- <ConfirmButton
- size="sm"
- className="h-8 shrink-0"
- disabled={picked.length === 0 || adding}
- onClick={() => void addAll()}
- >
- {addLabel(picked.length)}
- </ConfirmButton>
- </div>
- {refused.map((line) => (
- <p key={line} className="text-xs text-destructive">
- {line}
- </p>
- ))}
- {(agents.isError || allowed.isError) && (
- <p className="text-xs text-destructive">
- {failureText(agents.error ?? allowed.error, 'Could not list the agents.')}
- </p>
- )}
- {tenantId === null ? (
- <p className="text-xs text-destructive">
- This workspace has no tenant to list people from.
- </p>
- ) : (
- roster.isError && (
- <p className="text-xs text-destructive">
- {failureText(roster.error, 'Could not list the people.')}
- </p>
- )
- )}
- <InviteHint workspaceId={workspaceId} canInvite={canInvite(serverId, workspaceId)} />
- </div>
- );
-});
-
-/** Whether the viewer may invite people to the workspace, as the workspace menu decides it. */
-function canInvite(serverId: string, workspaceId: string | null): boolean {
- const workspace = workspacesStore.workspaces.find((each) => each.id === workspaceId) ?? null;
- const server = switchServersStore.servers.find((each) => each.id === serverId) ?? null;
- return (
- workspace !== null &&
- server !== null &&
- administersWorkspace(workspace) &&
- !runsOnThisComputer(server)
- );
-}
-
-/** Where to go for someone the roster does not have yet. */
-export function InviteHint({
- workspaceId,
- canInvite,
-}: {
- workspaceId: string | null;
- canInvite: boolean;
-}) {
- const showInvitePeopleModal = useShowModal('invitePeopleModal');
- return (
- <p className="px-1 text-xs text-foreground-muted">
- Don&apos;t see someone?{' '}
- {canInvite && workspaceId !== null ? (
- <button
- type="button"
- className="cursor-pointer underline hover:text-foreground"
- onClick={() => showInvitePeopleModal({ workspaceId })}
- >
- Invite them to the workspace
- </button>
- ) : (
- 'Ask a workspace admin to invite them.'
- )}
- </p>
- );
-}
-
/**
* A room's settings: what it is for, what it tells agents on arrival, and who is
* in it.
@@ -547,7 +193,6 @@ export const RoomConfigurationPanel = observer(function RoomConfigurationPanel({
readOnly={!permissions.canWrite}
/>
<AccessAndGroupFields workspaceId={workspaceId} room={room} permissions={permissions} />
- <ParticipantsSection workspaceId={workspaceId} room={room} permissions={permissions} />
<RolesSection workspaceId={workspaceId} room={room} permissions={permissions} />
<RoomInfoSection room={room} />
<section
@@ -565,7 +210,6 @@ export const RoomConfigurationPanel = observer(function RoomConfigurationPanel({
const SETTINGS_SECTIONS = [
['room-settings-general', 'General'],
- ['room-settings-participants', 'Participants'],
['room-settings-roles', 'Roles'],
['room-settings-info', 'Room info'],
['room-settings-archive', 'Archive & delete'],
@@ -917,535 +561,6 @@ function Field({
);
}
-/**
- * Who is in the room: each agent with what it is doing here, whether it is told
- * when someone joins, and a way to take it out; then the people. Someone who may
- * write to the room adds agents — any agent on the server, as the gateway
- * offers — and invites people from the messaging app.
- */
-const ParticipantsSection = observer(function ParticipantsSection({
- workspaceId,
- room,
- permissions,
-}: {
- workspaceId: string;
- room: RemoteRoomDetail;
- permissions: RoomPermissions;
-}) {
- const queryClient = useQueryClient();
- const [panel, setPanel] = useState<'agent' | 'people' | null>(null);
- const [busy, setBusy] = useState<string | null>(null);
- const [error, setError] = useState<string | null>(null);
- const showAddAgentsToRoomModal = useShowModal('addAgentsToRoomModal');
- const remoteAgents = useWorkspaceAgents(workspaceId);
- const remoteById = new Map((remoteAgents.data ?? []).map((agent) => [agent.id, agent]));
- const detailQueryKey = roomDetailKey(workspaceId, room.id);
- const canWrite = permissions.canWrite;
- const inviteability = roomInviteability(room, bridgePlatformLabel(room.bridgeType));
- const canInvitePeople = canWrite && inviteability.canInvite;
-
- async function refresh() {
- await queryClient.invalidateQueries({ queryKey: detailQueryKey });
- await switchRoomsStore.refreshRoomState();
- }
-
- async function act(key: string, action: () => Promise<void>, fallback: string) {
- setBusy(key);
- setError(null);
- try {
- await action();
- } catch (cause) {
- setError(failureText(cause, fallback));
- } finally {
- setBusy(null);
- }
- }
-
- return (
- <section id="room-settings-participants" className="flex flex-col gap-3">
- <div className="flex items-center justify-between gap-3">
- <div className="flex items-baseline gap-2">
- <h2 className="text-sm font-semibold text-foreground">Participants</h2>
- <span className="text-xs text-foreground-muted">
- {membershipSummary(room.agentIds.length, room.connectedUserNames.length)}
- </span>
- </div>
- {canWrite && (
- <div className="flex items-center gap-2">
- <Button
- variant="outline"
- size="sm"
- onClick={() => showAddAgentsToRoomModal({ roomId: room.id })}
- >
- <FileText className="size-3.5" />
- From a template
- </Button>
- <Button
- variant="outline"
- size="sm"
- aria-expanded={panel === 'agent'}
- onClick={() => setPanel(panel === 'agent' ? null : 'agent')}
- >
- <Plus className="size-3.5" />
- Add agent
- </Button>
- {canInvitePeople && (
- <Button
- variant="outline"
- size="sm"
- aria-expanded={panel === 'people'}
- onClick={() => setPanel(panel === 'people' ? null : 'people')}
- >
- <Plus className="size-3.5" />
- Add people
- </Button>
- )}
- </div>
- )}
- </div>
-
- {panel === 'agent' && (
- <AddAgentPanel workspaceId={workspaceId} room={room} onAdded={refresh} />
- )}
- {panel === 'people' && room.bridgeId !== null && (
- <AddPeoplePanel workspaceId={workspaceId} room={room} bridgeId={room.bridgeId} />
- )}
- {error !== null && <p className="text-xs text-destructive">{error}</p>}
- {canWrite && !inviteability.canInvite && inviteability.reason !== null && (
- <p className="text-xs text-foreground-muted">{inviteability.reason}</p>
- )}
-
- {room.agentIds.length === 0 && room.connectedUserNames.length === 0 ? (
- <p className="text-sm text-foreground-muted">Nobody is in this room yet.</p>
- ) : (
- <div className="divide-y divide-border overflow-hidden rounded-[10px] border border-border">
- {room.agentIds.map((agentId) => {
- const name = agentNameFor(agentId, workspaceId, remoteById);
- const presence = roomAgentPresence(room.agentStatuses[agentId]);
- const role = room.roles.find((each) => each.heldBy.includes(name));
- const listening = room.joinEventListeners.includes(agentId);
- return (
- <div key={agentId} className="flex items-center gap-3 px-3.5 py-2.5">
- <AgentMark agentId={agentId} workspaceId={workspaceId} remoteById={remoteById} />
- <div className="flex min-w-0 flex-1 flex-col">
- <span className="truncate text-sm font-medium text-foreground">{name}</span>
- <span className="truncate text-xs text-foreground-muted">
- {[
- agentKindFor(agentId, workspaceId, remoteById),
- room.agentStatuses[agentId] === undefined ? null : presence.label,
- role ? `role: ${role.name}` : null,
- ]
- .filter(Boolean)
- .join(' · ')}
- </span>
- </div>
- <label
- className="flex shrink-0 items-center gap-2 text-xs text-foreground-muted"
- title="Tell this agent when someone joins the room"
- >
- Notify on join
- <Switch
- size="sm"
- checked={listening}
- disabled={!canWrite || busy === `join:${agentId}`}
- aria-label={`Tell ${name} when someone joins`}
- onCheckedChange={(next) =>
- void act(
- `join:${agentId}`,
- async () => {
- queryClient.setQueryData(
- detailQueryKey,
- await rpc.workspaces.setRoomAgentJoinEvents({
- workspaceId,
- roomId: room.id,
- agentId,
- receivesJoinEvents: next,
- })
- );
- },
- 'Could not change the join notification.'
- )
- }
- />
- </label>
- {canWrite && (
- <Button
- variant="ghost"
- size="icon-xs"
- aria-label={`Remove ${name}`}
- title={`Remove ${name}`}
- disabled={busy === `remove:${agentId}`}
- onClick={() =>
- void act(
- `remove:${agentId}`,
- async () => {
- await rpc.workspaces.removeRoomAgent({
- workspaceId,
- roomId: room.id,
- agentId,
- });
- await refresh();
- },
- `Could not remove ${name}.`
- )
- }
- >
- {busy === `remove:${agentId}` ? <Loader2 className="animate-spin" /> : <X />}
- </Button>
- )}
- </div>
- );
- })}
- {room.connectedUserNames.map((person) => (
- <div key={`user:${person}`} className="flex items-center gap-3 px-3.5 py-2.5">
- <PersonMark name={person} size="md" />
- <span className="min-w-0 flex-1 truncate text-sm text-foreground">{person}</span>
- <span className="shrink-0 text-xs text-foreground-muted">person</span>
- </div>
- ))}
- </div>
- )}
- {room.bridgeId !== null && room.connectedUserNames.length > 0 && (
- <p className="text-xs text-foreground-muted">
- People are those Switch has seen in the channel or added to it. The channel may have more.
- </p>
- )}
- </section>
- );
-});
-
-/**
- * Invite people to a bridged room from the messaging app's users Switch knows.
- * The server does not say who it could not add, so the names asked for are
- * compared with the room's people afterwards and any missing are named.
- */
-const AddPeoplePanel = observer(function AddPeoplePanel({
- workspaceId,
- room,
- bridgeId,
-}: {
- workspaceId: string;
- room: RemoteRoomDetail;
- bridgeId: string;
-}) {
- const queryClient = useQueryClient();
- const [notAdded, setNotAdded] = useState<string | null>(null);
- const users = useQuery({
- queryKey: ['bridge-user-names', workspaceId, bridgeId],
- queryFn: () => rpc.workspaces.listBridgeUserNames({ workspaceId, bridgeId }),
- });
- const present = new Set(room.connectedUserNames);
- return (
- <>
- <AddParticipantPanel
- noun="person"
- searchPlaceholder={`Search people on ${room.bridgeDisplayName ?? 'the messaging app'}…`}
- allInText="Everyone Switch knows on this messaging app is already in the room."
- loading={users.isPending}
- loadError={users.isError ? failureText(users.error, 'Could not list the people.') : null}
- candidates={(users.data ?? [])
- .filter((name) => !present.has(name))
- .map((name) => ({
- id: name,
- name,
- mark: <PersonMark name={name} size="sm" />,
- detail: 'person',
- }))}
- footer={
- <p className="px-1 text-xs text-foreground-muted">
- Only people Switch has seen on this messaging app are listed.
- </p>
- }
- onAdd={async (name) => {
- setNotAdded(null);
- const updated = await rpc.workspaces.addRoomUsers({
- workspaceId,
- roomId: room.id,
- userNames: [name],
- });
- queryClient.setQueryData(roomDetailKey(workspaceId, room.id), updated);
- if (!updated.connectedUserNames.includes(name))
- setNotAdded(
- `${name} was not added. The messaging app may not have let Switch invite them.`
- );
- }}
- />
- {notAdded !== null && <p className="text-xs text-destructive">{notAdded}</p>}
- </>
- );
-});
-
-type Person = { id: string; name: string; detail: string };
-
-/** Removal from the cards, for someone who may manage the members; `removePerson` is null for one who cannot be removed. */
-type ManageParticipants = {
- removing: string | null;
- removeAgent: (agentId: string) => void;
- removePerson: (id: string) => (() => void) | null;
-};
-
-/** The room's members as cards, agents first. `agentNames` names agents the caller already knows. */
-const ParticipantList = observer(function ParticipantList({
- workspaceId,
- agentIds,
- agentNames,
- people,
- manage,
-}: {
- workspaceId: string | null;
- agentIds: string[];
- agentNames: Map<string, string>;
- people: Person[];
- manage: ManageParticipants | null;
-}) {
- // Names for agents belonging to other installs, which this computer has no
- // local record of. Shares its key with the rest of the app, so it is usually
- // already in hand.
- const remoteAgents = useWorkspaceAgents(workspaceId);
- const remoteById = new Map((remoteAgents.data ?? []).map((a) => [a.id, a]));
- return agentIds.length === 0 && people.length === 0 ? (
- <p className="text-sm text-foreground-muted">Nobody is in this room yet.</p>
- ) : (
- <div className="grid grid-cols-2 gap-2.5">
- {agentIds.map((agentId) => (
- <ParticipantCard
- key={agentId}
- mark={<AgentMark agentId={agentId} workspaceId={workspaceId} remoteById={remoteById} />}
- name={agentNames.get(agentId) ?? agentNameFor(agentId, workspaceId, remoteById)}
- detail={agentKindFor(agentId, workspaceId, remoteById)}
- removing={manage?.removing === agentId}
- onRemove={manage && (() => manage.removeAgent(agentId))}
- />
- ))}
- {people.map((person) => (
- <ParticipantCard
- key={person.id}
- mark={<PersonMark name={person.name} size="md" />}
- name={person.name}
- detail={person.detail}
- removing={manage?.removing === person.id}
- onRemove={manage?.removePerson(person.id) ?? null}
- />
- ))}
- </div>
- );
-});
-
-function ParticipantCard({
- mark,
- name,
- detail,
- removing,
- onRemove,
-}: {
- mark: React.ReactNode;
- name: string;
- detail: string;
- removing: boolean;
- onRemove: (() => void) | null;
-}) {
- return (
- <div className="flex items-center gap-3 rounded-[10px] border border-border bg-[var(--surface-2)] px-3.5 py-3">
- {mark}
- <div className="flex min-w-0 flex-1 flex-col">
- <span className="truncate text-sm font-medium text-foreground">{name}</span>
- <span className="truncate text-xs text-foreground-muted">{detail}</span>
- </div>
- {onRemove && (
- <Button
- variant="ghost"
- size="icon-xs"
- aria-label={`Remove ${name}`}
- title={`Remove ${name}`}
- disabled={removing}
- onClick={onRemove}
- >
- {removing ? <Loader2 className="animate-spin" /> : <X />}
- </Button>
- )}
- </div>
- );
-}
-
-type Candidate = { id: string; name: string; mark: React.ReactNode; detail: string };
-
-/**
- * A searchable list of who could join, each row adding one. A refusal is shown
- * in the words `onAdd` threw with.
- */
-function AddParticipantPanel({
- noun,
- searchPlaceholder,
- allInText,
- loading,
- loadError,
- candidates,
- footer,
- onAdd,
-}: {
- noun: string;
- searchPlaceholder: string;
- allInText: string;
- loading: boolean;
- loadError: string | null;
- candidates: Candidate[];
- /** Under the list, such as where to go for someone who is not in it. */
- footer: React.ReactNode;
- onAdd: (id: string) => Promise<void>;
-}) {
- const [filter, setFilter] = useState('');
- const [busyId, setBusyId] = useState<string | null>(null);
- const [error, setError] = useState<string | null>(null);
- const query = filter.trim().toLowerCase();
- const shown = candidates.filter(
- (candidate) =>
- query === '' || `${candidate.name}\n${candidate.detail}`.toLowerCase().includes(query)
- );
-
- async function add(id: string) {
- setBusyId(id);
- setError(null);
- try {
- await onAdd(id);
- } catch (cause) {
- setError(failureText(cause, `Could not add the ${noun}.`));
- } finally {
- setBusyId(null);
- }
- }
-
- return (
- <div className="flex flex-col gap-2 pt-1">
- <InputGroup>
- <InputGroupAddon>
- <Search className="size-3.5 text-foreground-muted" />
- </InputGroupAddon>
- <InputGroupInput
- autoFocus
- placeholder={searchPlaceholder}
- aria-label={`Search for a ${noun} to add`}
- value={filter}
- onChange={(e) => setFilter(e.target.value)}
- />
- {filter !== '' && (
- <InputGroupAddon align="inline-end">
- <InputGroupButton
- size="icon-xs"
- aria-label="Clear the search"
- onClick={() => setFilter('')}
- >
- <X className="size-3.5" />
- </InputGroupButton>
- </InputGroupAddon>
- )}
- </InputGroup>
-
- {error !== null && <p className="text-xs text-destructive">Not added — {error}</p>}
- {loadError !== null && <p className="text-xs text-destructive">{loadError}</p>}
-
- {loading ? (
- <p className="px-1 py-2 text-sm text-foreground-muted">Loading…</p>
- ) : shown.length === 0 ? (
- loadError === null && (
- <p className="px-1 py-2 text-sm text-foreground-muted">
- {query === '' ? allInText : `No ${noun} here matches “${filter.trim()}”.`}
- </p>
- )
- ) : (
- <div className="divide-y divide-border overflow-hidden rounded-[10px] border border-border">
- {shown.map((candidate) => (
- <button
- key={candidate.id}
- type="button"
- disabled={busyId !== null}
- onClick={() => void add(candidate.id)}
- className={cn(
- 'flex w-full cursor-pointer items-center gap-3 bg-background px-3.5 py-2.5 text-left transition-colors hover:bg-[var(--fill)]',
- busyId !== null && 'cursor-wait'
- )}
- >
- {candidate.mark}
- <span className="min-w-0 flex-1 truncate text-sm text-foreground">
- {candidate.name}
- </span>
- <span className="shrink-0 text-xs text-foreground-muted">{candidate.detail}</span>
- <span className="shrink-0 text-xs font-medium text-foreground">
- {busyId === candidate.id ? 'Adding…' : 'Add'}
- </span>
- </button>
- ))}
- </div>
- )}
- {footer}
- </div>
- );
-}
-
-/**
- * Search the server's agents and put one in the room — any agent the viewer can
- * see, as the gateway offers. Whether an agent then answers anyone in the room
- * is still up to its own addressing rules.
- */
-const AddAgentPanel = observer(function AddAgentPanel({
- workspaceId,
- room,
- onAdded,
-}: {
- workspaceId: string;
- room: RemoteRoomDetail;
- onAdded: () => Promise<void>;
-}) {
- const members = new Set(room.agentIds);
- const remoteAgents = useWorkspaceAgents(workspaceId);
- const serverId = workspacesStore.serverIdFor(workspaceId);
- const viewerId = serverId ? (switchServersStore.statusFor(serverId)?.user?.id ?? null) : null;
- return (
- <AddParticipantPanel
- noun="agent"
- footer={null}
- searchPlaceholder="Search agents…"
- allInText={
- (remoteAgents.data ?? []).length === 0
- ? 'There are no agents on this server yet.'
- : 'Every agent on this server is already in this room.'
- }
- loading={remoteAgents.isPending}
- loadError={
- remoteAgents.isError ? failureText(remoteAgents.error, 'Could not list the agents.') : null
- }
- candidates={(remoteAgents.data ?? [])
- .filter((agent) => !members.has(agent.id))
- .map((agent) => ({
- id: agent.id,
- name: agent.name,
- mark: (
- <AgentAvatar name={agent.name} iconUrl={agent.iconUrl} serverId={serverId} size={22} />
- ),
- detail: [
- localAgentFor(agent.id, workspaceId) ||
- (viewerId !== null && agent.ownerId === viewerId)
- ? 'yours'
- : agent.ownerName
- ? `${agent.ownerName}’s`
- : null,
- agentKindFor(agent.id, workspaceId, new Map([[agent.id, agent]])),
- ]
- .filter(Boolean)
- .join(' · '),
- }))}
- onAdd={async (agentId) => {
- await rpc.workspaces.addRoomAgents({
- workspaceId,
- roomId: room.id,
- agentIds: [agentId],
- direction: 'agents_to_room',
- });
- await onAdded();
- }}
- />
- );
-});
-
function PanelNotice({
icon,
title,
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-resources-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-resources-panel.tsx
new file mode 100644
index 000000000..d85b2bf87
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-resources-panel.tsx
@@ -0,0 +1,676 @@
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { ExternalLink, FileText, Link2, Loader2, Package, Plus, Search, X } from 'lucide-react';
+import { observer } from 'mobx-react-lite';
+import { type ReactNode, useState } from 'react';
+import { opensAsConsoleChat } from '@renderer/features/chats/console-chat-redirect';
+import { chatsStore } from '@renderer/features/chats/stores/chats';
+import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
+import { failureText } from '@renderer/lib/errors/describe-failure';
+import { rpc } from '@renderer/lib/ipc';
+import { useNavigate } from '@renderer/lib/layout/navigation-provider';
+import { openExternalUrl } from '@renderer/lib/open-external';
+import { Button } from '@renderer/lib/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogContentArea,
+ DialogHeader,
+ DialogTitle,
+} from '@renderer/lib/ui/dialog';
+import { Input } from '@renderer/lib/ui/input';
+import type { RoomResource, RoomResourceKind } from '@shared/core/switch-servers/switch-servers';
+import { roomDetailKey } from './room-participants';
+import { attachableResources, resourcesByOrigin } from './room-resources';
+
+const KIND_LABEL: Record<RoomResourceKind, { title: string; noun: string; none: string }> = {
+ references: { title: 'References', noun: 'reference', none: 'No references attached.' },
+ documents: { title: 'Documents', noun: 'document', none: 'No documents attached.' },
+ packages: { title: 'Packages', noun: 'package', none: 'No packages attached.' },
+};
+
+const roomResourcesKey = (workspaceId: string, roomId: string, kind: RoomResourceKind) => [
+ 'room-resources',
+ workspaceId,
+ roomId,
+ kind,
+];
+const linkedRoomsKey = (workspaceId: string, roomId: string) => [
+ 'room-linked-rooms',
+ workspaceId,
+ roomId,
+];
+
+/**
+ * What the room's agents are given to work with, as the gateway shows it: the
+ * library's references, documents and packages attached to the room, the
+ * documents its agents wrote here, and the rooms it points at. Whoever may
+ * change the room attaches, detaches and links; everyone else reads.
+ */
+export const RoomResourcesPanel = observer(function RoomResourcesPanel({
+ roomId,
+}: {
+ roomId: string;
+}) {
+ const chat = chatsStore.chat(roomId);
+ const workspaceId =
+ switchRoomsStore.roomWorkspaceId(roomId) ?? (chat ? workspacesStore.activeId : null);
+ const detail = useQuery({
+ queryKey: roomDetailKey(workspaceId ?? '', roomId),
+ queryFn: () => rpc.workspaces.getRoomDetail({ workspaceId: workspaceId as string, roomId }),
+ enabled: workspaceId !== null,
+ });
+ if (workspaceId === null) {
+ return <Centered>This room’s workspace is still loading.</Centered>;
+ }
+ const room = detail.data ?? null;
+ // A Console chat's members may read it but only its managers change it.
+ const canWrite =
+ opensAsConsoleChat(roomId) && chat
+ ? chat.canManage
+ : room !== null && switchRoomsStore.roomPermissions(workspaceId, room).canWrite;
+
+ return (
+ <div className="h-full overflow-y-auto">
+ <div className="mx-auto flex w-full max-w-[880px] flex-col gap-8 px-10 py-8">
+ <ResourceSection
+ workspaceId={workspaceId}
+ roomId={roomId}
+ kind="references"
+ canWrite={canWrite}
+ />
+ <ResourceSection
+ workspaceId={workspaceId}
+ roomId={roomId}
+ kind="documents"
+ canWrite={canWrite}
+ />
+ <ResourceSection
+ workspaceId={workspaceId}
+ roomId={roomId}
+ kind="packages"
+ canWrite={canWrite}
+ />
+ <LinkedRoomsSection workspaceId={workspaceId} roomId={roomId} canWrite={canWrite} />
+ </div>
+ </div>
+ );
+});
+
+const ResourceSection = observer(function ResourceSection({
+ workspaceId,
+ roomId,
+ kind,
+ canWrite,
+}: {
+ workspaceId: string;
+ roomId: string;
+ kind: RoomResourceKind;
+ canWrite: boolean;
+}) {
+ const queryClient = useQueryClient();
+ const key = roomResourcesKey(workspaceId, roomId, kind);
+ const attached = useQuery({
+ queryKey: key,
+ queryFn: () => rpc.workspaces.listRoomResources({ workspaceId, roomId, kind }),
+ });
+ // Packages say what came in with them, so a reference or document shows which package brought it.
+ const packages = useQuery({
+ queryKey: roomResourcesKey(workspaceId, roomId, 'packages'),
+ queryFn: () => rpc.workspaces.listRoomResources({ workspaceId, roomId, kind: 'packages' }),
+ enabled: kind !== 'packages',
+ });
+ const [picking, setPicking] = useState(false);
+ const [busy, setBusy] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [reading, setReading] = useState<RoomResource | null>(null);
+ const label = KIND_LABEL[kind];
+ const packageNames = new Map((packages.data ?? []).map((p) => [p.id, p.name]));
+ const { library, roomScoped } = resourcesByOrigin(attached.data ?? []);
+
+ async function detach(resource: RoomResource) {
+ setBusy(resource.id);
+ setError(null);
+ try {
+ await rpc.workspaces.setRoomResourceAttached({
+ workspaceId,
+ roomId,
+ kind,
+ resourceId: resource.id,
+ attached: false,
+ });
+ await queryClient.invalidateQueries({ queryKey: key });
+ } catch (cause) {
+ setError(
+ failureText(
+ cause,
+ resource.roomScoped
+ ? `Could not delete ${resource.name}.`
+ : `Could not detach ${resource.name}.`
+ )
+ );
+ } finally {
+ setBusy(null);
+ }
+ }
+
+ return (
+ <section aria-label={label.title} className="flex flex-col gap-3">
+ <div className="flex items-center justify-between gap-3">
+ <h2 className="text-sm font-semibold text-foreground">{label.title}</h2>
+ {canWrite && (
+ <Button variant="outline" size="sm" onClick={() => setPicking(true)}>
+ <Plus className="size-3.5" />
+ Attach {label.noun}
+ </Button>
+ )}
+ </div>
+ {attached.isPending ? (
+ <Loader2 className="size-4 animate-spin text-foreground-muted" />
+ ) : attached.isError ? (
+ <p className="text-xs text-destructive">
+ {failureText(attached.error, `Could not list this room’s ${label.title.toLowerCase()}.`)}
+ </p>
+ ) : library.length === 0 && roomScoped.length === 0 ? (
+ <p className="text-sm text-foreground-muted">{label.none}</p>
+ ) : (
+ <>
+ {library.length > 0 && (
+ <List>
+ {library.map((resource) => (
+ <ResourceRow
+ key={resource.id}
+ resource={resource}
+ via={resource.packageIds.map((id) => packageNames.get(id) ?? 'a package')}
+ onOpen={
+ resource.urls[0]
+ ? () => void openExternalUrl(resource.urls[0]!, 'Could not open the link')
+ : kind === 'documents'
+ ? () => setReading(resource)
+ : null
+ }
+ removeLabel={canWrite ? `Detach ${resource.name}` : null}
+ busy={busy === resource.id}
+ onRemove={() => void detach(resource)}
+ />
+ ))}
+ </List>
+ )}
+ {roomScoped.length > 0 && (
+ <>
+ <p className="text-xs text-foreground-muted">Written by agents in this room</p>
+ <List>
+ {roomScoped.map((resource) => (
+ <ResourceRow
+ key={resource.id}
+ resource={resource}
+ via={[]}
+ onOpen={() => setReading(resource)}
+ removeLabel={canWrite ? `Delete ${resource.name}` : null}
+ busy={busy === resource.id}
+ onRemove={() => void detach(resource)}
+ />
+ ))}
+ </List>
+ </>
+ )}
+ </>
+ )}
+ {error !== null && <p className="text-xs text-destructive">{error}</p>}
+ {picking && (
+ <AttachDialog
+ workspaceId={workspaceId}
+ roomId={roomId}
+ kind={kind}
+ attached={attached.data ?? []}
+ onClose={() => setPicking(false)}
+ onAttached={() => void queryClient.invalidateQueries({ queryKey: key })}
+ />
+ )}
+ {reading && (
+ <DocumentDialog
+ workspaceId={workspaceId}
+ roomId={roomId}
+ document={reading}
+ onClose={() => setReading(null)}
+ />
+ )}
+ </section>
+ );
+});
+
+function ResourceRow({
+ resource,
+ via,
+ onOpen,
+ removeLabel,
+ busy,
+ onRemove,
+}: {
+ resource: RoomResource;
+ /** The packages that brought it in, by name. */
+ via: string[];
+ onOpen: (() => void) | null;
+ /** The remove button's label, or null for someone who may not remove it. */
+ removeLabel: string | null;
+ busy: boolean;
+ onRemove: () => void;
+}) {
+ const Icon =
+ resource.kind === 'packages' ? Package : resource.kind === 'documents' ? FileText : Link2;
+ const meta = [
+ resource.typeLabel,
+ resource.createdByAgentName ? `by ${resource.createdByAgentName}` : null,
+ ...via.map((name) => `via ${name}`),
+ ].filter(Boolean);
+ const body = (
+ <>
+ <Icon className="size-4 shrink-0 text-foreground-muted" />
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="flex items-center gap-1.5 truncate text-sm text-foreground">
+ {resource.name}
+ {resource.urls[0] && <ExternalLink className="size-3 shrink-0 text-foreground-muted" />}
+ </span>
+ {(resource.description || meta.length > 0) && (
+ <span className="truncate text-xs text-foreground-muted">
+ {[...meta, resource.description].filter(Boolean).join(' · ')}
+ </span>
+ )}
+ </span>
+ </>
+ );
+ return (
+ <div className="flex items-center gap-2 px-3.5 py-2.5">
+ {onOpen ? (
+ <button
+ type="button"
+ className="flex min-w-0 flex-1 cursor-pointer items-center gap-3 text-left"
+ onClick={onOpen}
+ >
+ {body}
+ </button>
+ ) : (
+ <div className="flex min-w-0 flex-1 items-center gap-3">{body}</div>
+ )}
+ {removeLabel && (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label={removeLabel}
+ title={removeLabel}
+ disabled={busy}
+ onClick={onRemove}
+ >
+ {busy ? <Loader2 className="animate-spin" /> : <X />}
+ </Button>
+ )}
+ </div>
+ );
+}
+
+/** The library's items of one kind not yet attached, each attached with a click. */
+const AttachDialog = observer(function AttachDialog({
+ workspaceId,
+ roomId,
+ kind,
+ attached,
+ onClose,
+ onAttached,
+}: {
+ workspaceId: string;
+ roomId: string;
+ kind: RoomResourceKind;
+ attached: RoomResource[];
+ onClose: () => void;
+ onAttached: () => void;
+}) {
+ const library = useQuery({
+ queryKey: ['library', workspaceId, kind],
+ queryFn: () => rpc.workspaces.listLibrary({ workspaceId, kind }),
+ });
+ const [filter, setFilter] = useState('');
+ const [done, setDone] = useState<Set<string>>(new Set());
+ const [busy, setBusy] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const label = KIND_LABEL[kind];
+ const shown = attachableResources(library.data ?? [], attached, filter).filter(
+ (resource) => !done.has(resource.id)
+ );
+
+ async function attach(resource: RoomResource) {
+ setBusy(resource.id);
+ setError(null);
+ try {
+ await rpc.workspaces.setRoomResourceAttached({
+ workspaceId,
+ roomId,
+ kind,
+ resourceId: resource.id,
+ attached: true,
+ });
+ setDone((current) => new Set(current).add(resource.id));
+ onAttached();
+ } catch (cause) {
+ setError(failureText(cause, `Could not attach ${resource.name}.`));
+ } finally {
+ setBusy(null);
+ }
+ }
+
+ return (
+ <Dialog open onOpenChange={(open) => !open && onClose()}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>Attach a {label.noun}</DialogTitle>
+ </DialogHeader>
+ <DialogContentArea className="flex flex-col gap-3 pt-0">
+ <div className="relative">
+ <Search className="absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-foreground-muted" />
+ <Input
+ autoFocus
+ className="pl-8"
+ placeholder={`Search ${label.title.toLowerCase()}…`}
+ value={filter}
+ onChange={(event) => setFilter(event.target.value)}
+ />
+ </div>
+ {library.isPending ? (
+ <Loader2 className="size-4 animate-spin text-foreground-muted" />
+ ) : library.isError ? (
+ <p className="text-xs text-destructive">
+ {failureText(library.error, `Could not list the ${label.title.toLowerCase()}.`)}
+ </p>
+ ) : shown.length === 0 ? (
+ <p className="text-sm text-foreground-muted">
+ {filter.trim()
+ ? `No ${label.title.toLowerCase()} match.`
+ : `Every ${label.noun} you can read is already attached.`}
+ </p>
+ ) : (
+ <div className="flex max-h-80 flex-col overflow-y-auto">
+ {shown.map((resource) => (
+ <div key={resource.id} className="flex items-center gap-2 py-1.5">
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="truncate text-sm text-foreground">{resource.name}</span>
+ {(resource.typeLabel || resource.description) && (
+ <span className="truncate text-xs text-foreground-muted">
+ {[resource.typeLabel, resource.description].filter(Boolean).join(' · ')}
+ </span>
+ )}
+ </span>
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={busy !== null}
+ onClick={() => void attach(resource)}
+ >
+ {busy === resource.id ? <Loader2 className="animate-spin" /> : 'Attach'}
+ </Button>
+ </div>
+ ))}
+ </div>
+ )}
+ {error !== null && <p className="text-xs text-destructive">{error}</p>}
+ </DialogContentArea>
+ </DialogContent>
+ </Dialog>
+ );
+});
+
+function DocumentDialog({
+ workspaceId,
+ roomId,
+ document,
+ onClose,
+}: {
+ workspaceId: string;
+ roomId: string;
+ document: RoomResource;
+ onClose: () => void;
+}) {
+ const content = useQuery({
+ queryKey: ['room-document', workspaceId, roomId, document.id],
+ queryFn: () => rpc.workspaces.getRoomDocument({ workspaceId, roomId, documentId: document.id }),
+ });
+ return (
+ <Dialog open onOpenChange={(open) => !open && onClose()}>
+ <DialogContent className="sm:max-w-2xl">
+ <DialogHeader>
+ <DialogTitle>{document.name}</DialogTitle>
+ </DialogHeader>
+ <DialogContentArea className="flex flex-col gap-3 overflow-y-auto pt-0">
+ {document.description && (
+ <p className="text-sm text-foreground-muted">{document.description}</p>
+ )}
+ {content.isPending ? (
+ <Loader2 className="size-4 animate-spin text-foreground-muted" />
+ ) : content.isError ? (
+ <p className="text-xs text-destructive">
+ {failureText(content.error, 'Could not read this document.')}
+ </p>
+ ) : (
+ <pre className="rounded-md bg-background-1 p-3 font-mono text-xs whitespace-pre-wrap text-foreground">
+ {content.data.content}
+ </pre>
+ )}
+ </DialogContentArea>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+const LinkedRoomsSection = observer(function LinkedRoomsSection({
+ workspaceId,
+ roomId,
+ canWrite,
+}: {
+ workspaceId: string;
+ roomId: string;
+ canWrite: boolean;
+}) {
+ const queryClient = useQueryClient();
+ const { navigate } = useNavigate();
+ const key = linkedRoomsKey(workspaceId, roomId);
+ const links = useQuery({
+ queryKey: key,
+ queryFn: () => rpc.workspaces.listLinkedRooms({ workspaceId, roomId }),
+ });
+ const [adding, setAdding] = useState(false);
+ const [busy, setBusy] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ async function remove(targetRoomId: string, name: string) {
+ setBusy(targetRoomId);
+ setError(null);
+ try {
+ await rpc.workspaces.removeLinkedRoom({ workspaceId, roomId, targetRoomId });
+ await queryClient.invalidateQueries({ queryKey: key });
+ } catch (cause) {
+ setError(failureText(cause, `Could not unlink ${name}.`));
+ } finally {
+ setBusy(null);
+ }
+ }
+
+ return (
+ <section aria-label="Linked rooms" className="flex flex-col gap-3">
+ <div className="flex items-center justify-between gap-3">
+ <h2 className="text-sm font-semibold text-foreground">Linked rooms</h2>
+ {canWrite && (
+ <Button variant="outline" size="sm" onClick={() => setAdding(true)}>
+ <Plus className="size-3.5" />
+ Link a room
+ </Button>
+ )}
+ </div>
+ {links.isPending ? (
+ <Loader2 className="size-4 animate-spin text-foreground-muted" />
+ ) : links.isError ? (
+ <p className="text-xs text-destructive">
+ {failureText(links.error, 'Could not list the linked rooms.')}
+ </p>
+ ) : links.data.length === 0 ? (
+ <p className="text-sm text-foreground-muted">This room points at no other rooms.</p>
+ ) : (
+ <List>
+ {links.data.map((link) => (
+ <div key={link.roomId} className="flex items-center gap-2 px-3.5 py-2.5">
+ <button
+ type="button"
+ className="flex min-w-0 flex-1 cursor-pointer flex-col text-left"
+ onClick={() => navigate('room', { roomId: link.roomId })}
+ >
+ <span className="truncate text-sm text-foreground">{link.name}</span>
+ <span className="truncate text-xs text-foreground-muted">
+ {[link.label, link.description].filter(Boolean).join(' · ')}
+ </span>
+ </button>
+ {canWrite && (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label={`Unlink ${link.name}`}
+ title={`Unlink ${link.name}`}
+ disabled={busy === link.roomId}
+ onClick={() => void remove(link.roomId, link.name)}
+ >
+ {busy === link.roomId ? <Loader2 className="animate-spin" /> : <X />}
+ </Button>
+ )}
+ </div>
+ ))}
+ </List>
+ )}
+ {error !== null && <p className="text-xs text-destructive">{error}</p>}
+ {adding && (
+ <LinkRoomDialog
+ workspaceId={workspaceId}
+ roomId={roomId}
+ linked={new Set((links.data ?? []).map((link) => link.roomId))}
+ onClose={() => setAdding(false)}
+ onLinked={() => void queryClient.invalidateQueries({ queryKey: key })}
+ />
+ )}
+ </section>
+ );
+});
+
+const LinkRoomDialog = observer(function LinkRoomDialog({
+ workspaceId,
+ roomId,
+ linked,
+ onClose,
+ onLinked,
+}: {
+ workspaceId: string;
+ roomId: string;
+ linked: Set<string>;
+ onClose: () => void;
+ onLinked: () => void;
+}) {
+ const [filter, setFilter] = useState('');
+ const [target, setTarget] = useState<string | null>(null);
+ const [label, setLabel] = useState('');
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const query = filter.trim().toLowerCase();
+ const rooms = switchRoomsStore
+ .readableRoomsInWorkspace(workspaceId)
+ .filter((room) => room.id !== roomId && !linked.has(room.id) && !room.archived)
+ .filter((room) => !query || room.name.toLowerCase().includes(query));
+
+ async function save() {
+ if (target === null || !label.trim()) return;
+ setSaving(true);
+ setError(null);
+ try {
+ await rpc.workspaces.addLinkedRoom({
+ workspaceId,
+ roomId,
+ targetRoomId: target,
+ label: label.trim(),
+ });
+ onLinked();
+ onClose();
+ } catch (cause) {
+ setError(failureText(cause, 'Could not link the room.'));
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ return (
+ <Dialog open onOpenChange={(open) => !open && onClose()}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>Link a room</DialogTitle>
+ </DialogHeader>
+ <DialogContentArea className="flex flex-col gap-3 pt-0">
+ <Input
+ autoFocus
+ placeholder="Search rooms…"
+ value={filter}
+ onChange={(event) => setFilter(event.target.value)}
+ />
+ <div className="flex max-h-56 flex-col overflow-y-auto" role="listbox">
+ {rooms.length === 0 ? (
+ <p className="py-2 text-sm text-foreground-muted">No other rooms to link.</p>
+ ) : (
+ rooms.map((room) => (
+ <button
+ key={room.id}
+ type="button"
+ role="option"
+ aria-selected={target === room.id}
+ className={
+ target === room.id
+ ? 'rounded-md bg-[var(--sel-soft)] px-2 py-1.5 text-left text-sm text-foreground'
+ : 'rounded-md px-2 py-1.5 text-left text-sm text-foreground hover:bg-background-1'
+ }
+ onClick={() => setTarget(room.id)}
+ >
+ {room.name}
+ </button>
+ ))
+ )}
+ </div>
+ <Input
+ placeholder="Why they are linked, such as “support” or “depends on”"
+ value={label}
+ maxLength={200}
+ onChange={(event) => setLabel(event.target.value)}
+ />
+ {error !== null && <p className="text-xs text-destructive">{error}</p>}
+ <div className="flex justify-end gap-2">
+ <Button variant="ghost" size="sm" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button
+ size="sm"
+ disabled={target === null || !label.trim() || saving}
+ onClick={() => void save()}
+ >
+ Link
+ </Button>
+ </div>
+ </DialogContentArea>
+ </DialogContent>
+ </Dialog>
+ );
+});
+
+function List({ children }: { children: ReactNode }) {
+ return (
+ <div className="divide-y divide-border overflow-hidden rounded-[10px] border border-border">
+ {children}
+ </div>
+ );
+}
+
+function Centered({ children }: { children: ReactNode }) {
+ return (
+ <div className="flex h-full items-center justify-center p-8 text-sm text-foreground-muted">
+ {children}
+ </div>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-resources.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-resources.test.ts
new file mode 100644
index 000000000..bbbcf3e88
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-resources.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from 'vitest';
+import type { RoomResource } from '@shared/core/switch-servers/switch-servers';
+import { attachableResources, resourcesByOrigin } from './room-resources';
+
+const resource = (overrides: Partial<RoomResource>): RoomResource => ({
+ id: 'r',
+ kind: 'documents',
+ name: 'Doc',
+ description: '',
+ typeLabel: null,
+ urls: [],
+ roomScoped: false,
+ createdByAgentName: null,
+ packageIds: [],
+ ...overrides,
+});
+
+describe('a room’s resources', () => {
+ it('keeps the documents agents wrote here apart from the library’s', () => {
+ const { library, roomScoped } = resourcesByOrigin([
+ resource({ id: 'lib' }),
+ resource({ id: 'mine', roomScoped: true }),
+ ]);
+ expect(library.map((r) => r.id)).toEqual(['lib']);
+ expect(roomScoped.map((r) => r.id)).toEqual(['mine']);
+ });
+
+ it('offers what is not attached yet, by name, matching name, type or description', () => {
+ const library = [
+ resource({ id: 'b', name: 'Beta', kind: 'references', typeLabel: 'GitHub' }),
+ resource({ id: 'a', name: 'Alpha', description: 'design notes' }),
+ resource({ id: 'c', name: 'Gamma' }),
+ ];
+ const attached = [resource({ id: 'c' })];
+ expect(attachableResources(library, attached, '').map((r) => r.id)).toEqual(['a', 'b']);
+ expect(attachableResources(library, attached, 'github').map((r) => r.id)).toEqual(['b']);
+ expect(attachableResources(library, attached, ' DESIGN ').map((r) => r.id)).toEqual(['a']);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-resources.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-resources.ts
new file mode 100644
index 000000000..95dca7087
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-resources.ts
@@ -0,0 +1,38 @@
+import type { RoomResource } from '@shared/core/switch-servers/switch-servers';
+
+/**
+ * A room's attached items split as the gateway shows them: those from the
+ * library, and the documents agents wrote in the room itself.
+ */
+export function resourcesByOrigin(resources: readonly RoomResource[]): {
+ library: RoomResource[];
+ roomScoped: RoomResource[];
+} {
+ return {
+ library: resources.filter((resource) => !resource.roomScoped),
+ roomScoped: resources.filter((resource) => resource.roomScoped),
+ };
+}
+
+/**
+ * The library's items not attached to the room yet, by name, matching what
+ * was typed in their name, type or description.
+ */
+export function attachableResources(
+ library: readonly RoomResource[],
+ attached: readonly RoomResource[],
+ filter: string
+): RoomResource[] {
+ const already = new Set(attached.map((resource) => resource.id));
+ const query = filter.trim().toLowerCase();
+ return library
+ .filter((resource) => !already.has(resource.id))
+ .filter(
+ (resource) =>
+ !query ||
+ [resource.name, resource.typeLabel ?? '', resource.description].some((text) =>
+ text.toLowerCase().includes(query)
+ )
+ )
+ .sort((a, b) => a.name.localeCompare(b.name));
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-side-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-side-panel.tsx
index 279cc45a5..b03f478ea 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-side-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-side-panel.tsx
@@ -1,22 +1,44 @@
-import { useQuery } from '@tanstack/react-query';
-import { ChevronDown, ChevronRight, Settings } from 'lucide-react';
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { ChevronDown, ChevronRight, FileText, Loader2, MoreHorizontal, Plus } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { type ReactNode, useState } from 'react';
import { chatMembersQueryKey } from '@renderer/features/chats/chat-people';
import { opensAsConsoleChat } from '@renderer/features/chats/console-chat-redirect';
+import { chatFailure } from '@renderer/features/chats/stores/chat-errors';
import { chatsStore } from '@renderer/features/chats/stores/chats';
import { useManagedAgents } from '@renderer/features/managed-agents/use-managed-agents';
+import { isConsoleGroupChatSummary } from '@renderer/features/switch-servers/room-filters';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
+import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
+import { failureText } from '@renderer/lib/errors/describe-failure';
+import { useFeatureFlags } from '@renderer/lib/hooks/useFeatureFlags';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
+import { useShowModal } from '@renderer/lib/modal/modal-provider';
import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';
import { Button } from '@renderer/lib/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogContentArea,
+ DialogHeader,
+ DialogTitle,
+} from '@renderer/lib/ui/dialog';
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@renderer/lib/ui/dropdown-menu';
import { cn } from '@renderer/utils/utils';
import { chatAgentLabel } from '@shared/core/chats/chats';
+import type { RemoteRoomDetail } from '@shared/core/switch-servers/switch-servers';
+import { AddAgentPanel, AddPeoplePanel, ChatAddParticipantPanel } from './room-add-participants';
import { roomAgentPresence } from './room-agent-presence';
+import { roomInviteability } from './room-membership';
import { AgentMark, agentNameFor, PersonMark, roomDetailKey } from './room-participants';
-import { roomTabStore } from './room-tab-store';
const TONE_CLASS = {
live: 'bg-foreground-success',
@@ -24,30 +46,60 @@ const TONE_CLASS = {
off: 'bg-[var(--fg-passive)]',
} as const;
+/** What the viewer may change about who is in the room, and how. */
+type RosterControls = {
+ /** Opens adding agents, or null for someone who may not add them. */
+ addAgents: (() => void) | null;
+ /** Opens adding people, or null where they cannot be added. */
+ addPeople: (() => void) | null;
+ /** Why people cannot be added here, for someone who could otherwise. */
+ peopleNote: string | null;
+ removeAgent: ((agentId: string) => Promise<void>) | null;
+ /** Null for someone who may not remove people, or for a person who cannot be removed. */
+ removePerson: (key: string) => (() => Promise<void>) | null;
+ /** Whether the agent is told when someone joins, and the way to change it; null where it cannot be. */
+ joinEvents: {
+ listening: (agentId: string) => boolean;
+ set: (agentId: string, on: boolean) => Promise<void>;
+ } | null;
+};
+
+const NO_CONTROLS: RosterControls = {
+ addAgents: null,
+ addPeople: null,
+ peopleNote: null,
+ removeAgent: null,
+ removePerson: () => null,
+ joinEvents: null,
+};
+
/**
- * The room's own column, beside its conversation: a way into its settings, and
- * what is in the room that the conversation does not already show — who the
- * agents are and what each is doing here, and who the people are.
- *
- * Nothing here is a setting. Settings live behind the button, on a page of their
- * own, so the column never repeats them; the room's name and description are in
- * the title bar above, so it does not repeat those either.
+ * Who is in the room, beside it on every tab and on every platform: the
+ * agents and what each is doing here, and the people. Whoever may change the
+ * room adds and removes them here too. The room's settings and resources are
+ * its tabs, so nothing else lives in this column.
*/
export const RoomSidePanel = observer(function RoomSidePanel({ roomId }: { roomId: string }) {
+ const queryClient = useQueryClient();
const chat = chatsStore.chat(roomId);
const consoleChat = opensAsConsoleChat(roomId);
const workspaceId =
switchRoomsStore.roomWorkspaceId(roomId) ?? (chat ? workspacesStore.activeId : null);
const serverId =
switchRoomsStore.roomServerId(roomId) ?? (chat ? chatsStore.serverId : null) ?? null;
+ const groupChats = useFeatureFlags(serverId).group_chats;
+ const showAddAgentsToRoomModal = useShowModal('addAgentsToRoomModal');
+ const [adding, setAdding] = useState<'agents' | 'people' | null>(null);
+ const [error, setError] = useState<string | null>(null);
// Anyone taking part may read the room, so this answers for a chat's members too.
const detail = useQuery({
queryKey: roomDetailKey(workspaceId ?? '', roomId),
queryFn: () => rpc.workspaces.getRoomDetail({ workspaceId: workspaceId as string, roomId }),
enabled: workspaceId !== null,
});
+ const membersKey = chat && serverId ? chatMembersQueryKey(serverId, chat) : ['no-chat-members'];
const members = useQuery({
- queryKey: chat && serverId ? chatMembersQueryKey(serverId, chat) : ['no-chat-members'],
+ queryKey: membersKey,
queryFn: () => rpc.chats.members(serverId as string, roomId),
enabled: consoleChat && chat !== null && serverId !== null,
});
@@ -60,25 +112,91 @@ export const RoomSidePanel = observer(function RoomSidePanel({ roomId }: { roomI
key: member.userId,
name: member.name,
detail: member.isOwner ? 'owner' : null,
+ isOwner: member.isOwner,
}))
- : (room?.connectedUserNames ?? []).map((name) => ({ key: name, name, detail: null }));
+ : (room?.connectedUserNames ?? []).map((name) => ({
+ key: name,
+ name,
+ detail: null,
+ isOwner: false,
+ }));
+
+ async function refreshRoom() {
+ await queryClient.invalidateQueries({ queryKey: roomDetailKey(workspaceId ?? '', roomId) });
+ await switchRoomsStore.refreshRoomState();
+ }
+
+ let controls = NO_CONTROLS;
+ if (consoleChat && chat && serverId && isConsoleGroupChatSummary(chat) && chat.canManage) {
+ controls = {
+ ...NO_CONTROLS,
+ // Adding to a chat makes it a group, which the server offers only with group chats on.
+ addAgents: groupChats ? () => setAdding('agents') : null,
+ removeAgent: async (agentId) => {
+ await rpc.chats.removeAgent({ serverId, roomId, agentId });
+ chatsStore.dropAgent(roomId, agentId);
+ },
+ // The owner stays: there is no one to hand the chat to.
+ removePerson: (key) =>
+ people.find((person) => person.key === key)?.isOwner
+ ? null
+ : async () => {
+ await rpc.chats.removeMember({ serverId, roomId, userId: key });
+ await queryClient.invalidateQueries({ queryKey: membersKey });
+ },
+ };
+ } else if (!consoleChat && room && workspaceId) {
+ const permissions = switchRoomsStore.roomPermissions(workspaceId, room);
+ const inviteability = roomInviteability(room, bridgePlatformLabel(room.bridgeType));
+ if (permissions.canWrite) {
+ controls = {
+ addAgents: () => setAdding('agents'),
+ addPeople: inviteability.canInvite ? () => setAdding('people') : null,
+ peopleNote: inviteability.canInvite ? null : inviteability.reason,
+ removeAgent: async (agentId) => {
+ await rpc.workspaces.removeRoomAgent({ workspaceId, roomId, agentId });
+ await refreshRoom();
+ },
+ // Switch only knows the people it saw or added; it cannot take them out of a channel.
+ removePerson: () => null,
+ joinEvents: {
+ listening: (agentId) => room.joinEventListeners.includes(agentId),
+ set: async (agentId, on) => {
+ queryClient.setQueryData(
+ roomDetailKey(workspaceId, roomId),
+ await rpc.workspaces.setRoomAgentJoinEvents({
+ workspaceId,
+ roomId,
+ agentId,
+ receivesJoinEvents: on,
+ })
+ );
+ },
+ },
+ };
+ }
+ }
+
+ const act = async (action: () => Promise<void>, fallback: string) => {
+ setError(null);
+ try {
+ await action();
+ } catch (cause) {
+ setError(consoleChat ? chatFailure(cause).message : failureText(cause, fallback));
+ }
+ };
return (
<aside
aria-label="Room"
className="flex w-[260px] shrink-0 flex-col gap-3 overflow-y-auto border-r border-border p-2"
>
- <Button
- variant="outline"
- size="sm"
- className="w-full justify-center"
- onClick={() => roomTabStore.setTab(roomId, 'configuration')}
+ <Fold
+ title="Agents"
+ count={agentIds.length}
+ onAdd={controls.addAgents}
+ addLabel={consoleChat ? 'Add participants' : 'Add agents'}
>
- <Settings className="size-3.5" />
- Room settings
- </Button>
-
- <Fold title="Agents" count={agentIds.length}>
{agentIds.length === 0 ? (
<Note>No agents in this room yet.</Note>
) : (
@@ -92,25 +210,30 @@ export const RoomSidePanel = observer(function RoomSidePanel({ roomId }: { roomI
name={chatNames.get(agentId) ?? null}
status={room?.agentStatuses[agentId]}
roles={room?.roles ?? []}
+ controls={controls}
+ act={act}
/>
))
)}
</Fold>
- <Fold title={consoleChat ? 'People' : 'People seen here'} count={people.length}>
+ <Fold
+ title={consoleChat ? 'People' : 'People seen here'}
+ count={people.length}
+ onAdd={controls.addPeople}
+ addLabel="Add people"
+ >
{people.length === 0 ? (
<Note>{consoleChat ? 'Nobody else is here yet.' : 'Nobody has been seen here yet.'}</Note>
) : (
people.map((person) => (
- <div key={person.key} className="flex items-center gap-2 rounded-md px-2 py-1">
- <PersonMark name={person.name} size="sm" />
- <span className="min-w-0 flex-1 truncate text-[13px] text-foreground">
- {person.name}
- </span>
- {person.detail && (
- <span className="shrink-0 text-xs text-foreground-muted">{person.detail}</span>
- )}
- </div>
+ <PersonRow
+ key={person.key}
+ name={person.name}
+ detail={person.detail}
+ onRemove={controls.removePerson(person.key)}
+ act={act}
+ />
))
)}
{!consoleChat && (
@@ -119,7 +242,51 @@ export const RoomSidePanel = observer(function RoomSidePanel({ roomId }: { roomI
People who posted here or were added through Switch. The channel may have more.
</Note>
)}
+ {controls.peopleNote !== null && <Note>{controls.peopleNote}</Note>}
</Fold>
+
+ {error !== null && <p className="px-2 text-xs text-destructive">{error}</p>}
+
+ <Dialog open={adding !== null} onOpenChange={(open) => !open && setAdding(null)}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>
+ {adding === 'people' ? 'Add people' : consoleChat ? 'Add participants' : 'Add agents'}
+ </DialogTitle>
+ </DialogHeader>
+ <DialogContentArea className="flex flex-col gap-3 pt-0">
+ {adding === 'agents' && consoleChat && chat && serverId && (
+ <ChatAddParticipantPanel
+ serverId={serverId}
+ workspaceId={workspaceId}
+ chat={chat}
+ memberIds={new Set(people.map((person) => person.key))}
+ onAddedPeople={(next) => queryClient.setQueryData(membersKey, next)}
+ />
+ )}
+ {adding === 'agents' && !consoleChat && room && workspaceId && (
+ <>
+ <AddAgentPanel workspaceId={workspaceId} room={room} onAdded={refreshRoom} />
+ <Button
+ variant="outline"
+ size="sm"
+ className="self-start"
+ onClick={() => {
+ setAdding(null);
+ showAddAgentsToRoomModal({ roomId });
+ }}
+ >
+ <FileText className="size-3.5" />
+ From a template
+ </Button>
+ </>
+ )}
+ {adding === 'people' && room && workspaceId && room.bridgeId !== null && (
+ <AddPeoplePanel workspaceId={workspaceId} room={room} bridgeId={room.bridgeId} />
+ )}
+ </DialogContentArea>
+ </DialogContent>
+ </Dialog>
</aside>
);
});
@@ -127,7 +294,8 @@ export const RoomSidePanel = observer(function RoomSidePanel({ roomId }: { roomI
/**
* One agent in the room: its name, what it is doing here and the role it holds.
* The viewer's own agents open their seat in this room on the agent's page;
- * anyone else's are listed only.
+ * anyone else's are listed only. Whoever may change the room gets a menu for
+ * it here.
*/
const AgentRow = observer(function AgentRow({
agentId,
@@ -137,6 +305,8 @@ const AgentRow = observer(function AgentRow({
name,
status,
roles,
+ controls,
+ act,
}: {
agentId: string;
roomId: string;
@@ -145,13 +315,16 @@ const AgentRow = observer(function AgentRow({
name: string | null;
status: string | undefined;
/** The room's roles; the one this agent holds is shown beside its status. */
- roles: { name: string; heldBy: string[] }[];
+ roles: RemoteRoomDetail['roles'];
+ controls: RosterControls;
+ act: (action: () => Promise<void>, fallback: string) => Promise<void>;
}) {
const { navigate } = useNavigate();
const remoteAgents = useWorkspaceAgents(workspaceId);
const remoteById = new Map((remoteAgents.data ?? []).map((agent) => [agent.id, agent]));
const managed = useManagedAgents(serverId);
const own = (managed.data ?? []).find((agent) => agent.agentId === agentId) ?? null;
+ const [busy, setBusy] = useState(false);
const label = name ?? agentNameFor(agentId, workspaceId, remoteById);
// Roles name their holders by agent name, which is how the server reports them.
const role = roles.find((each) => each.heldBy.includes(label));
@@ -181,38 +354,158 @@ const AgentRow = observer(function AgentRow({
</>
);
- if (own && serverId) {
- return (
- <button
- type="button"
- title={`Open ${label}’s session in this room`}
- className="flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-1 text-left hover:bg-[var(--sel-soft)]"
- onClick={() =>
- navigate('managedAgent', { serverId, agentId, name: own.name, room: roomId })
- }
- >
- {body}
- </button>
- );
- }
- return <div className="flex items-center gap-2 rounded-md px-2 py-1">{body}</div>;
+ const run = (action: () => Promise<void>, fallback: string) => {
+ setBusy(true);
+ void act(action, fallback).finally(() => setBusy(false));
+ };
+ const { removeAgent, joinEvents } = controls;
+ const menu =
+ removeAgent || joinEvents ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label={`${label} in this room`}
+ className="shrink-0 opacity-0 group-hover:opacity-100 focus-visible:opacity-100 data-[popup-open]:opacity-100"
+ >
+ {busy ? <Loader2 className="animate-spin" /> : <MoreHorizontal />}
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end">
+ {joinEvents && (
+ <DropdownMenuCheckboxItem
+ checked={joinEvents.listening(agentId)}
+ onCheckedChange={(next) =>
+ run(() => joinEvents.set(agentId, next), 'Could not change the join notification.')
+ }
+ >
+ Tell it when someone joins
+ </DropdownMenuCheckboxItem>
+ )}
+ {removeAgent && (
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => run(() => removeAgent(agentId), `Could not remove ${label}.`)}
+ >
+ Remove from room
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : null;
+
+ return (
+ <div className="group flex items-center gap-1 rounded-md hover:bg-[var(--sel-soft)]">
+ {own && serverId ? (
+ <button
+ type="button"
+ title={`Open ${label}’s session in this room`}
+ className="flex min-w-0 flex-1 cursor-pointer items-center gap-2 px-2 py-1 text-left"
+ onClick={() =>
+ navigate('managedAgent', { serverId, agentId, name: own.name, room: roomId })
+ }
+ >
+ {body}
+ </button>
+ ) : (
+ <div className="flex min-w-0 flex-1 items-center gap-2 px-2 py-1">{body}</div>
+ )}
+ {menu}
+ </div>
+ );
});
-function Fold({ title, count, children }: { title: string; count: number; children: ReactNode }) {
+function PersonRow({
+ name,
+ detail,
+ onRemove,
+ act,
+}: {
+ name: string;
+ detail: string | null;
+ onRemove: (() => Promise<void>) | null;
+ act: (action: () => Promise<void>, fallback: string) => Promise<void>;
+}) {
+ const [busy, setBusy] = useState(false);
+ return (
+ <div className="group flex items-center gap-2 rounded-md px-2 py-1 hover:bg-[var(--sel-soft)]">
+ <PersonMark name={name} size="sm" />
+ <span className="min-w-0 flex-1 truncate text-[13px] text-foreground">{name}</span>
+ {detail && <span className="shrink-0 text-xs text-foreground-muted">{detail}</span>}
+ {onRemove && (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label={`${name} in this room`}
+ className="shrink-0 opacity-0 group-hover:opacity-100 focus-visible:opacity-100 data-[popup-open]:opacity-100"
+ >
+ {busy ? <Loader2 className="animate-spin" /> : <MoreHorizontal />}
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => {
+ setBusy(true);
+ void act(onRemove, `Could not remove ${name}.`).finally(() => setBusy(false));
+ }}
+ >
+ Remove from room
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </div>
+ );
+}
+
+function Fold({
+ title,
+ count,
+ onAdd,
+ addLabel,
+ children,
+}: {
+ title: string;
+ count: number;
+ onAdd: (() => void) | null;
+ addLabel: string;
+ children: ReactNode;
+}) {
const [open, setOpen] = useState(true);
const Chevron = open ? ChevronDown : ChevronRight;
return (
<section aria-label={title} className="flex flex-col gap-[2px]">
- <button
- type="button"
- aria-expanded={open}
- onClick={() => setOpen(!open)}
- className="flex items-center gap-1 px-1 pb-1 text-xs font-medium text-foreground-muted hover:text-foreground"
- >
- <Chevron className="size-3.5" />
- <span className="flex-1 text-left">{title}</span>
- <span className="text-[var(--fg-passive)] tabular-nums">{count}</span>
- </button>
+ <div className="flex items-center gap-1 px-1 pb-1">
+ <button
+ type="button"
+ aria-expanded={open}
+ onClick={() => setOpen(!open)}
+ className="flex flex-1 items-center gap-1 text-xs font-medium text-foreground-muted hover:text-foreground"
+ >
+ <Chevron className="size-3.5" />
+ <span className="flex-1 text-left">{title}</span>
+ <span className="text-[var(--fg-passive)] tabular-nums">{count}</span>
+ </button>
+ {onAdd && (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label={addLabel}
+ title={addLabel}
+ onClick={onAdd}
+ >
+ <Plus />
+ </Button>
+ )}
+ </div>
{open && children}
</section>
);
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-tab-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-tab-store.ts
index d3ffeaef6..21816b5e3 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-tab-store.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-tab-store.ts
@@ -1,8 +1,8 @@
import { makeAutoObservable } from 'mobx';
import { bridgeCanEmbed } from '@shared/core/switch-rooms/room-embed';
-/** The two things a room page can show. */
-export type RoomTab = 'chat' | 'configuration';
+/** The things a room page can show beside its participants. */
+export type RoomTab = 'chat' | 'resources' | 'configuration';
/**
* What a room shown inside another page opens on: its conversation when its
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/view.tsx
index b0fee3d1a..a5aab6fcc 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/view.tsx
@@ -1,4 +1,4 @@
-import { ArrowLeft, DoorOpen, ExternalLink } from 'lucide-react';
+import { DoorOpen, ExternalLink } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useLayoutEffect, useRef } from 'react';
import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';
@@ -20,6 +20,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/toolti
import { RoomConfigurationPanel } from './room-configuration-panel';
import { roomEmbedSlotStore } from './room-embed-slot';
import { openRoomChannel } from './room-links';
+import { RoomResourcesPanel } from './room-resources-panel';
import { RoomSidePanel } from './room-side-panel';
import { embeddedRoomTab, type RoomTab, roomTabStore } from './room-tab-store';
@@ -67,12 +68,14 @@ export const OpenInMessagingApp = observer(function OpenInMessagingApp({
const TABS = [
{ value: 'chat', label: 'Chat' },
+ { value: 'resources', label: 'Resources' },
{ value: 'configuration', label: 'Configuration' },
] as const satisfies readonly { value: RoomTab; label: string }[];
/**
- * The two sides of a room — its conversation and its settings — to pick
- * between; `fallback` is the side showing until one is picked.
+ * A room's tabs — its conversation, what its agents are given, and its
+ * settings — to pick between; `fallback` is the tab showing until one is
+ * picked.
*/
export const RoomTabs = observer(function RoomTabs({
roomId,
@@ -97,8 +100,7 @@ export const RoomTabs = observer(function RoomTabs({
* claim about how you got here rather than about where you are.
*
* Beside the name: where the room lives (its messaging app, or a group chat
- * here) and what it is for. Its settings are a page of their own, reached from
- * the room's side panel, and the title bar says when that page is showing.
+ * here) and what it is for; on the right, its tabs.
*/
const RoomTitlebar = observer(function RoomTitlebar() {
const { params } = useParams('room');
@@ -106,7 +108,6 @@ const RoomTitlebar = observer(function RoomTitlebar() {
const summary = switchRoomsStore.roomSummaryById(roomId);
const name = switchRoomsStore.roomNameById(roomId) ?? chatsStore.chat(roomId)?.name ?? null;
const bridgeType = switchRoomsStore.roomBridgeTypeById(roomId);
- const settings = roomTabStore.tabFor(roomId, 'chat') === 'configuration';
const where = summary?.bridgeDisplayName ?? (opensAsConsoleChat(roomId) ? 'Group chat' : null);
const description = summary?.description.trim() || null;
@@ -124,17 +125,15 @@ const RoomTitlebar = observer(function RoomTitlebar() {
<DoorOpen className="size-3.5 shrink-0" />
),
label: name ?? 'Room',
- onClick: settings ? () => roomTabStore.setTab(roomId, 'chat') : undefined,
},
- ...(settings ? [{ key: 'settings', label: 'Room settings' }] : []),
]}
/>
- {!settings && where && (
+ {where && (
<span className="shrink-0 rounded-full bg-background-tertiary px-2 py-0.5 text-[11px] text-foreground-muted">
{where}
</span>
)}
- {!settings && description && (
+ {description && (
<span className="min-w-0 truncate text-sm text-foreground-muted" title={description}>
{description}
</span>
@@ -142,7 +141,8 @@ const RoomTitlebar = observer(function RoomTitlebar() {
</div>
}
rightSlot={
- <div className="mr-2 flex items-center gap-1">
+ <div className="mr-2 flex items-center gap-2">
+ <RoomTabs roomId={roomId} fallback="chat" />
<OpenInMessagingApp roomId={roomId} />
</div>
}
@@ -158,35 +158,31 @@ const ConsoleChat = observer(function ConsoleChat({ roomId }: { roomId: string }
});
/**
- * The room's page: its side panel and its conversation, or — once Room
- * settings is picked — its settings across the whole page, with a way back.
- * Settings replace the page rather than sit beside the panel, so there is only
- * ever one column of the room's own beside the app's sidebar.
+ * The room's page: who is in it down the side, the same on every platform,
+ * and beside that the tab picked in the title bar — its conversation, its
+ * resources or its settings.
*/
const RoomMainPanel = observer(function RoomMainPanel(): React.JSX.Element {
const { params } = useParams('room');
const roomId = params.roomId;
+ const tab = roomTabStore.tabFor(roomId, 'chat');
return (
<>
<ConsoleChatRedirect roomId={roomId} />
- {roomTabStore.tabFor(roomId, 'chat') === 'configuration' ? (
- <div className="flex h-full min-h-0 flex-col">
- <div className="px-6 pt-3">
- <Button variant="outline" size="sm" onClick={() => roomTabStore.setTab(roomId, 'chat')}>
- <ArrowLeft className="size-3.5" />
- Back to room
- </Button>
- </div>
- <div className="min-h-0 flex-1">
- <RoomConfigurationPanel roomId={roomId} />
- </div>
- </div>
- ) : (
- <div className="flex h-full min-h-0">
- <RoomSidePanel roomId={roomId} />
+ <div className="flex h-full min-h-0">
+ <RoomSidePanel roomId={roomId} />
+ {tab === 'chat' ? (
<RoomConversation roomId={roomId} />
- </div>
- )}
+ ) : (
+ <div className="min-w-0 flex-1">
+ {tab === 'resources' ? (
+ <RoomResourcesPanel roomId={roomId} />
+ ) : (
+ <RoomConfigurationPanel roomId={roomId} />
+ )}
+ </div>
+ )}
+ </div>
</>
);
});
@@ -235,15 +231,17 @@ export const EmbeddedRoom = observer(function EmbeddedRoom({ roomId }: { roomId:
}, [roomId]);
return (
<div ref={ref} data-testid="embedded-room" className="min-h-0 flex-1">
- {roomTabStore.tabFor(roomId, embeddedRoomFallbackTab(roomId)) === 'configuration' ? (
- <RoomConfigurationPanel roomId={roomId} />
- ) : (
- <ConsoleChat roomId={roomId} />
- )}
+ {embeddedTabContent(roomId, roomTabStore.tabFor(roomId, embeddedRoomFallbackTab(roomId)))}
</div>
);
});
+function embeddedTabContent(roomId: string, tab: RoomTab): React.ReactNode {
+ if (tab === 'resources') return <RoomResourcesPanel roomId={roomId} />;
+ if (tab === 'configuration') return <RoomConfigurationPanel roomId={roomId} />;
+ return <ConsoleChat roomId={roomId} />;
+}
+
export const roomView = {
WrapView: ({ children }: { children: React.ReactNode; roomId: string }) => <>{children}</>,
TitlebarSlot: RoomTitlebar,
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/room-resources-panel.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/room-resources-panel.test.tsx
new file mode 100644
index 000000000..8c10b3684
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/room-resources-panel.test.tsx
@@ -0,0 +1,161 @@
+/**
+ * A room's Resources tab: what is attached, the documents its agents wrote,
+ * the rooms it points at, and the changes offered only to someone the server
+ * says may change the room.
+ */
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const listRoomResources = vi.hoisted(() => vi.fn());
+const setRoomResourceAttached = vi.hoisted(() => vi.fn());
+const listLinkedRooms = vi.hoisted(() => vi.fn());
+const permissions = vi.hoisted(() => ({ value: { canWrite: true, canManage: false } }));
+
+vi.hoisted(() => {
+ window.electronAPI ??= {
+ invoke: () => Promise.resolve(undefined),
+ eventOn: () => () => {},
+ eventSend: () => {},
+ } as unknown as typeof window.electronAPI;
+});
+
+vi.mock('@renderer/lib/ipc', () => ({
+ events: { on: vi.fn() },
+ rpc: {
+ workspaces: {
+ getRoomDetail: vi.fn(async () => ({ id: 'room-1', ownerId: 'u-2' })),
+ listRoomResources,
+ setRoomResourceAttached,
+ listLinkedRooms,
+ listLibrary: vi.fn(async () => []),
+ },
+ },
+}));
+
+vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({
+ switchRoomsStore: {
+ roomWorkspaceId: () => 'ws-1',
+ roomPermissions: () => permissions.value,
+ readableRoomsInWorkspace: () => [],
+ },
+}));
+
+import { RoomResourcesPanel } from '@renderer/features/switch-rooms/room-resources-panel';
+
+const base = {
+ description: '',
+ typeLabel: null,
+ urls: [],
+ createdByAgentName: null,
+ packageIds: [],
+};
+const RESOURCES = {
+ references: [
+ {
+ ...base,
+ id: 'ref-1',
+ kind: 'references',
+ name: 'Repo',
+ typeLabel: 'GitHub',
+ urls: ['https://github.com/acme/repo'],
+ roomScoped: false,
+ packageIds: ['pkg-1'],
+ },
+ ],
+ documents: [
+ { ...base, id: 'd-1', kind: 'documents', name: 'Guide', roomScoped: false },
+ {
+ ...base,
+ id: 'd-2',
+ kind: 'documents',
+ name: 'Standup notes',
+ roomScoped: true,
+ createdByAgentName: 'scribe',
+ },
+ ],
+ packages: [{ ...base, id: 'pkg-1', kind: 'packages', name: 'Onboarding', roomScoped: false }],
+};
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+beforeEach(() => {
+ listRoomResources.mockReset();
+ listRoomResources.mockImplementation(
+ async ({ kind }: { kind: keyof typeof RESOURCES }) => RESOURCES[kind]
+ );
+ setRoomResourceAttached.mockReset();
+ setRoomResourceAttached.mockResolvedValue(undefined);
+ listLinkedRooms.mockReset();
+ listLinkedRooms.mockResolvedValue([
+ { roomId: 'room-2', name: 'support', description: '', label: 'escalate to' },
+ ]);
+ permissions.value = { canWrite: true, canManage: false };
+});
+
+afterEach(async () => {
+ if (root) await act(async () => root!.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+});
+
+async function renderPanel(): Promise<HTMLDivElement> {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
+ await act(async () =>
+ root!.render(
+ <QueryClientProvider client={client}>
+ <RoomResourcesPanel roomId="room-1" />
+ </QueryClientProvider>
+ )
+ );
+ for (let i = 0; i < 8; i++) await act(async () => await Promise.resolve());
+ return container;
+}
+
+describe('the Resources tab', () => {
+ it('lists what is attached, which package brought it, and the rooms it points at', async () => {
+ const el = await renderPanel();
+ const text = el.textContent ?? '';
+ expect(text).toContain('Repo');
+ expect(text).toContain('GitHub');
+ expect(text).toContain('via Onboarding');
+ expect(text).toContain('Guide');
+ expect(text).toContain('Written by agents in this room');
+ expect(text).toContain('by scribe');
+ expect(text).toContain('support');
+ expect(text).toContain('escalate to');
+ });
+
+ it('offers attaching, detaching, deleting and linking to someone who may change the room', async () => {
+ const el = await renderPanel();
+ expect(el.textContent).toContain('Attach reference');
+ expect(el.textContent).toContain('Link a room');
+ expect(el.querySelector('[aria-label="Delete Standup notes"]')).not.toBeNull();
+ await act(async () =>
+ el.querySelector<HTMLButtonElement>('[aria-label="Detach Guide"]')!.click()
+ );
+ expect(setRoomResourceAttached).toHaveBeenCalledWith({
+ workspaceId: 'ws-1',
+ roomId: 'room-1',
+ kind: 'documents',
+ resourceId: 'd-1',
+ attached: false,
+ });
+ });
+
+ it('only lists for someone who may not change the room', async () => {
+ permissions.value = { canWrite: false, canManage: false };
+ const el = await renderPanel();
+ expect(el.textContent).toContain('Repo');
+ expect(el.textContent).not.toContain('Attach reference');
+ expect(el.textContent).not.toContain('Link a room');
+ expect(el.querySelector('[aria-label^="Detach"]')).toBeNull();
+ expect(el.querySelector('[aria-label^="Delete"]')).toBeNull();
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/room-settings-sections.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/room-settings-sections.test.tsx
index a50bf9ce4..5a6cbab6d 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/room-settings-sections.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/room-settings-sections.test.tsx
@@ -55,7 +55,13 @@ vi.mock('@renderer/features/sidebar/sidebar-tree-data', () => ({
refreshSidebarRoomStateAfterOnboarding: vi.fn(),
}));
+vi.mock('@renderer/lib/hooks/useFeatureFlags', () => ({ useFeatureFlags: () => ({}) }));
+vi.mock('@renderer/features/managed-agents/use-managed-agents', () => ({
+ useManagedAgents: () => ({ data: [] }),
+}));
+
import { RoomConfigurationPanel } from '@renderer/features/switch-rooms/room-configuration-panel';
+import { RoomSidePanel } from '@renderer/features/switch-rooms/room-side-panel';
const ROOM = {
id: 'room-1',
@@ -122,7 +128,9 @@ afterEach(async () => {
root = null;
});
-async function renderPanel(): Promise<HTMLDivElement> {
+async function renderPanel(
+ panel: 'configuration' | 'side' = 'configuration'
+): Promise<HTMLDivElement> {
container = document.createElement('div');
document.body.appendChild(container);
root = createRoot(container);
@@ -130,7 +138,11 @@ async function renderPanel(): Promise<HTMLDivElement> {
await act(async () =>
root!.render(
<QueryClientProvider client={client}>
- <RoomConfigurationPanel roomId="room-1" />
+ {panel === 'side' ? (
+ <RoomSidePanel roomId="room-1" />
+ ) : (
+ <RoomConfigurationPanel roomId="room-1" />
+ )}
</QueryClientProvider>
)
);
@@ -161,20 +173,28 @@ async function type(field: HTMLInputElement | HTMLTextAreaElement, value: string
}
describe('room settings for someone who may write to the room', () => {
- it('shows each agent’s presence, and access as a control for its manager', async () => {
+ it('shows access as a control for its manager, and leaves who is in the room to the side', async () => {
const el = await renderPanel();
- expect(el.textContent).toContain('reviewer-bot');
- expect(el.textContent).toContain('Here now');
expect(el.querySelector('[aria-label="Who can see and post"]')).not.toBeNull();
expect(el.textContent).toContain('C123');
+ expect(el.textContent).not.toContain('Notify on join');
});
- it('turns an agent’s join notification on', async () => {
- const el = await renderPanel();
- const toggle = el.querySelector<HTMLElement>(
- '[aria-label="Tell reviewer-bot when someone joins"]'
+ it('lists each agent with its presence in the side column, and adds from there', async () => {
+ const el = await renderPanel('side');
+ expect(el.textContent).toContain('reviewer-bot');
+ expect(el.textContent).toContain('Here now');
+ expect(el.querySelector('[aria-label="Add agents"]')).not.toBeNull();
+ expect(el.querySelector('[aria-label="Add people"]')).not.toBeNull();
+ });
+
+ it('turns an agent’s join notification on from its menu in the side column', async () => {
+ const el = await renderPanel('side');
+ await click(el.querySelector<HTMLElement>('[aria-label="reviewer-bot in this room"]')!);
+ const item = [...document.querySelectorAll<HTMLElement>('[role="menuitemcheckbox"]')].find(
+ (each) => /when someone joins/.test(each.textContent ?? '')
)!;
- await click(toggle);
+ await click(item);
expect(setRoomAgentJoinEvents).toHaveBeenCalledWith({
workspaceId: 'ws-1',
roomId: 'room-1',
@@ -227,4 +247,12 @@ describe('room settings for someone who may only read the room', () => {
expect(button(el, /^Archive$/)).toBeUndefined();
expect(el.querySelector<HTMLInputElement>('input[aria-label="Name"]')!.disabled).toBe(true);
});
+
+ it('lists who is in the room without adding or menus', async () => {
+ permissions.value = { canWrite: false, canManage: false };
+ const el = await renderPanel('side');
+ expect(el.textContent).toContain('reviewer-bot');
+ expect(el.querySelector('[aria-label="Add agents"]')).toBeNull();
+ expect(el.querySelector('[aria-label="reviewer-bot in this room"]')).toBeNull();
+ });
});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-configuration.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-configuration.test.ts
index 14817746c..a6f9bcc3d 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/chat-configuration.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-configuration.test.ts
@@ -7,9 +7,11 @@ import {
addAllToChat,
addLabel,
addToChat,
+ ChatAddParticipantPanel,
InviteHint,
- RoomConfigurationPanel,
-} from '@renderer/features/switch-rooms/room-configuration-panel';
+} from '@renderer/features/switch-rooms/room-add-participants';
+import { RoomConfigurationPanel } from '@renderer/features/switch-rooms/room-configuration-panel';
+import { RoomSidePanel } from '@renderer/features/switch-rooms/room-side-panel';
import type { ChatSummary } from '@shared/core/chats/chats';
import { RpcError } from '@shared/lib/ipc/rpc-error';
@@ -40,7 +42,7 @@ const agent = {
ownedByViewer: false,
};
-function render(canManage: boolean): string {
+function render(canManage: boolean, panel: 'side' | 'configuration' | 'add' = 'side'): string {
chat.current = {
roomId: 'r',
name: 'Planning',
@@ -64,43 +66,40 @@ function render(canManage: boolean): string {
createElement(
QueryClientProvider,
{ client },
- createElement(RoomConfigurationPanel, { roomId: 'r' })
+ panel === 'side'
+ ? createElement(RoomSidePanel, { roomId: 'r' })
+ : panel === 'configuration'
+ ? createElement(RoomConfigurationPanel, { roomId: 'r' })
+ : createElement(ChatAddParticipantPanel, {
+ serverId: 's',
+ workspaceId: null,
+ chat: chat.current,
+ memberIds: new Set(['u1', 'u2']),
+ onAddedPeople: () => {},
+ })
)
);
}
-describe('RoomConfigurationPanel for a group chat', () => {
- it('lists the chat’s agents and people, with add and remove for a manager', () => {
+describe('a group chat’s participant column', () => {
+ it('lists the chat’s agents and people, with adding and a menu per member for a manager', () => {
const html = render(true);
- expect(html).toContain('Planning');
expect(html).toContain('Helper');
- expect(html).toContain('1 agent · 2 people');
- expect(html).toContain('Add participants');
- expect(html).not.toMatch(/>\s*Add agent\s*</);
- expect(html).not.toContain('Add person');
- expect(html).not.toContain('From a template');
- expect(html).toContain('aria-label="Remove Helper"');
- expect(html).toContain('aria-label="Remove Bob"');
- expect(html).not.toContain('aria-label="Remove Alice"');
- });
-
- it('keeps the add field open under the header, above the cards, with the invite line under it', () => {
- const html = render(true);
- const field = html.indexOf('id="chat-add-participant"');
- expect(field).toBeGreaterThan(html.indexOf('Add participants'));
- expect(html.indexOf('Don&#x27;t see someone?')).toBeGreaterThan(field);
- expect(html.indexOf('aria-label="Remove Helper"')).toBeGreaterThan(field);
- // Nothing picked yet: Add sits beside the field, disabled.
- expect(html).toMatch(/<button[^>]* disabled=""[^>]*><span[^>]*>Add<span data-slot="shortcut"/);
+ expect(html).toContain('Bob');
+ expect(html).toContain('aria-label="Add participants"');
+ expect(html).not.toContain('aria-label="Add people"');
+ expect(html).toContain('aria-label="Helper in this room"');
+ expect(html).toContain('aria-label="Bob in this room"');
+ // The owner stays: there is no one to hand the chat to.
+ expect(html).not.toContain('aria-label="Alice in this room"');
});
it('offers no adding to a manager while the server does not offer group chats', () => {
flags.group_chats = false;
try {
const html = render(true);
- expect(html).not.toContain('Add participants');
- expect(html).not.toContain('id="chat-add-participant"');
- expect(html).toContain('aria-label="Remove Bob"');
+ expect(html).not.toContain('aria-label="Add participants"');
+ expect(html).toContain('aria-label="Bob in this room"');
} finally {
flags.group_chats = true;
}
@@ -109,11 +108,28 @@ describe('RoomConfigurationPanel for a group chat', () => {
it('shows the participants without controls to someone who cannot manage', () => {
const html = render(false);
expect(html).toContain('Bob');
- expect(html).not.toContain('Add participants');
+ expect(html).not.toContain('aria-label="Add participants"');
+ expect(html).not.toContain('in this room"');
+ });
+});
+
+describe('adding to a group chat', () => {
+ it('puts the invite line under the field, and holds Add until someone is picked', () => {
+ const html = render(true, 'add');
+ const field = html.indexOf('id="chat-add-participant"');
+ expect(field).toBeGreaterThan(-1);
+ expect(html.indexOf('Don&#x27;t see someone?')).toBeGreaterThan(field);
+ expect(html).toMatch(/<button[^>]* disabled=""[^>]*><span[^>]*>Add<span data-slot="shortcut"/);
+ });
+});
+
+describe('a group chat’s configuration', () => {
+ it('leaves who is in the chat to the participant column, and keeps Leave room', () => {
+ const html = render(false, 'configuration');
+ expect(html).toContain('Planning');
expect(html).not.toContain('id="chat-add-participant"');
// Leaving needs no manager rights.
expect(html).toContain('Leave room…');
- expect(html).not.toContain('aria-label="Remove');
});
});
@@ -140,10 +156,10 @@ describe('chatMembersQueryKey', () => {
});
describe('group chat people', () => {
- it('labels the owner and everyone else as a member', () => {
+ it('labels the owner, and nobody else', () => {
const html = render(false);
expect(html).toMatch(/Alice<\/span><span[^>]*>owner</);
- expect(html).toMatch(/Bob<\/span><span[^>]*>member</);
+ expect(html).not.toMatch(/Bob<\/span><span[^>]*>/);
expect(html).not.toContain('>person<');
});
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.ts
index b39cc0f08..154e382ba 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
@@ -1338,3 +1338,35 @@ export type MessagingAppInstall = {
/** Null while the install is still active. */
endedAt: string | null;
};
+
+/** The kinds of library item a room can have attached. */
+export type RoomResourceKind = 'references' | 'documents' | 'packages';
+
+/** A library item as a room lists it, or as the library offers it for attaching. */
+export type RoomResource = {
+ id: string;
+ kind: RoomResourceKind;
+ name: string;
+ description: string;
+ /** A reference's type as people read it ("GitHub"); null for anything else. */
+ typeLabel: string | null;
+ /** A reference's links; empty for anything else. */
+ urls: string[];
+ /** A document written in the room by one of its agents, rather than one from the library. */
+ roomScoped: boolean;
+ /** The agent that wrote a room-scoped document, when the server says. */
+ createdByAgentName: string | null;
+ /** The packages this came in with, by id: attached through them rather than on its own. */
+ packageIds: string[];
+};
+
+/** A document read in full, through the room it is attached to. */
+export type RoomDocumentContent = {
+ id: string;
+ name: string;
+ description: string;
+ content: string;
+};
+
+/** Another room this room points at, and why. */
+export type LinkedRoom = { roomId: string; name: string; description: string; label: string };